import { createContext, useContext, useEffect, useState } from 'react';

type ColorMode = 'light' | 'dark';

const initialState = {
  colorMode: 'light' as ColorMode,
  setColorMode: (_mode: ColorMode) => {},
};

type ColorModeProviderProps = { children: React.ReactNode; defaultMode?: ColorMode; storageKey?: string };

const ColorModeContext = createContext(initialState);

export function ColorModeProvider(props: ColorModeProviderProps) {
  const { children, defaultMode = 'light', storageKey = 'officer-color-mode' } = props;
  const [colorMode, setColorModeState] = useState<ColorMode>(
    () => (localStorage.getItem(storageKey) as ColorMode) || defaultMode,
  );

  useEffect(() => {
    const root = window.document.documentElement;
    root.classList.remove('light', 'dark');
    root.classList.add(colorMode);
  }, [colorMode]);

  const setColorMode = (mode: ColorMode) => {
    localStorage.setItem(storageKey, mode);
    setColorModeState(mode);
  };

  return <ColorModeContext.Provider value={{ colorMode, setColorMode }}>{children}</ColorModeContext.Provider>;
}

export const useColorMode = () => {
  const context = useContext(ColorModeContext);

  if (context === undefined) throw new Error('useColorMode must be used within a ColorModeProvider');

  return context;
};
