import { useState, useEffect, useCallback, createContext, useContext, ReactNode, useRef } from 'react';
import { usePage } from '@inertiajs/react';
import { SharedData, SidebarThemeColors, SidebarTheme } from '@/types';

interface SidebarThemeContextType {
    theme: SidebarTheme | null;
    isLoading: boolean;
    refreshTheme: () => Promise<void>;
}

const SidebarThemeContext = createContext<SidebarThemeContextType | null>(null);

const THEME_STORAGE_KEY = 'sidebar_theme';

// Check if theme should respect system light/dark mode
export function shouldRespectSystemTheme(themeKey: string): boolean {
    return themeKey === 'default' || themeKey === 'dark';
}

// Apply theme colors to CSS variables - only for fixed themes (not default/dark)
export function applySidebarTheme(colors: SidebarThemeColors, respectsSystemTheme: boolean = false) {
    if (typeof document === 'undefined') return;

    const root = document.documentElement;

    // If theme respects system theme (default/dark), don't apply inline styles
    // Let the CSS handle it via light/dark mode classes
    if (respectsSystemTheme) {
        // Remove inline styles so CSS can take over
        root.style.removeProperty('--sidebar-background');
        root.style.removeProperty('--sidebar-foreground');
        root.style.removeProperty('--sidebar-primary');
        root.style.removeProperty('--sidebar-primary-foreground');
        root.style.removeProperty('--sidebar-accent');
        root.style.removeProperty('--sidebar-accent-foreground');
        root.style.removeProperty('--sidebar-border');
        root.style.removeProperty('--sidebar-ring');
        root.style.removeProperty('--sidebar');
        root.removeAttribute('data-custom-sidebar-theme');
        return;
    }

    // For fixed themes (forest, sunset, etc.), apply inline styles to override dark mode
    root.style.setProperty('--sidebar-background', colors.background);
    root.style.setProperty('--sidebar-foreground', colors.foreground);
    root.style.setProperty('--sidebar-primary', colors.primary);
    root.style.setProperty('--sidebar-primary-foreground', '#ffffff');
    root.style.setProperty('--sidebar-accent', colors.accent);
    root.style.setProperty('--sidebar-accent-foreground', colors.accentForeground || colors.foreground);
    root.style.setProperty('--sidebar-border', colors.border);
    root.style.setProperty('--sidebar-ring', colors.primary);

    // Also set the standard sidebar variables
    root.style.setProperty('--sidebar', colors.background);
    root.style.setProperty('--sidebar-foreground', colors.foreground);
    root.style.setProperty('--sidebar-primary', colors.primary);
    root.style.setProperty('--sidebar-accent', colors.accent);
    root.style.setProperty('--sidebar-border', colors.border);
    root.style.setProperty('--sidebar-ring', colors.primary);

    if (colors.accentForeground) {
        root.style.setProperty('--sidebar-accent-foreground', colors.accentForeground);
    }

    // Mark that custom theme is active
    root.setAttribute('data-custom-sidebar-theme', 'true');
}

// Default theme colors
export const defaultSidebarTheme: SidebarThemeColors = {
    background: '#ffffff',
    foreground: '#09090b',
    primary: '#424d61',
    accent: '#1e242f',
    accentForeground: '#09090b',
    border: '#e4e4e7',
};

// Hook untuk menggunakan tema sidebar
export function useSidebarTheme() {
    const { sidebarTheme: inertiaTheme } = usePage<SharedData>().props;
    const [theme, setTheme] = useState<SidebarTheme | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const initialized = useRef(false);

    const refreshTheme = useCallback(async () => {
        setIsLoading(true);
        try {
            // Fetch from API to get latest theme
            const response = await fetch('/api/theme');
            if (response.ok) {
                const themeData: SidebarTheme = await response.json();
                setTheme(themeData);
                applySidebarTheme(themeData.colors, themeData.respectsSystemTheme);
                localStorage.setItem(THEME_STORAGE_KEY, JSON.stringify(themeData));
            }
        } catch (error) {
            console.error('Error refreshing theme:', error);
        } finally {
            setIsLoading(false);
        }
    }, []);

    useEffect(() => {
        // Priority 1: Use Inertia props if available (from HandleInertiaRequests)
        if (inertiaTheme?.colors) {
            setTheme(inertiaTheme);
            applySidebarTheme(inertiaTheme.colors, inertiaTheme.respectsSystemTheme);
            localStorage.setItem(THEME_STORAGE_KEY, JSON.stringify(inertiaTheme));
            setIsLoading(false);
            initialized.current = true;
            return;
        }

        // Priority 2: Try localStorage for instant render
        const stored = localStorage.getItem(THEME_STORAGE_KEY);
        if (stored) {
            try {
                const parsed: SidebarTheme = JSON.parse(stored);
                setTheme(parsed);
                applySidebarTheme(parsed.colors, parsed.respectsSystemTheme);
                initialized.current = true;
            } catch {
                // Invalid stored data
            }
        }

        // Priority 3: Use default theme
        if (!initialized.current) {
            const defaultTheme: SidebarTheme = {
                theme: 'default',
                colors: defaultSidebarTheme,
                respectsSystemTheme: true
            };
            setTheme(defaultTheme);
            applySidebarTheme(defaultSidebarTheme, true);
            initialized.current = true;
        }

        setIsLoading(false);
    }, [inertiaTheme]);

    return { theme, isLoading, refreshTheme };
}

// Provider component untuk sidebar theme
export function SidebarThemeProvider({ children }: { children: ReactNode }) {
    const themeData = useSidebarTheme();

    return (
        <SidebarThemeContext.Provider value={themeData}>
            {children}
        </SidebarThemeContext.Provider>
    );
}

// Hook untuk mengakses context
export function useSidebarThemeContext() {
    const context = useContext(SidebarThemeContext);
    if (!context) {
        throw new Error('useSidebarThemeContext must be used within SidebarThemeProvider');
    }
    return context;
}

// Initialize theme on app load
export function initializeSidebarTheme() {
    if (typeof window === 'undefined') return;

    const stored = localStorage.getItem(THEME_STORAGE_KEY);
    if (stored) {
        try {
            const parsed: SidebarTheme = JSON.parse(stored);
            applySidebarTheme(parsed.colors, parsed.respectsSystemTheme);
        } catch {
            // Invalid stored data - use default which respects system theme
            applySidebarTheme(defaultSidebarTheme, true);
        }
    }
}

// Theme presets untuk reference di frontend
export const sidebarThemePresets: Record<string, { name: string; description: string; respectsSystemTheme?: boolean; colors: SidebarThemeColors }> = {
    default: {
        name: 'Default Light',
        description: 'Clean white sidebar - follows system light/dark mode',
        respectsSystemTheme: true,
        colors: {
            background: '#ffffff',
            foreground: '#09090b',
            primary: '#000000ff',
            accent: '#f4f4f5',
            accentForeground: '#09090b',
            border: '#e4e4e7',
        },
    },
    dark: {
        name: 'Dark Modern',
        description: 'Modern dark sidebar - follows system light/dark mode',
        respectsSystemTheme: true,
        colors: {
            background: '#09090b',
            foreground: '#fafafa',
            primary: '#fcfdfdff',
            accent: '#27272a',
            accentForeground: '#fafafa',
            border: '#27272a',
        },
    },
    adminlte_blue: {
        name: 'AdminLTE Blue',
        description: 'Classic AdminLTE blue theme - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#343a40',
            foreground: '#c2c7d0',
            primary: '#007bff',
            accent: '#494e53',
            border: '#4b545c',
        },
    },
    adminlte_dark: {
        name: 'AdminLTE Dark',
        description: 'Dark AdminLTE theme - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#212529',
            foreground: '#dee2e6',
            primary: '#17a2b8',
            accent: '#2c3035',
            border: '#373b3e',
        },
    },
    midnight: {
        name: 'Midnight Blue',
        description: 'Deep blue professional - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#0f172a',
            foreground: '#e2e8f0',
            primary: '#3b82f6',
            accent: '#1e293b',
            border: '#334155',
        },
    },
    purple_dream: {
        name: 'Purple Dream',
        description: 'Elegant purple theme - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#2e1065',
            foreground: '#faf5ff',
            primary: '#a855f7',
            accent: '#4c1d95',
            border: '#5b21b6',
        },
    },
    forest: {
        name: 'Forest Green',
        description: 'Natural green theme - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#064e3b',
            foreground: '#ecfdf5',
            primary: '#10b981',
            accent: '#065f46',
            border: '#047857',
        },
    },
    sunset: {
        name: 'Sunset Orange',
        description: 'Warm orange theme - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#7c2d12',
            foreground: '#fff7ed',
            primary: '#f97316',
            accent: '#9a3412',
            border: '#c2410c',
        },
    },
    ocean: {
        name: 'Ocean Teal',
        description: 'Calm teal theme - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#134e4a',
            foreground: '#f0fdfa',
            primary: '#14b8a6',
            accent: '#115e59',
            border: '#0f766e',
        },
    },
    rose: {
        name: 'Rose Pink',
        description: 'Elegant rose theme - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#881337',
            foreground: '#fff1f2',
            primary: '#f43f5e',
            accent: '#9f1239',
            border: '#be123c',
        },
    },
    slate: {
        name: 'Slate Gray',
        description: 'Professional slate gray - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#334155',
            foreground: '#f8fafc',
            primary: '#64748b',
            accent: '#475569',
            border: '#52647b',
        },
    },
    indigo: {
        name: 'Indigo Night',
        description: 'Deep indigo theme - fixed colors',
        respectsSystemTheme: false,
        colors: {
            background: '#312e81',
            foreground: '#eef2ff',
            primary: '#6366f1',
            accent: '#4338ca',
            border: '#4f46e5',
        },
    },
};
