import { useEffect, useReducer, useState, type ReactNode } from "react";
import type { DedupedSightings, ReducedSightingType } from "../../types/types";
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();
  const [sessionStarted, setSessionStarted] = useState(false);
  const [sessionList, setSessionList] = useState<ReducedSightingType[]>([]);
  const [sessionPaused, setSessionPaused] = useState(false);
  const [savedSightings, setSavedSightings] = useState<DedupedSightings | []>([]);

  useEffect(() => {
    const fetchData = async () => {
      const result = await mutation.mutateAsync({
        operation: "VIEW",
        path: "sessionStats",
      });
      if (!result.result) return;
      setSavedSightings(result?.result);
    };
    fetchData();
  }, []);

  return (
    <IntegrationsContext.Provider
      value={{
        setSessionStarted,
        sessionStarted,
        sessionList,
        setSessionList,
        sessionPaused,
        setSessionPaused,
        savedSightings,
        setSavedSightings,
        state,
        dispatch,
      }}
    >
      {children}
    </IntegrationsContext.Provider>
  );
};
