import { createContext, useCallback, useContext } from 'react';
import { useAtom } from 'jotai';
import { CallPreferences, CallPreferencesAtom } from '../callPreferences';

const CallPreferencesAtomContext = createContext<CallPreferencesAtom | null>(null);
export const CallPreferencesProvider = CallPreferencesAtomContext.Provider;

export const useCallPreferencesAtom = (): CallPreferencesAtom => {
  const atom = useContext(CallPreferencesAtomContext);
  if (!atom) {
    throw new Error('CallPreferencesAtom not provided!');
  }

  return atom;
};

export const useCallPreferences = (): CallPreferences & {
  toggleMicrophone: () => void;
  toggleVideo: () => void;
} => {
  const callPrefAtom = useCallPreferencesAtom();
  const [pref, setPref] = useAtom(callPrefAtom);

  const toggleMicrophone = useCallback(() => {
    setPref({
      microphone: !pref.microphone,
      video: pref.video,
    });
  }, [setPref, pref]);

  const toggleVideo = useCallback(() => {
    setPref({
      microphone: pref.microphone,
      video: !pref.video,
    });
  }, [setPref, pref]);

  return {
    ...pref,
    toggleMicrophone,
    toggleVideo,
  };
};
