import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Sun, Moon } from 'lucide-react';

// ── TYPES ──────────────────────────────────────────────
type Theme = 'light' | 'dark';

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

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

// ── TOKENS CSS PAR THÈME ──────────────────────────────
const THEMES = {
    light: {
        // Backgrounds
        '--bg-app': '#f1f5f9',
        '--bg-main': '#ffffff',
        '--bg-card': '#ffffff',
        '--bg-input': '#f8fafc',
        '--bg-input-sm': '#ffffff',
        '--bg-hover': '#f8fafc',
        '--bg-thead': '#f8fafc',
        '--bg-row-hover': '#f8fafc',
        '--bg-notif-unread': '#f0f9ff',
        '--bg-sidebar': 'linear-gradient(160deg,#6366f1 0%,#4f46e5 100%)',

        // Borders
        '--border-main': '#e2e8f0',
        '--border-input': '#e2e8f0',
        '--border-card': '#e2e8f0',
        '--border-divider': '#f1f5f9',

        // Text
        '--text-primary': '#0f172a',
        '--text-secondary': '#64748b',
        '--text-muted': '#94a3b8',
        '--text-heading': '#0f172a',

        // Shadows
        '--shadow-card': '0 1px 3px rgba(0,0,0,.06), 0 4px 16px rgba(0,0,0,.04)',
        '--shadow-notif': '0 8px 32px rgba(0,0,0,.12)',

        // Stat cards
        '--stat-bg': '#ffffff',

        // Header
        '--header-bg': 'transparent',
        '--header-btn-bg': '#ffffff',
        '--header-btn-border': '#e2e8f0',
    },
    dark: {
        // Backgrounds
        '--bg-app': '#0f172a',
        '--bg-main': '#1e293b',
        '--bg-card': '#1e293b',
        '--bg-input': '#0f172a',
        '--bg-input-sm': '#0f172a',
        '--bg-hover': '#334155',
        '--bg-thead': '#0f172a',
        '--bg-row-hover': '#0f172a',
        '--bg-notif-unread': '#1e3a5f',
        '--bg-sidebar': 'linear-gradient(160deg,#312e81 0%,#1e1b4b 100%)',

        // Borders
        '--border-main': '#334155',
        '--border-input': '#334155',
        '--border-card': '#334155',
        '--border-divider': '#1e293b',

        // Text
        '--text-primary': '#f1f5f9',
        '--text-secondary': '#94a3b8',
        '--text-muted': '#64748b',
        '--text-heading': '#f8fafc',

        // Shadows
        '--shadow-card': '0 1px 3px rgba(0,0,0,.3), 0 4px 16px rgba(0,0,0,.2)',
        '--shadow-notif': '0 8px 32px rgba(0,0,0,.5)',

        // Stat cards
        '--stat-bg': '#1e293b',

        // Header
        '--header-bg': 'transparent',
        '--header-btn-bg': '#1e293b',
        '--header-btn-border': '#334155',
    },
};

// ── INJECTION CSS VARIABLES ───────────────────────────
function applyTheme(theme: Theme) {
    const root = document.documentElement;
    const tokens = THEMES[theme];
    Object.entries(tokens).forEach(([key, val]) => {
        root.style.setProperty(key, val);
    });
    root.setAttribute('data-theme', theme);
}

// ── PROVIDER ──────────────────────────────────────────
export const ThemeProvider = ({ children }: { children: ReactNode }) => {
    const [theme, setTheme] = useState<Theme>(() => {
        const saved = localStorage.getItem('theme') as Theme | null;
        if (saved === 'light' || saved === 'dark') return saved;
        // Détecte la préférence système
        return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    });

    // Applique les tokens au montage et à chaque changement
    useEffect(() => {
        applyTheme(theme);
        localStorage.setItem('theme', theme);
    }, [theme]);

    const toggleTheme = () => setTheme(t => t === 'light' ? 'dark' : 'light');
    const isDark = theme === 'dark';

    return (
        <ThemeContext.Provider value={{ theme, toggleTheme, isDark }}>
            {children}
        </ThemeContext.Provider>
    );
};

// ── HOOK ──────────────────────────────────────────────
export const useTheme = () => {
    const ctx = useContext(ThemeContext);
    if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
    return ctx;
};

// ── BOUTON TOGGLE (réutilisable partout) ──────────────
export const ThemeToggleButton = ({ style }: { style?: React.CSSProperties }) => {
    const { toggleTheme, isDark } = useTheme();

    return (
        <button
            onClick={toggleTheme}
            title={isDark ? 'Passer en mode clair' : 'Passer en mode sombre'}
            style={{
                background: 'var(--header-btn-bg)',
                border: '1px solid var(--header-btn-border)',
                borderRadius: 10,
                width: 40, height: 40,
                cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: 'var(--text-secondary)',
                transition: 'all 0.2s',
                flexShrink: 0,
                ...style,
            }}
        >
            {isDark
                ? <Sun size={18} color="#fbbf24" />
                : <Moon size={18} color="#6366f1" />
            }
        </button>
    );
};