import { useCameraFeedContext } from "../../../../../app/context/CameraFeedContext";
import SliderComponent from "../../../../../ui/SliderComponent";
import { useCameraZoom } from "../../../hooks/useCameraZoom";
import { useDebouncedCallback } from "use-debounce";

type CameraControlsProps = {
  cameraFeedID: "A" | "B" | "C";
};

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

  const zoomLevel = state.zoomLevel ? state.zoomLevel[cameraFeedID] : 1;
  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: value as number },
    });
    debouncedMutation(newZoom);
  };

  return (
    <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={1} max={3} step={0.1} />
      </div>
    </div>
  );
};

export default CameraControls;
