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

type IntegrationsProviderType = {
  children: ReactNode;
};

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

  useEffect(() => {
    let isMounted = true;

    const fetchData = async () => {
      try {
        await mutation.mutateAsync({
          operation: "Load",
          path: "",
          value: null,
        });
        const result = await mutation.mutateAsync({
          operation: "VIEW",
          path: "sessionStats",
        });

        if (!isMounted) return;

        const catResult = await mutation.mutateAsync({
          operation: "VIEW",
          path: "CategoryPopup",
        });

        if (!isMounted) return;
        if (!result?.result || typeof result.result === "string") return;

        dispatch({ type: "UPDATE", payload: result.result });
        dispatch({ type: "NPEDCATENABLED", payload: catResult.result });
      } catch (error) {
        console.error("Error in fetchData:", error);
      }
    };

    fetchData();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    const fetchHotlistData = async () => {
      dispatch({ type: "SETHOTLISTS", payload: query?.data?.hotlists });
    };
    fetchHotlistData();
  }, [query?.data]);

  return (
    <IntegrationsContext.Provider
      value={{
        state,
        dispatch,
      }}
    >
      {children}
    </IntegrationsContext.Provider>
  );
};
