import { useEffect, useReducer, type ReactNode } from "react";
import AlertHitContext from "../AlertHitContext";
import { reducer, initalState } from "../reducers/AlertReducers";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
import type { SightingType } from "../../types/types";

type AlertHitProviderTypeProps = {
  children: ReactNode;
};

export const AlertHitProvider = ({ children }: AlertHitProviderTypeProps) => {
  const [state, dispatch] = useReducer(reducer, initalState);
  const { query } = useCameraBlackboard();

  useEffect(() => {
    if (query.data) {
      query?.data?.alertHistory?.forEach((element: SightingType) => {
        dispatch({ type: "ADD", payload: element });
      });
    }
  }, [query.data, query.error, query.isLoading]);

  return (
    <AlertHitContext.Provider
      value={{
        state,
        dispatch,
        isLoading: query.isLoading,
        isError: query.isError,
        error: query.error,
      }}
    >
      {children}
    </AlertHitContext.Provider>
  );
};

export default AlertHitProvider;
