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";

export const CameraFeedProvider = ({ children }: { children: ReactNode }) => {
  const { blackboardMutation } = useBlackBoard();
  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();
  }, []);

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