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

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

interface ThemeContextType {
  theme: Theme;
  toggleTheme: () => void;
  setTheme: (theme: Theme) => void;
  setThemeMode: (theme: Theme) => void;
  isDark: boolean;
  disableDarkMode: boolean;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

interface ThemeProviderProps {
  children: React.ReactNode;
  defaultTheme?: Theme;
  disableDarkMode?: boolean;
  storageKey?: string;
}

export function ThemeProvider({
  children,
  disableDarkMode = false,
  defaultTheme,
  storageKey = 'xertica-theme',
}: ThemeProviderProps) {
  const getInitialTheme = (): Theme => {
    if (disableDarkMode) return 'light';
    if (defaultTheme) return defaultTheme;
    if (typeof window !== 'undefined') {
      const savedTheme = window.localStorage?.getItem(storageKey) as Theme;
      if (savedTheme && (savedTheme === 'light' || savedTheme === 'dark')) {
        return savedTheme;
      }
      if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        return 'dark';
      }
    }
    return 'light';
  };

  const [theme, setThemeState] = useState<Theme>(getInitialTheme);

  useEffect(() => {
    if (disableDarkMode && theme === 'dark') {
      setThemeState('light');
    }
  }, [disableDarkMode, theme]);

  useEffect(() => {
    if (typeof document === 'undefined') return;
    const root = document.documentElement;
    root.classList.remove('light', 'dark');

    if (theme === 'dark') {
      root.classList.add('dark');
    } else {
      root.classList.add('light');
    }

    if (typeof window !== 'undefined') {
      window.localStorage?.setItem(storageKey, theme);
    }
  }, [theme, storageKey]);

  useEffect(() => {
    if (disableDarkMode) return;
    if (typeof window === 'undefined' || !window.matchMedia) return;
    if (!window.localStorage?.getItem(storageKey)) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
      const handleChange = (e: MediaQueryListEvent) => {
        setThemeState(e.matches ? 'dark' : 'light');
      };
      mediaQuery.addEventListener('change', handleChange);
      return () => mediaQuery.removeEventListener('change', handleChange);
    }
  }, [disableDarkMode, storageKey]);

  const toggleTheme = () => {
    if (disableDarkMode) return;
    setThemeState(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
  };

  const setTheme = (newTheme: Theme) => {
    if (disableDarkMode && newTheme === 'dark') return;
    setThemeState(newTheme);
  };

  const setThemeMode = setTheme;

  const value: ThemeContextType = {
    theme,
    toggleTheme,
    setTheme,
    setThemeMode,
    isDark: theme === 'dark',
    disableDarkMode,
  };

  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}

export function useTheme() {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
}
