import React, { useState } from 'react';
import { Form } from 'react-bootstrap';
import { getColor } from '../../../../util/colorModule';
import { useSelector } from 'react-redux';

const SelectTubeAndFiber = ({
  tubes,
  setCableMap,
  currentTube,
  currentFiber,
}) => {
  const [tube, setTube] = useState(null);

  const onTubeChangeHandler = (e) => {
    if (isNaN(e.target.value)) return;
    setTube(parseInt(e.target.value));
  };

  const onFiberChangeHandler = (e) => {
    if (isNaN(e.target.value)) return;
    const fiber = parseInt(e.target.value);
    setCableMap((prev) => {
      const newCableMap = [...prev];
      const tubeIndex = newCableMap.findIndex(
        (tube) => tube.tube_number === currentTube
      );
      const fiberIndex = newCableMap[tubeIndex].fibers.findIndex(
        (fiber) => fiber.fiber_number === currentFiber
      );
      newCableMap[tubeIndex].fibers[fiberIndex].parent_fiber_id = fiber;
      return newCableMap;
    });
  };

  return (
    <>
      <td>
        <Form.Select onChange={onTubeChangeHandler}>
          <option value='none'>None</option>
          {tubes.map((tube) => (
            <option value={tube.tube_number} key={tube.id}>
              {tube.tube_number}:{tube.id} ({getColor(tube.tube_number)})
            </option>
          ))}
        </Form.Select>
      </td>
      <td>
        <Form.Select onChange={onFiberChangeHandler}>
          <option value='none'>None</option>
          {tube &&
            tubes[tube - 1].fibers.map((fiber) => (
              <option value={fiber.id} key={fiber.id}>
                {fiber.fiber_number}:{fiber.id} ({getColor(fiber.fiber_number)}){' '}
                {fiber.child_fiber_id && 'used'}
              </option>
            ))}
        </Form.Select>
      </td>
    </>
  );
};

const CableMappingRow = ({ tube, setCableMap }) => {
  const { startNode } = useSelector((state) => state.coordinatesReducer);
  return tube.fibers.map((fiber) => {
    return (
      <tr key={fiber.fiber_number}>
        <td>
          <Form.Control
            value={tube.tube_number + ` (${getColor(tube.tube_number)})`}
            disabled
          />
        </td>
        <td>
          <Form.Control
            value={fiber.fiber_number + ` (${getColor(fiber.fiber_number)})`}
            disabled
          />
        </td>
        <SelectTubeAndFiber
          tubes={startNode.tubes}
          setCableMap={setCableMap}
          currentTube={tube.tube_number}
          currentFiber={fiber.fiber_number}
        />
      </tr>
    );
  });
};

export default CableMappingRow;
