import React, { useState } from 'react';
import { Head, useForm } from '@inertiajs/react';
import AdminLayout from '@/cp/Layouts/AdminLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/Components/ui/card";
import { Label } from "@/Components/ui/label";
import { Button } from "@/Components/ui/button";
import { Save, Palette, RotateCcw } from "lucide-react";

// --- 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({ settings }) {
    // Setup initial Hex states from DB HSL values
    const [lightPrimary, setLightPrimary] = useState(
        hslToHex(settings.appearance_light_primary_h || 222.2, settings.appearance_light_primary_s || '47.4%', settings.appearance_light_primary_l || '11.2%')
    );
    const [lightPrimaryFg, setLightPrimaryFg] = useState(
        hslToHex(settings.appearance_light_primary_fg_h || 210, settings.appearance_light_primary_fg_s || '40%', settings.appearance_light_primary_fg_l || '98%')
    );
    const [darkPrimary, setDarkPrimary] = useState(
        hslToHex(settings.appearance_dark_primary_h || 210, settings.appearance_dark_primary_s || '40%', settings.appearance_dark_primary_l || '98%')
    );
    const [darkPrimaryFg, setDarkPrimaryFg] = useState(
        hslToHex(settings.appearance_dark_primary_fg_h || 222.2, settings.appearance_dark_primary_fg_s || '47.4%', settings.appearance_dark_primary_fg_l || '11.2%')
    );
    const [radius, setRadius] = useState(settings.appearance_radius || '0.5rem');

    const { transform, post, processing, recentlySuccessful } = useForm({});

    // --- Reset to Default Logic ---
    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');
    };

    const submit = (e) => {
        e.preventDefault();

        // Convert the Hex color pickers to HSL logic needed for Tailwind CSS variables
        const lp = hexToHSL(lightPrimary);
        const lpf = hexToHSL(lightPrimaryFg);
        const dp = hexToHSL(darkPrimary);
        const dpf = hexToHSL(darkPrimaryFg);

        // Package the data correctly using transform
        transform((data) => ({
            ...data,
            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 + '%',
            appearance_radius: radius
        }));

        // Send the post request
        post(route('cp.settings.appearance.update'), {
            preserveScroll: true
        });
    };

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

            <div className="max-w-4xl mx-auto">
                <div className="flex items-center gap-3 mb-6">
                    <Palette className="w-8 h-8 text-primary" />
                    <div>
                        <h2 className="text-2xl font-bold tracking-tight">Appearance</h2>
                        <p className="text-muted-foreground">Manage your application colors and global border radius.</p>
                    </div>
                </div>

                <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
                    {/* Settings Form */}
                    <Card className="md:col-span-2">
                        <form onSubmit={submit}>
                            <CardHeader>
                                <CardTitle>Global Themes</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">{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">{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">{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">{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-input bg-background rounded-md focus:ring-primary focus:border-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>
                                    </select>
                                </div>

                            </CardContent>
                            
                            <CardFooter className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 px-6 py-4 border-t bg-muted/20">
                                <div className="flex items-center gap-4">
                                    {/* Added Reset Button Here */}
                                    <Button 
                                        type="button" 
                                        variant="outline" 
                                        onClick={resetToDefaults} 
                                        className="gap-2"
                                    >
                                        <RotateCcw className="w-4 h-4" />
                                        Reset Defaults
                                    </Button>
                                    
                                    <p className="text-sm text-muted-foreground hidden sm:block">
                                        {recentlySuccessful && <span className="font-medium text-green-500">Appearance applied globally!</span>}
                                    </p>
                                </div>
                                
                                <Button type="submit" disabled={processing} className="gap-2 w-full sm:w-auto">
                                    <Save className="w-4 h-4" />
                                    {processing ? 'Applying...' : 'Apply Colors Globally'}
                                </Button>

                                {/* Mobile success message */}
                                <p className="text-sm text-muted-foreground sm:hidden w-full text-center">
                                    {recentlySuccessful && <span className="font-medium text-green-500">Appearance applied globally!</span>}
                                </p>
                            </CardFooter>
                        </form>
                    </Card>

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

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