import { atom, useRecoilState } from 'recoil';

export const theme = atom({
  key: 'dark-theme',
  default: false,
});

export const useDarkTheme = () => {
  const [isDarkMode, setIsDarkMode] = useRecoilState(theme);

  const setDarkTheme = () => {
    document.documentElement.setAttribute('color-theme', 'dark');
    localStorage.setItem('theme', 'dark');
    setIsDarkMode(true);
  };

  const setLightTheme = () => {
    document.documentElement.setAttribute('color-theme', 'light');
    localStorage.setItem('theme', 'light');
    setIsDarkMode(false);
  };

  const setPreferTheme = () => {
    const isOsColorThemeDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    localStorage.removeItem('theme');
    document.documentElement.setAttribute('color-theme', isOsColorThemeDark ? 'dark' : 'light');
    setIsDarkMode(isOsColorThemeDark);
  };

  return {
    setDarkTheme,
    setLightTheme,
    setPreferTheme,
    isDarkMode,
  };
};
