import { useEffect, useMemo, useReducer, type ReactNode } from "react";
import { SoundContext } from "../SoundContext";
import { initialState, reducer } from "../reducers/SoundContextReducer";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";

type SoundContextProviderProps = {
  children: ReactNode;
};

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

  useEffect(() => {
    const fetchSound = async () => {
      const result = await mutation.mutateAsync({
        operation: "VIEW",
        path: "soundSettings",
      });

      dispatch({ type: "UPDATE", payload: result.result });
    };
    fetchSound();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const value = useMemo(() => ({ state, dispatch }), [state, dispatch]);
  return (
    <SoundContext.Provider value={value}>{children}</SoundContext.Provider>
  );
};

export default SoundContextProvider;
