"use client";

import React from 'react';
import { useStore } from '@/lib/store';
import { Save, Sparkles, Brain, Settings2, Moon, Sun, Monitor, Check } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useTheme } from '@/components/theme-provider';

import { MobileCookieInstructions } from './MobileCookieInstructions';

type Provider = 'whisk' | 'meta';

const providers: { id: Provider; name: string; icon: any; description: string }[] = [
    { id: 'whisk', name: 'Google Whisk', icon: Sparkles, description: 'ImageFX / Imagen 3' },
    { id: 'meta', name: 'Meta AI', icon: Brain, description: 'Imagine / Emu' },
];

export function Settings() {
    const { settings, setSettings } = useStore();
    const { theme, setTheme } = useTheme();
    const [mounted, setMounted] = React.useState(false);

    React.useEffect(() => {
        setMounted(true);
    }, []);

    const ThemeButton = ({ theme: t, icon: Icon, label }: { theme: 'light' | 'dark' | 'system', icon: any, label: string }) => (
        <button
            onClick={() => setTheme(t)}
            className={cn(
                "flex items-center justify-center gap-2 p-3 rounded-xl border transition-all active:scale-95",
                mounted && theme === t
                    ? "bg-primary text-primary-foreground border-primary"
                    : "bg-card hover:bg-muted border-border text-muted-foreground"
            )}
        >
            <Icon className="h-4 w-4" />
            <span className="text-sm font-medium">{label}</span>
        </button>
    );

    // Local state for form fields
    const [provider, setProvider] = React.useState<Provider>(settings.provider || 'whisk');
    const [whiskCookies, setWhiskCookies] = React.useState(settings.whiskCookies || '');
    const [useMetaFreeWrapper, setUseMetaFreeWrapper] = React.useState(settings.useMetaFreeWrapper !== undefined ? settings.useMetaFreeWrapper : true);
    const [metaFreeWrapperUrl, setMetaFreeWrapperUrl] = React.useState(settings.metaFreeWrapperUrl || 'http://localhost:8000');
    const [metaCookies, setMetaCookies] = React.useState(settings.metaCookies || '');
    const [facebookCookies, setFacebookCookies] = React.useState(settings.facebookCookies || '');
    const [saved, setSaved] = React.useState(false);
    const [whiskVerified, setWhiskVerified] = React.useState(false);
    const [metaVerified, setMetaVerified] = React.useState(false);

    const handleSave = () => {
        setSettings({
            provider,
            whiskCookies,
            useMetaFreeWrapper,
            metaFreeWrapperUrl,
            metaCookies,
            facebookCookies
        });
        setSaved(true);
        setTimeout(() => setSaved(false), 2000);
    };

    return (
        <div className="space-y-8 pb-32">
            {/* Header Section */}
            <div className="px-2">
                <h2 className="text-2xl font-black text-foreground tracking-tight">Settings</h2>
                <p className="text-sm font-medium text-muted-foreground mt-1">Configure your AI preferences and API credentials.</p>
            </div>

            {/* General Preferences Card */}
            <div className="bg-card rounded-3xl p-6 md:p-8 shadow-premium border border-border/50 space-y-8 relative overflow-hidden">
                <div className="absolute top-0 right-0 -mr-12 -mt-12 w-48 h-48 bg-primary/5 rounded-full blur-2xl" />

                <section className="space-y-6 relative z-10">
                    <div className="flex items-center gap-3">
                        <div className="p-2.5 rounded-2xl bg-primary/10 text-primary">
                            <Settings2 className="h-5 w-5" />
                        </div>
                        <h3 className="font-extrabold text-lg tracking-tight">Appearance</h3>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <ThemeButton theme="light" icon={Sun} label="Light" />
                        <ThemeButton theme="dark" icon={Moon} label="Dark" />
                        <ThemeButton theme="system" icon={Monitor} label="System" />
                    </div>
                </section>

                <div className="border-t border-border/50" />

                <section className="space-y-6 relative z-10">
                    <div className="flex items-center gap-3">
                        <div className="p-2.5 rounded-2xl bg-primary/10 text-primary">
                            <Sparkles className="h-5 w-5" />
                        </div>
                        <h3 className="font-extrabold text-lg tracking-tight">Default Engine</h3>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        {providers.map((p) => (
                            <button
                                key={p.id}
                                onClick={() => setProvider(p.id)}
                                className={cn(
                                    "flex items-center gap-4 p-4 rounded-2xl border-2 transition-all active:scale-[0.98] text-left",
                                    provider === p.id
                                        ? "border-primary bg-primary/5 ring-4 ring-primary/10"
                                        : "border-border/50 hover:border-primary/30 bg-background/50"
                                )}
                            >
                                <div className={cn(
                                    "p-3 rounded-xl transition-colors",
                                    provider === p.id ? "bg-primary text-white" : "bg-muted text-muted-foreground"
                                )}>
                                    <p.icon className="h-6 w-6" />
                                </div>
                                <div>
                                    <p className={cn("font-bold text-sm", provider === p.id ? "text-primary" : "text-foreground")}>{p.name}</p>
                                    <p className="text-[10px] uppercase font-black tracking-widest text-muted-foreground mt-0.5">{p.description}</p>
                                </div>
                            </button>
                        ))}
                    </div>
                </section>
            </div>

            {/* Provider Credentials Card */}
            <div className="bg-card rounded-3xl p-6 md:p-8 shadow-premium border border-border/50 relative overflow-hidden">
                <div className="absolute bottom-0 left-0 -ml-12 -mb-12 w-48 h-48 bg-secondary/5 rounded-full blur-2xl" />

                <section className="space-y-8 relative z-10">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                            <div className="p-2.5 rounded-2xl bg-primary/10 text-primary">
                                <Sparkles className="h-5 w-5" />
                            </div>
                            <h3 className="font-extrabold text-lg tracking-tight">API Credentials</h3>
                        </div>
                        <button
                            onClick={handleSave}
                            className="flex items-center gap-2 px-6 py-2 bg-primary text-white rounded-full text-xs font-black uppercase tracking-widest hover:bg-violet-700 shadow-lg shadow-primary/20 transition-all active:scale-95"
                        >
                            <Save className="h-4 w-4" />
                            {saved ? "Saved Configuration" : "Save Configuration"}
                        </button>
                    </div>

                    <div className="grid grid-cols-1 gap-12">
                        {/* Whisk Settings */}
                        {provider === 'whisk' && (
                            <div className="space-y-4 animate-in fade-in slide-in-from-left-4 duration-300">
                                <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                        <span className="h-2 w-2 rounded-full bg-primary" />
                                        <h4 className="text-xs font-black uppercase tracking-widest text-foreground">Google Whisk Configuration</h4>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <button
                                            onClick={async () => {
                                                try {
                                                    const text = await navigator.clipboard.readText();
                                                    setWhiskCookies(text);
                                                } catch (err) {
                                                    console.error('Failed to read clipboard', err);
                                                    alert('Please grant clipboard permissions to use this feature.');
                                                }
                                            }}
                                            className="px-3 py-1 bg-muted/50 hover:bg-muted text-[10px] font-bold rounded-lg border border-border/50 transition-all flex items-center gap-1.5 active:scale-95"
                                        >
                                            <span className="w-1.5 h-1.5 rounded-full bg-primary/40" />
                                            Paste Cookies
                                        </button>
                                        <button
                                            onClick={() => {
                                                const isValid = whiskCookies.includes('PHPSESSID') || whiskCookies.length > 100;
                                                if (isValid) {
                                                    setWhiskVerified(true);
                                                    setTimeout(() => setWhiskVerified(false), 3000);
                                                } else {
                                                    alert("Whisk cookies might be incomplete.");
                                                }
                                            }}
                                            className={cn(
                                                "px-3 py-1 text-[10px] font-bold rounded-lg border transition-all active:scale-95 flex items-center gap-1.5",
                                                whiskVerified
                                                    ? "bg-green-500/10 border-green-500/20 text-green-600 dark:text-green-400"
                                                    : "bg-primary/10 hover:bg-primary/20 text-primary border-primary/20"
                                            )}
                                        >
                                            {whiskVerified ? <Check className="h-3 w-3" /> : null}
                                            {whiskVerified ? "Verified" : "Verify"}
                                        </button>
                                    </div>
                                </div>
                                <div className="space-y-2">
                                    <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground ml-1">Authentication Cookies</label>
                                    <textarea
                                        value={whiskCookies}
                                        onChange={(e) => setWhiskCookies(e.target.value)}
                                        placeholder="Paste your Whisk cookies here..."
                                        className="w-full h-32 bg-background/50 border border-border/50 rounded-2xl p-4 text-xs font-mono focus:ring-2 focus:ring-primary/20 focus:border-primary/50 outline-none resize-none transition-all"
                                    />
                                    <MobileCookieInstructions provider="whisk" />
                                </div>
                            </div>
                        )}

                        {/* Meta AI Settings */}
                        {provider === 'meta' && (
                            <div className="space-y-4 animate-in fade-in slide-in-from-right-4 duration-300">
                                <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                        <span className="h-2 w-2 rounded-full bg-blue-500" />
                                        <h4 className="text-xs font-black uppercase tracking-widest text-foreground">Meta AI Configuration</h4>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <button
                                            onClick={() => {
                                                const isValid = metaCookies.length > 50 && facebookCookies.length > 50;
                                                if (isValid) {
                                                    setMetaVerified(true);
                                                    setTimeout(() => setMetaVerified(false), 3000);
                                                } else {
                                                    alert("Please ensure both Meta and Facebook cookies are pasted.");
                                                }
                                            }}
                                            className={cn(
                                                "px-3 py-1 text-[10px] font-bold rounded-lg border transition-all active:scale-95 flex items-center gap-1.5",
                                                metaVerified
                                                    ? "bg-green-500/10 border-green-500/20 text-green-600 dark:text-green-400"
                                                    : "bg-blue-500/10 hover:bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/20"
                                            )}
                                        >
                                            {metaVerified ? <Check className="h-3 w-3" /> : null}
                                            {metaVerified ? "Verified" : "Verify Duo"}
                                        </button>
                                    </div>
                                </div>

                                {/* Advanced Configuration (Meta Specific) */}
                                <details className="group mb-4">
                                    <summary className="flex items-center gap-2 cursor-pointer text-xs text-muted-foreground/50 hover:text-muted-foreground mb-4 select-none">
                                        <Settings2 className="h-3 w-3" />
                                        <span>Advanced Host Configuration</span>
                                    </summary>

                                    <div className="space-y-6 pl-4 border-l border-border/50 mb-6">
                                        <div className="flex items-center justify-between p-4 rounded-xl bg-muted/30 border border-border/50">
                                            <div className="space-y-0.5">
                                                <p className="text-sm font-bold">Local Docker Wrapper</p>
                                                <p className="text-[10px] uppercase font-black tracking-widest text-muted-foreground">Internal API Bridge</p>
                                            </div>
                                            <button
                                                onClick={() => setUseMetaFreeWrapper(!useMetaFreeWrapper)}
                                                className={cn(
                                                    "relative inline-flex h-6 w-11 items-center rounded-full transition-colors outline-none",
                                                    useMetaFreeWrapper ? "bg-primary" : "bg-border"
                                                )}
                                            >
                                                <span className={cn(
                                                    "inline-block h-4 w-4 transform rounded-full bg-white transition-transform",
                                                    useMetaFreeWrapper ? "translate-x-6" : "translate-x-1"
                                                )} />
                                            </button>
                                        </div>

                                        {useMetaFreeWrapper && (
                                            <div className="space-y-2">
                                                <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground ml-1">Wrapper Endpoint</label>
                                                <input
                                                    type="text"
                                                    value={metaFreeWrapperUrl}
                                                    onChange={(e) => setMetaFreeWrapperUrl(e.target.value)}
                                                    className="w-full p-3 rounded-xl bg-muted/30 border border-border/50 focus:ring-1 focus:ring-primary/50 outline-none font-mono text-xs"
                                                />
                                            </div>
                                        )}
                                    </div>
                                </details>

                                {/* Meta Cookies Fields */}
                                <div className="space-y-6">
                                    <div className="space-y-2">
                                        <div className="flex items-center justify-between px-1">
                                            <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Meta.ai Cookies</label>
                                            <button
                                                onClick={async () => {
                                                    try {
                                                        const text = await navigator.clipboard.readText();
                                                        setMetaCookies(text);
                                                    } catch (err) {
                                                        console.error('Clipboard error', err);
                                                        alert('Clipboard permission denied.');
                                                    }
                                                }}
                                                className="text-[10px] font-bold text-primary hover:underline"
                                            >
                                                Paste
                                            </button>
                                        </div>
                                        <textarea
                                            value={metaCookies}
                                            onChange={(e) => setMetaCookies(e.target.value)}
                                            placeholder="Paste your Meta cookies..."
                                            className="w-full h-32 bg-background/50 border border-border/50 rounded-2xl p-4 text-xs font-mono focus:ring-2 focus:ring-primary/20 focus:border-primary/50 outline-none resize-none transition-all"
                                        />
                                    </div>

                                    <div className="space-y-2">
                                        <div className="flex items-center justify-between px-1">
                                            <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Facebook.com Auth Cookies</label>
                                            <button
                                                onClick={async () => {
                                                    try {
                                                        const text = await navigator.clipboard.readText();
                                                        setFacebookCookies(text);
                                                    } catch (err) {
                                                        console.error('Clipboard error', err);
                                                        alert('Clipboard permission denied.');
                                                    }
                                                }}
                                                className="text-[10px] font-bold text-primary hover:underline"
                                            >
                                                Paste
                                            </button>
                                        </div>
                                        <textarea
                                            value={facebookCookies}
                                            onChange={(e) => setFacebookCookies(e.target.value)}
                                            placeholder="Paste your Facebook cookies (REQUIRED)..."
                                            className="w-full h-32 bg-background/50 border border-border/50 rounded-2xl p-4 text-xs font-mono focus:ring-2 focus:ring-primary/20 focus:border-primary/50 outline-none resize-none transition-all"
                                        />
                                    </div>
                                    <MobileCookieInstructions provider="meta" />
                                </div>
                            </div>
                        )}
                    </div>
                </section>
            </div>
        </div>
    );
}
