import type { PaintedCell, Region } from "../../../../types/types";
import ColourPicker from "./ColourPicker";
import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext";

type RegionSelectorProps = {
  regions: Region[];
  selectedRegionIndex: number;
  mode: string;
  cameraFeedID: "A" | "B" | "C";
};

const RegionSelector = ({ regions, selectedRegionIndex, mode, cameraFeedID }: RegionSelectorProps) => {
  const { dispatch } = useCameraFeedContext();
  const handleChange = (e: { target: { value: string } }) => {
    dispatch({ type: "CHANGE_MODE", payload: { cameraFeedID: cameraFeedID, mode: e.target.value } });
  };

  const handleAddRegionClick = () => {
    const regionName = `Region ${regions.length + 1}`;
    dispatch({
      type: "ADD_NEW_REGION",
      payload: { cameraFeedID: cameraFeedID, regionName: regionName, brushColour: "#ffffff" },
    });
  };

  const handleResetRegion = () => {
    dispatch({
      type: "RESET_PAINTED_CELLS",
      payload: { cameraFeedID: cameraFeedID, paintedCells: new Map<string, PaintedCell>() },
    });
  };

  const handleRemoveClick = () => {
    dispatch({
      type: "REMOVE_REGION",
      payload: { cameraFeedID: cameraFeedID, regionName: regions[selectedRegionIndex].name },
    });
  };

  const handleModeChange = (newMode: string) => {
    dispatch({ type: "CHANGE_MODE", payload: { cameraFeedID: cameraFeedID, mode: newMode } });
  };

  const handleRegionSelect = (index: number) => {
    dispatch({ type: "SET_SELECTED_REGION_INDEX", payload: index });
  };

  const handleRegionColourChange = (index: number, newColour: string) => {
    const regionName = regions[index].name;

    dispatch({
      type: "SET_SELECTED_REGION_COLOUR",
      payload: { cameraFeedID: cameraFeedID, regionName: regionName, newColour: newColour },
    });
  };

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 md:grid-rows-2 gap-4">
      <div className="p-2 border border-gray-600 rounded-lg flex flex-col">
        <h2 className="text-2xl mb-2">Tools</h2>
        <div className="flex flex-col">
          <label
            htmlFor="paintMode"
            className={`p-4 border rounded-lg  mb-2
            ${mode === "painter" ? "border-gray-400 bg-[#202b36]" : "bg-[#253445] border-gray-700"}
            hover:bg-[#202b36] hover:cursor-pointer`}
          >
            <input
              id="paintMode"
              type="radio"
              onChange={handleChange}
              checked={mode === "painter"}
              value="painter"
              className="sr-only"
            />
            <span className="text-xl">Paint mode</span>
          </label>
          <label
            htmlFor="eraseMode"
            className={`p-4 border rounded-lg  mb-2
            ${mode === "eraser" ? "border-gray-400 bg-[#202b36]" : "bg-[#253445] border-gray-700"}
            hover:bg-[#202b36] hover:cursor-pointer`}
          >
            <input
              id="eraseMode"
              type="radio"
              onChange={handleChange}
              checked={mode === "eraser"}
              value={"eraser"}
              className="sr-only"
            />
            <span className="text-xl">Erase mode</span>
          </label>
        </div>
      </div>
      <div className="p-2 border border-gray-600 rounded-lg flex flex-col">
        <h2 className="text-2xl mb-2">Region Select</h2>
        <>
          {regions?.map((region, idx) => {
            const isSelected = selectedRegionIndex === idx;
            const inputId = `region-${idx}`;
            return (
              <label
                htmlFor={inputId}
                key={region.name}
                className={`items-center p-4 m-4 rounded-xl border flex flex-row justify-between
                  ${isSelected ? "border-gray-400 bg-[#202b36]" : "bg-[#253445] border-gray-700"} hover:bg-[#202b36] hover:cursor-pointer`}
              >
                <div className="flex flex-row gap-4 items-center">
                  <input
                    type="radio"
                    checked={isSelected}
                    id={inputId}
                    name="region"
                    className="sr-only"
                    onChange={() => {
                      handleModeChange("painter");
                      handleRegionSelect(idx);
                    }}
                  />
                  <span className="text-xl">{region.name}</span>
                </div>
                <ColourPicker colour={region.brushColour} setColour={(c: string) => handleRegionColourChange(idx, c)} />
                <p className="text-slate-400">{region.brushColour}</p>
              </label>
            );
          })}
        </>
        <div className=" mx-auto flex flex-row gap-4  mt-4">
          <button className="border border-blue-900 bg-blue-700 px-4 rounded-md" onClick={handleAddRegionClick}>
            Add Region
          </button>
          <button className="border border-red-900 px-4 rounded-md" onClick={handleRemoveClick}>
            Remove Region
          </button>
        </div>
      </div>

      <div className="p-2 border border-gray-600 rounded-lg flex flex-col md:col-span-2 h-50">
        <div className="flex flex-col">
          <h2 className="text-2xl mb-2">Actions</h2>
          <button
            onClick={handleResetRegion}
            className="mt-2 px-4 py-2 border border-red-600 rounded-md text-white bg-red-600 w-full md:w-[40%] hover:bg-red-700 hover:cursor-pointer"
          >
            Reset Region
          </button>
        </div>
      </div>
    </div>
  );
};

export default RegionSelector;
