import { useEffect } from "react";
import type { CameraID } from "../../../../../app/config/cameraConfig";
import { useCameraFeedContext } from "../../../../../app/context/CameraFeedContext";
import SliderComponent from "../../../../../ui/SliderComponent";
import { useCameraZoom } from "../../../hooks/useCameraZoom";
import { useDebouncedCallback } from "use-debounce";

type CameraControlsProps = {
  cameraFeedID: CameraID;
  subTabIndex?: number;
};

const CameraControls = ({ cameraFeedID, subTabIndex }: CameraControlsProps) => {
  const { state, dispatch } = useCameraFeedContext();
  const { cameraZoomMutation, cameraZoomQuery } = useCameraZoom(cameraFeedID);

  const zoomLevel = state.zoomLevel ? state.zoomLevel[cameraFeedID] : 0;
  const currentZoomLevel = cameraZoomQuery.data ? cameraZoomQuery.data["propPhysCurrent"].value : 0;
  const minLevel = cameraZoomQuery.data ? cameraZoomQuery.data["propPhysMin"].value : 0;
  const maxLevel = cameraZoomQuery.data ? cameraZoomQuery.data["propPhysMax"].value : 0;

  const normalizedZoomLevel = ((currentZoomLevel - minLevel) / (maxLevel - minLevel)).toFixed(2);
  useEffect(() => {
    if (subTabIndex === 1) {
      dispatch({ type: "CHANGE_MODE", payload: { cameraFeedID, mode: "controller" } });
    }
  }, [cameraFeedID, dispatch, subTabIndex]);

  const debouncedMutation = useDebouncedCallback(async (value) => {
    await cameraZoomMutation.mutateAsync({
      cameraFeedID,
      zoomLevel: value as number,
    });
  }, 1000);

  const handleChange = (value: number | number[]) => {
    const newZoom = value as number;
    dispatch({
      type: "SET_ZOOM_LEVEL",
      payload: { cameraFeedID: cameraFeedID, zoomLevel: newZoom },
    });
    debouncedMutation(newZoom);
  };

  const handleOneShotClick = () => {
    debouncedMutation(normalizedZoomLevel);
  };

  return (
    <div>
      <div className="p-2 border border-gray-600 rounded-lg flex flex-col w-full mt-[5%]">
        <h2 className="text-2xl mb-4">Camera {cameraFeedID}</h2>
        <div className="w-[70%] ">
          <label htmlFor="zoom">Zoom {zoomLevel}</label>
          <SliderComponent id="zoom" onChange={handleChange} value={zoomLevel} min={0} max={1} step={0.1} />
        </div>
      </div>

      <div className="p-2 border border-gray-600 rounded-lg flex flex-col w-full mt-[5%]">
        <h2>One Shot</h2>
        <button
          type="button"
          className="p-2 bg-gray-500 rounded-xl w-[40%] mt-2 hover:bg-gray-700 cursor-pointer"
          onClick={handleOneShotClick}
        >
          One Shot
        </button>
      </div>
    </div>
  );
};

export default CameraControls;
