import { memo, useEffect } from 'react';
import { Badge } from 'react-bootstrap';
import { MdKeyboardArrowRight } from 'react-icons/md';
import _ from 'lodash';
import { getFiberInfo } from '../../../../../util/colorModule';

const FiberTractView = ({ fiber, parent, setComponents }) => {
    let currentFiber = fiber;
    let fiberTract = [];
    while (currentFiber) {
        fiberTract.push(currentFiber);
        currentFiber = parent
            ? currentFiber.parent_fiber
            : currentFiber.child_fiber;
    }
    useEffect(() => {
        if (fiberTract.length === 0) return;
        if (parent) {
            setComponents((prevState) => {
                return {
                    ...prevState,
                    startNode:
                        fiberTract[fiberTract.length - 1].parent_component,
                };
            });
        } else {
            setComponents((prevState) => {
                return {
                    ...prevState,
                    endNode: fiberTract[fiberTract.length - 1].child_component,
                };
            });
        }
    }, [fiberTract, setComponents, parent]);

    if (fiberTract.length === 0) {
        return null;
    }

    const fiberTractComponent = fiberTract.map((fiber) => {
        const { number, color: colorName } = getFiberInfo(fiber.fiber_number);
        const color = _.capitalize(colorName);

        return (
            <Badge bg='primary' key={fiber.id}>
                {fiber.cable.name}: ({number}: {color})
            </Badge>
        );
    });

    return parent
        ? fiberTractComponent
              .reverse()
              .reduce((prev, curr) => [
                  prev,
                  <MdKeyboardArrowRight className='text-white' key={curr.id} />,
                  curr,
              ])
        : fiberTractComponent.reduce((prev, curr) => [
              prev,
              <MdKeyboardArrowRight className='text-white' key={curr.id} />,
              curr,
          ]);
};

const MemoizedFiberTractView = memo(FiberTractView);
export default MemoizedFiberTractView;
