import React, { createContext, useContext, useEffect, useState } from 'react';
import { ThemePreferences } from '@/lib/types';

interface ThemeContextType {
  theme: ThemePreferences;
  setTheme: (theme: Partial<ThemePreferences>) => void;
  resolvedMode: 'light' | 'dark';
}

const defaultTheme: ThemePreferences = {
  mode: 'dark',
  accentColor: 'blue',
  layoutMode: 'sidebar',
  density: 'comfortable',
};

// Accent color mappings for HSL values
const accentColorMap: Record<string, { hue: number; saturation: number; lightness: number }> = {
  blue: { hue: 220, saturation: 90, lightness: 56 },
  purple: { hue: 262, saturation: 83, lightness: 58 },
  green: { hue: 142, saturation: 76, lightness: 36 },
  orange: { hue: 38, saturation: 92, lightness: 50 },
  pink: { hue: 330, saturation: 81, lightness: 60 },
  teal: { hue: 168, saturation: 76, lightness: 42 },
};

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

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setThemeState] = useState<ThemePreferences>(() => {
    const stored = localStorage.getItem('crm-theme');
    return stored ? JSON.parse(stored) : defaultTheme;
  });

  const [resolvedMode, setResolvedMode] = useState<'light' | 'dark'>('dark');

  useEffect(() => {
    const updateResolvedMode = () => {
      if (theme.mode === 'system') {
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        setResolvedMode(prefersDark ? 'dark' : 'light');
      } else {
        setResolvedMode(theme.mode);
      }
    };

    updateResolvedMode();

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    mediaQuery.addEventListener('change', updateResolvedMode);
    return () => mediaQuery.removeEventListener('change', updateResolvedMode);
  }, [theme.mode]);

  // Apply theme mode class
  useEffect(() => {
    const root = document.documentElement;
    root.classList.remove('light', 'dark');
    root.classList.add(resolvedMode);
  }, [resolvedMode]);

  // Apply accent color CSS variables
  useEffect(() => {
    const root = document.documentElement;
    const accent = accentColorMap[theme.accentColor] || accentColorMap.blue;
    
    root.style.setProperty('--primary', `${accent.hue} ${accent.saturation}% ${accent.lightness}%`);
    root.style.setProperty('--ring', `${accent.hue} ${accent.saturation}% ${accent.lightness}%`);
    root.style.setProperty('--sidebar-primary', `${accent.hue} ${accent.saturation}% ${accent.lightness}%`);
    root.style.setProperty('--sidebar-ring', `${accent.hue} ${accent.saturation}% ${accent.lightness}%`);
  }, [theme.accentColor]);

  // Persist theme to localStorage
  useEffect(() => {
    localStorage.setItem('crm-theme', JSON.stringify(theme));
  }, [theme]);

  const setTheme = (newTheme: Partial<ThemePreferences>) => {
    setThemeState((prev) => ({ ...prev, ...newTheme }));
  };

  return (
    <ThemeContext.Provider value={{ theme, setTheme, resolvedMode }}>
      {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;
}
