import { useEffect, useReducer, type ReactNode } from "react";
import { CameraFeedContext } from "../context/CameraFeedContext";
import { initialState, reducer } from "../reducers/cameraFeedReducer";
import { useBlackBoard } from "../../hooks/useBlackBoard";
import type { CameraFeedState } from "../../types/types";
import { useCameraZoom } from "../../features/cameras/hooks/useCameraZoom";

export const CameraFeedProvider = ({ children }: { children: ReactNode }) => {
  const { blackboardMutation } = useBlackBoard();
  const { cameraZoomQuery: cameraZoomQueryA } = useCameraZoom("A");
  const { cameraZoomQuery: cameraZoomQueryB } = useCameraZoom("B");
  const { cameraZoomQuery: cameraZoomQueryC } = useCameraZoom("C");

  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    const fetchBlackBoardData = async () => {
      const result = await blackboardMutation.mutateAsync({
        operation: "VIEW",
        path: "cameraFeed",
      });
      if (!result?.result || typeof result.result === "string") return;
      const cameraFeedData: CameraFeedState = result.result;
      const recontructedState = {
        ...cameraFeedData,
        paintedCells: {
          A: new Map(cameraFeedData.paintedCells.A),
          B: new Map(cameraFeedData.paintedCells.B),
          C: new Map(cameraFeedData.paintedCells.C),
        },
      };
      dispatch({ type: "SET_CAMERA_FEED_DATA", cameraState: recontructedState });
    };
    fetchBlackBoardData();
  }, []);

  useEffect(() => {
    const fetchZoomLevels = async () => {
      const [resultA, resultB, resultC] = await Promise.all([
        cameraZoomQueryA.refetch(),
        cameraZoomQueryB.refetch(),
        cameraZoomQueryC.refetch(),
      ]);

      console.log(resultA?.data);
      const zoomLevelAnumber = parseFloat(resultA.data?.propPhysCurrent?.value);
      const zoomLevelBnumber = parseFloat(resultB.data?.propPhysCurrent?.value);
      const zoomLevelCnumber = parseFloat(resultC.data?.propPhysCurrent?.value);

      if (resultA.data) {
        dispatch({
          type: "SET_ZOOM_LEVEL",
          payload: { cameraFeedID: "A", zoomLevel: zoomLevelAnumber },
        });
      }

      if (resultB.data) {
        dispatch({
          type: "SET_ZOOM_LEVEL",
          payload: { cameraFeedID: "B", zoomLevel: zoomLevelBnumber },
        });
      }

      if (resultC.data) {
        dispatch({
          type: "SET_ZOOM_LEVEL",
          payload: { cameraFeedID: "C", zoomLevel: zoomLevelCnumber },
        });
      }
    };
    fetchZoomLevels();
  }, []);

  return <CameraFeedContext.Provider value={{ state, dispatch }}>{children}</CameraFeedContext.Provider>;
};
