import { useState, useEffect } from 'react';

export type Theme = 'light' | 'dark' | 'system';

export const useTheme = () => {
  const [theme, setTheme] = useState<Theme>(() => {
    return (localStorage.getItem('theme') as Theme) || 'system';
  });

  const applyTheme = (currentTheme: Theme) => {
    const root = document.documentElement;
    root.classList.remove('light', 'dark');

    if (currentTheme === 'dark') {
      root.classList.add('dark');
      root.style.colorScheme = 'dark';
    } else if (currentTheme === 'light') {
      root.classList.add('light');
      root.style.colorScheme = 'light';
    } else {
      // System
      const systemIsDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      if (systemIsDark) {
        root.classList.add('dark');
        root.style.colorScheme = 'dark';
      } else {
        root.classList.add('light');
        root.style.colorScheme = 'light';
      }
    }
  };

  const changeTheme = (newTheme: Theme) => {
    localStorage.setItem('theme', newTheme);
    setTheme(newTheme);
    applyTheme(newTheme);
    window.dispatchEvent(new Event('themeChange'));
  };

  useEffect(() => {
    applyTheme(theme);

    // Listen for system theme changes if theme is set to 'system'
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleSystemThemeChange = () => {
      if (localStorage.getItem('theme') === 'system' || !localStorage.getItem('theme')) {
        applyTheme('system');
      }
    };

    mediaQuery.addEventListener('change', handleSystemThemeChange);
    
    const handleStorageChange = () => {
      const storedTheme = (localStorage.getItem('theme') as Theme) || 'system';
      setTheme(storedTheme);
      applyTheme(storedTheme);
    };

    window.addEventListener('themeChange', handleStorageChange);

    return () => {
      mediaQuery.removeEventListener('change', handleSystemThemeChange);
      window.removeEventListener('themeChange', handleStorageChange);
    };
  }, [theme]);

  return { theme, changeTheme };
};
