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 { CAMERA_IDS } from "../config/cameraConfig";
import CameraZoomFetcher from "./CameraZoomFetcher";

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: CAMERA_IDS.reduce(
          (acc, id) => {
            acc[id] = new Map(cameraFeedData.paintedCells[id]);
            return acc;
          },
          {} as typeof cameraFeedData.paintedCells,
        ),
      };
      dispatch({ type: "SET_CAMERA_FEED_DATA", cameraState: recontructedState });
    };
    fetchBlackBoardData();
  }, []);

  return (
    <CameraFeedContext.Provider value={{ state, dispatch }}>
      {CAMERA_IDS.map((cameraId) => (
        <CameraZoomFetcher key={cameraId} cameraId={cameraId} dispatch={dispatch} />
      ))}
      {children}
    </CameraFeedContext.Provider>
  );
};
