import { useEffect, useReducer, useState, type ReactNode } from "react";
import type { DedupedSightings, NPEDUser, ReducedSightingType } from "../../types/types";
import { NPEDUserContext } from "../NPEDUserContext";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
import { initialState, reducer } from "../reducers/NPEDContextReducer";

type NPEDUserProviderType = {
  children: ReactNode;
};

export const NPEDUserProvider = ({ children }: NPEDUserProviderType) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const { mutation } = useCameraBlackboard();
  const [user, setUser] = useState<NPEDUser | null>(null);
  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();
  }, []);
  console.log(savedSightings);
  return (
    <NPEDUserContext.Provider
      value={{
        user,
        setUser,
        setSessionStarted,
        sessionStarted,
        sessionList,
        setSessionList,
        sessionPaused,
        setSessionPaused,
        savedSightings,
        setSavedSightings,
      }}
    >
      {children}
    </NPEDUserContext.Provider>
  );
};
