import React, { useState, useEffect } from 'react';
import { Head, router } from '@inertiajs/react';
import AdminLayout from '@/Admin/Layouts/AdminLayout'; 
import SettingsLayout from '@/Admin/Layouts/SettingsLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Label } from "@/Components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/Components/ui/radio-group";
import { Loader2, Save, Palette, Monitor, Moon, Sun, RotateCcw } from 'lucide-react';
import axios from 'axios';
import { toast } from 'sonner';

// --- Color Conversion Utilities ---
function hslToHex(h, sStr, lStr) {
    let s = parseFloat(sStr) / 100;
    let l = parseFloat(lStr) / 100;
    let c = (1 - Math.abs(2 * l - 1)) * s, x = c * (1 - Math.abs((h / 60) % 2 - 1)), m = l - c / 2, r = 0, g = 0, b = 0;
    if (0 <= h && h < 60) { r = c; g = x; b = 0; } else if (60 <= h && h < 120) { r = x; g = c; b = 0; } else if (120 <= h && h < 180) { r = 0; g = c; b = x; } else if (180 <= h && h < 240) { r = 0; g = x; b = c; } else if (240 <= h && h < 300) { r = x; g = 0; b = c; } else if (300 <= h && h < 360) { r = c; g = 0; b = x; }
    r = Math.round((r + m) * 255).toString(16).padStart(2, '0');
    g = Math.round((g + m) * 255).toString(16).padStart(2, '0');
    b = Math.round((b + m) * 255).toString(16).padStart(2, '0');
    return `#${r}${g}${b}`;
}

function hexToHSL(H) {
    let r = 0, g = 0, b = 0;
    if (H.length === 4) { r = "0x" + H[1] + H[1]; g = "0x" + H[2] + H[2]; b = "0x" + H[3] + H[3]; } else if (H.length === 7) { r = "0x" + H[1] + H[2]; g = "0x" + H[3] + H[4]; b = "0x" + H[5] + H[6]; }
    r /= 255; g /= 255; b /= 255;
    let cmin = Math.min(r, g, b), cmax = Math.max(r, g, b), delta = cmax - cmin, h = 0, s = 0, l = 0;
    if (delta === 0) h = 0; else if (cmax === r) h = ((g - b) / delta) % 6; else if (cmax === g) h = (b - r) / delta + 2; else h = (r - g) / delta + 4;
    h = Math.round(h * 60); if (h < 0) h += 360;
    l = (cmax + cmin) / 2; s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
    s = +(s * 100).toFixed(1); l = +(l * 100).toFixed(1);
    return { h, s, l };
}

export default function Appearance() {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    
    const [theme, setTheme] = useState('system');
    const [radius, setRadius] = useState('0.5rem');
    const [lightPrimary, setLightPrimary] = useState('#000000');
    const [lightPrimaryFg, setLightPrimaryFg] = useState('#ffffff');
    const [darkPrimary, setDarkPrimary] = useState('#ffffff');
    const [darkPrimaryFg, setDarkPrimaryFg] = useState('#000000');

    useEffect(() => {
        axios.get('/api/admin/settings/appearance')
            .then(res => {
                const s = res.data;
                setTheme(s.site_default_theme);
                setRadius(s.appearance_radius);
                setLightPrimary(hslToHex(s.appearance_light_primary_h, s.appearance_light_primary_s, s.appearance_light_primary_l));
                setLightPrimaryFg(hslToHex(s.appearance_light_primary_fg_h, s.appearance_light_primary_fg_s, s.appearance_light_primary_fg_l));
                setDarkPrimary(hslToHex(s.appearance_dark_primary_h, s.appearance_dark_primary_s, s.appearance_dark_primary_l));
                setDarkPrimaryFg(hslToHex(s.appearance_dark_primary_fg_h, s.appearance_dark_primary_fg_s, s.appearance_dark_primary_fg_l));
            })
            .catch(() => toast.error("Failed to load settings."))
            .finally(() => setLoading(false));
    }, []);

    const resetToDefaults = () => {
        setLightPrimary(hslToHex(222.2, '47.4%', '11.2%'));
        setLightPrimaryFg(hslToHex(210, '40%', '98%'));
        setDarkPrimary(hslToHex(210, '40%', '98%'));
        setDarkPrimaryFg(hslToHex(222.2, '47.4%', '11.2%'));
        setRadius('0.5rem');
        setTheme('system');
    };

    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true);

        const lp = hexToHSL(lightPrimary);
        const lpf = hexToHSL(lightPrimaryFg);
        const dp = hexToHSL(darkPrimary);
        const dpf = hexToHSL(darkPrimaryFg);

        const payload = {
            site_default_theme: theme,
            appearance_radius: radius,
            appearance_light_primary_h: lp.h, appearance_light_primary_s: lp.s + '%', appearance_light_primary_l: lp.l + '%',
            appearance_light_primary_fg_h: lpf.h, appearance_light_primary_fg_s: lpf.s + '%', appearance_light_primary_fg_l: lpf.l + '%',
            appearance_dark_primary_h: dp.h, appearance_dark_primary_s: dp.s + '%', appearance_dark_primary_l: dp.l + '%',
            appearance_dark_primary_fg_h: dpf.h, appearance_dark_primary_fg_s: dpf.s + '%', appearance_dark_primary_fg_l: dpf.l + '%'
        };

        try {
            await axios.post('/api/admin/settings/appearance', payload);
            toast.success("Appearance settings updated successfully!");
            // Reload page to apply CSS variables securely across the entire admin panel & frontend
            setTimeout(() => window.location.reload(), 1000);
        } catch (error) {
            toast.error("Failed to update settings.");
            setSaving(false);
        } 
    };

    return (
        <AdminLayout header="Settings">
            <Head title="Appearance Settings" />

            <SettingsLayout>
                {loading ? (
                    <div className="flex justify-center py-12"><Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /></div>
                ) : (
                    <form onSubmit={handleSave} className="space-y-6">
                        
                        {/* 1. Global Theme Selector */}
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Monitor className="w-5 h-5 text-primary" /> Default Theme Mode
                                </CardTitle>
                                <CardDescription>Set the default theme for guests and new users.</CardDescription>
                            </CardHeader>
                            <CardContent>
                                <RadioGroup defaultValue={theme} onValueChange={setTheme} className="grid grid-cols-1 md:grid-cols-3 gap-4">
                                    <div>
                                        <RadioGroupItem value="light" id="light" className="peer sr-only" />
                                        <Label htmlFor="light" className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary cursor-pointer">
                                            <Sun className="mb-3 h-6 w-6" /> Light
                                        </Label>
                                    </div>
                                    <div>
                                        <RadioGroupItem value="dark" id="dark" className="peer sr-only" />
                                        <Label htmlFor="dark" className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary cursor-pointer">
                                            <Moon className="mb-3 h-6 w-6" /> Dark
                                        </Label>
                                    </div>
                                    <div>
                                        <RadioGroupItem value="system" id="system" className="peer sr-only" />
                                        <Label htmlFor="system" className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary cursor-pointer">
                                            <Monitor className="mb-3 h-6 w-6" /> System
                                        </Label>
                                    </div>
                                </RadioGroup>
                            </CardContent>
                        </Card>

                        {/* 2. Brand Colors & Radius */}
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                            <Card className="md:col-span-2">
                                <CardHeader>
                                    <CardTitle className="flex items-center gap-2">
                                        <Palette className="w-5 h-5 text-primary" /> Brand Colors & Styling
                                    </CardTitle>
                                    <CardDescription>Pick your exact brand colors.</CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-6">
                                    
                                    <div className="grid grid-cols-2 gap-4 p-4 border rounded-xl bg-muted/20">
                                        <div className="col-span-2 font-semibold">Light Mode Colors</div>
                                        <div className="space-y-2">
                                            <Label>Primary Background</Label>
                                            <div className="flex items-center gap-2">
                                                <input type="color" value={lightPrimary} onChange={(e) => setLightPrimary(e.target.value)} className="w-12 h-10 p-1 bg-transparent border rounded cursor-pointer" />
                                                <span className="text-sm uppercase text-muted-foreground font-mono">{lightPrimary}</span>
                                            </div>
                                        </div>
                                        <div className="space-y-2">
                                            <Label>Primary Text</Label>
                                            <div className="flex items-center gap-2">
                                                <input type="color" value={lightPrimaryFg} onChange={(e) => setLightPrimaryFg(e.target.value)} className="w-12 h-10 p-1 bg-transparent border rounded cursor-pointer" />
                                                <span className="text-sm uppercase text-muted-foreground font-mono">{lightPrimaryFg}</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-2 gap-4 p-4 border rounded-xl bg-zinc-950 text-zinc-100">
                                        <div className="col-span-2 font-semibold text-zinc-300">Dark Mode Colors</div>
                                        <div className="space-y-2">
                                            <Label className="text-zinc-400">Primary Background</Label>
                                            <div className="flex items-center gap-2">
                                                <input type="color" value={darkPrimary} onChange={(e) => setDarkPrimary(e.target.value)} className="w-12 h-10 p-1 border-zinc-700 bg-zinc-900 rounded cursor-pointer" />
                                                <span className="text-sm uppercase text-zinc-400 font-mono">{darkPrimary}</span>
                                            </div>
                                        </div>
                                        <div className="space-y-2">
                                            <Label className="text-zinc-400">Primary Text</Label>
                                            <div className="flex items-center gap-2">
                                                <input type="color" value={darkPrimaryFg} onChange={(e) => setDarkPrimaryFg(e.target.value)} className="w-12 h-10 p-1 border-zinc-700 bg-zinc-900 rounded cursor-pointer" />
                                                <span className="text-sm uppercase text-zinc-400 font-mono">{darkPrimaryFg}</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="space-y-2">
                                        <Label>Global Border Radius</Label>
                                        <select 
                                            className="w-full px-3 py-2 text-sm border border-input bg-background rounded-md focus:ring-primary" 
                                            value={radius} 
                                            onChange={(e) => setRadius(e.target.value)}
                                        >
                                            <option value="0rem">0 (Square)</option>
                                            <option value="0.3rem">0.3rem (Small)</option>
                                            <option value="0.5rem">0.5rem (Default)</option>
                                            <option value="0.75rem">0.75rem (Large)</option>
                                            <option value="1.0rem">1.0rem (Extra Large)</option>
                                            <option value="2.0rem">2.0rem (Pill)</option>
                                        </select>
                                    </div>

                                </CardContent>
                                <CardFooter className="flex flex-col sm:flex-row justify-between gap-4 px-6 py-4 border-t bg-muted/10">
                                    <Button type="button" variant="outline" onClick={resetToDefaults} className="gap-2 w-full sm:w-auto">
                                        <RotateCcw className="w-4 h-4" /> Reset Defaults
                                    </Button>
                                    <Button type="submit" disabled={saving} className="gap-2 w-full sm:w-auto">
                                        {saving ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <Save className="w-4 h-4" />}
                                        Apply Global Appearance
                                    </Button>
                                </CardFooter>
                            </Card>

                            {/* 3. Live Previews */}
                            <div className="space-y-6">
                                <Card className="bg-white border-zinc-200 text-zinc-950">
                                    <CardHeader className="pb-3"><CardTitle className="text-sm text-zinc-900">Light Preview</CardTitle></CardHeader>
                                    <CardContent className="space-y-4">
                                        <button type="button" style={{ backgroundColor: lightPrimary, color: lightPrimaryFg, borderRadius: radius }} className="w-full px-4 py-2 text-sm font-medium shadow-sm">
                                            Primary Button
                                        </button>
                                        <div style={{ borderRadius: radius }} className="flex items-center justify-center p-3 text-sm border border-zinc-200 bg-zinc-50 text-zinc-500">
                                            Sample Card
                                        </div>
                                    </CardContent>
                                </Card>

                                <Card className="border-zinc-800 bg-zinc-950 text-zinc-100">
                                    <CardHeader className="pb-3"><CardTitle className="text-sm text-zinc-100">Dark Preview</CardTitle></CardHeader>
                                    <CardContent className="space-y-4">
                                        <button type="button" style={{ backgroundColor: darkPrimary, color: darkPrimaryFg, borderRadius: radius }} className="w-full px-4 py-2 text-sm font-medium shadow-sm">
                                            Primary Button
                                        </button>
                                        <div style={{ borderRadius: radius }} className="flex items-center justify-center p-3 text-sm border border-zinc-800 bg-zinc-900 text-zinc-400">
                                            Sample Card
                                        </div>
                                    </CardContent>
                                </Card>
                            </div>
                        </div>

                    </form>
                )}
            </SettingsLayout>
        </AdminLayout>
    );
}