import { useEffect, useReducer, type ReactNode } from "react";
import { IntegrationsContext } from "../IntegrationsContext";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
import { initialState, reducer } from "../reducers/IntegrationsContextReducer";

type IntegrationsProviderType = {
  children: ReactNode;
};

export const IntegrationsProvider = ({ children }: IntegrationsProviderType) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const { mutation } = useCameraBlackboard();

  useEffect(() => {
    const fetchData = async () => {
      const result = await mutation.mutateAsync({
        operation: "VIEW",
        path: "sessionStats",
      });
      if (!result.result || typeof result.result === "string") return;

      dispatch({ type: "UPDATE", payload: result?.result });
    };
    fetchData();
  }, []);
  return (
    <IntegrationsContext.Provider
      value={{
        state,
        dispatch,
      }}
    >
      {children}
    </IntegrationsContext.Provider>
  );
};
