import React, { useMemo, useState } from 'react';
import { Form, FormField } from '@admin/components/form';
import { HexColorPicker } from '@admin/components/hex-color-picker';
import TextEditor from '@admin/components/rich-text-editor';
import { Button } from '@admin/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogClose,
} from '@admin/components/ui/dialog';
import { Sheet, SheetClose, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '@admin/components/ui/sheet';
import { router } from '@inertiajs/react';
import { LayoutGrid, Pencil, Save, Trash2 } from 'lucide-react';
import { FormProvider, useForm } from 'react-hook-form';

interface BrandingSettings {
    primary_color?: string;
    secondary_color?: string;
    default_logo?: string | null;
    default_icon?: string | null;
    default_favicon?: string | null;
}

interface LoginSettings {
    admin_login_layout?: string;
    tenant_login_layout?: string;
    login_banner?: string | null;
    login_title?: string;
    login_subtitle?: string;
    social_login_enabled?: boolean;
    terms_url?: string;
    privacy_url?: string;
    terms_content?: string;
    privacy_content?: string;
}

// ── Layout preview thumbnails ──────────────────────────────────────────────

function PreviewLayout1({ active }: { active: boolean }) {
    return (
        <svg viewBox="0 0 160 100" className="w-full" xmlns="http://www.w3.org/2000/svg">
            <rect width="160" height="100" rx="4" fill={active ? '#eff6ff' : '#f8fafc'} />
            <rect x="0" y="0" width="72" height="100" rx="4" fill={active ? '#3b82f6' : '#94a3b8'} />
            <rect x="0" y="60" width="72" height="40" rx="0" fill="rgba(0,0,0,0.35)" />
            <rect x="100" y="14" width="14" height="14" rx="3" fill={active ? '#3b82f6' : '#cbd5e1'} />
            <rect x="88" y="32" width="40" height="4" rx="2" fill={active ? '#1e40af' : '#94a3b8'} />
            <line x1="82" y1="42" x2="142" y2="42" stroke={active ? '#bfdbfe' : '#e2e8f0'} strokeWidth="1" />
            <rect x="82" y="48" width="60" height="7" rx="2" fill="white" stroke={active ? '#93c5fd' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="82" y="59" width="60" height="7" rx="2" fill="white" stroke={active ? '#93c5fd' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="82" y="70" width="60" height="8" rx="2" fill={active ? '#3b82f6' : '#94a3b8'} />
        </svg>
    );
}

function PreviewLayout2({ active }: { active: boolean }) {
    return (
        <svg viewBox="0 0 160 100" className="w-full" xmlns="http://www.w3.org/2000/svg">
            <rect width="160" height="100" rx="4" fill={active ? '#eff6ff' : '#f1f5f9'} />
            <rect x="71" y="8" width="18" height="18" rx="4" fill={active ? '#3b82f6' : '#94a3b8'} />
            <rect x="55" y="30" width="50" height="4" rx="2" fill={active ? '#1e40af' : '#94a3b8'} />
            <rect x="30" y="38" width="100" height="54" rx="5" fill="white" stroke={active ? '#bfdbfe' : '#e2e8f0'} strokeWidth="1" style={{ filter: 'drop-shadow(0 2px 6px rgba(0,0,0,0.08))' }} />
            <rect x="40" y="46" width="80" height="7" rx="2" fill={active ? '#eff6ff' : '#f8fafc'} stroke={active ? '#93c5fd' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="40" y="57" width="80" height="7" rx="2" fill={active ? '#eff6ff' : '#f8fafc'} stroke={active ? '#93c5fd' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="40" y="68" width="80" height="8" rx="2" fill={active ? '#3b82f6' : '#94a3b8'} />
            <rect x="40" y="80" width="6" height="6" rx="1" fill={active ? '#bfdbfe' : '#e2e8f0'} />
            <rect x="50" y="82" width="30" height="3" rx="1" fill={active ? '#bfdbfe' : '#e2e8f0'} />
        </svg>
    );
}

function PreviewLayout3({ active }: { active: boolean }) {
    return (
        <svg viewBox="0 0 160 100" className="w-full" xmlns="http://www.w3.org/2000/svg">
            <rect width="160" height="100" rx="4" fill={active ? '#eff6ff' : '#f1f5f9'} />
            <rect x="20" y="6" width="120" height="88" rx="5" fill="white" stroke={active ? '#bfdbfe' : '#e2e8f0'} strokeWidth="1" style={{ filter: 'drop-shadow(0 2px 8px rgba(0,0,0,0.10))' }} />
            <rect x="20" y="6" width="120" height="36" rx="5" fill={active ? '#3b82f6' : '#94a3b8'} />
            <rect x="20" y="32" width="120" height="10" fill={active ? '#3b82f6' : '#94a3b8'} />
            <rect x="20" y="20" width="120" height="22" fill="rgba(0,0,0,0.3)" />
            <rect x="28" y="27" width="10" height="10" rx="2" fill="white" fillOpacity="0.9" />
            <rect x="42" y="29" width="40" height="3" rx="1" fill="rgba(255,255,255,0.85)" />
            <rect x="42" y="34" width="28" height="2.5" rx="1" fill="rgba(255,255,255,0.5)" />
            <rect x="30" y="48" width="100" height="7" rx="2" fill={active ? '#eff6ff' : '#f8fafc'} stroke={active ? '#93c5fd' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="30" y="59" width="100" height="7" rx="2" fill={active ? '#eff6ff' : '#f8fafc'} stroke={active ? '#93c5fd' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="30" y="70" width="100" height="8" rx="2" fill={active ? '#3b82f6' : '#94a3b8'} />
            <rect x="30" y="82" width="6" height="6" rx="1" fill={active ? '#bfdbfe' : '#e2e8f0'} />
            <rect x="40" y="84" width="30" height="3" rx="1" fill={active ? '#bfdbfe' : '#e2e8f0'} />
        </svg>
    );
}

const LAYOUTS = [
    { value: 'layout1', label: 'Layout Design 1', Preview: PreviewLayout1 },
    { value: 'layout2', label: 'Layout Design 2', Preview: PreviewLayout2 },
    { value: 'layout3', label: 'Layout Design 3', Preview: PreviewLayout3 },
];

function LayoutPickerModal({
    label,
    value,
    onChange,
}: {
    label: string;
    value: string;
    onChange: (v: string) => void;
}) {
    const [open, setOpen] = useState(false);
    const [pending, setPending] = useState(value);

    const current = LAYOUTS.find((l) => l.value === value) ?? LAYOUTS[0];
    const CurrentPreview = current.Preview;

    return (
        <>
            <div>
                <p className="mb-2 text-sm font-medium text-gray-700">{label}</p>
                <button
                    type="button"
                    onClick={() => { setPending(value); setOpen(true); }}
                    className="flex w-full items-center gap-3 rounded-lg border border-gray-200 bg-white px-4 py-3 text-left transition hover:border-blue-400 hover:shadow-sm"
                >
                    <div className="w-20 shrink-0 overflow-hidden rounded border border-gray-100">
                        <CurrentPreview active={true} />
                    </div>
                    <div className="flex-1">
                        <p className="text-sm font-medium text-gray-800">{current.label}</p>
                        <p className="text-xs text-gray-400">Click to change layout</p>
                    </div>
                    <LayoutGrid className="h-4 w-4 shrink-0 text-gray-400" />
                </button>
            </div>

            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent className="sm:max-w-2xl">
                    <DialogHeader>
                        <DialogTitle>{label}</DialogTitle>
                    </DialogHeader>
                    <div className="grid grid-cols-3 gap-4 py-2">
                        {LAYOUTS.map(({ value: v, label: l, Preview: LayoutPreview }) => {
                            const active = pending === v;
                            return (
                                <button
                                    key={v}
                                    type="button"
                                    onClick={() => setPending(v)}
                                    className={[
                                        'group flex flex-col overflow-hidden rounded-xl border-2 transition-all',
                                        active ? 'border-blue-500 ring-2 ring-blue-200' : 'border-gray-200 hover:border-blue-300',
                                    ].join(' ')}
                                >
                                    <div className="p-2"><LayoutPreview active={active} /></div>
                                    <div className={[
                                        'px-3 py-2 text-center text-xs font-medium',
                                        active ? 'bg-blue-50 text-blue-700' : 'bg-gray-50 text-gray-500 group-hover:text-gray-700',
                                    ].join(' ')}>{l}</div>
                                </button>
                            );
                        })}
                    </div>
                    <div className="flex justify-end gap-2 pt-2">
                        <DialogClose asChild>
                            <Button type="button" variant="outline">Cancel</Button>
                        </DialogClose>
                        <Button type="button" onClick={() => { onChange(pending); setOpen(false); }}>
                            Apply Layout
                        </Button>
                    </div>
                </DialogContent>
            </Dialog>
        </>
    );
}

function FileRow({
    fieldName,
    label,
    hint,
    currentUrl,
    onDelete,
    deleting,
    maxSize = 5,
}: {
    fieldName: string;
    label: string;
    hint: string;
    currentUrl?: string | null;
    onDelete?: () => void;
    deleting?: boolean;
    maxSize?: number;
}) {
    return (
        <div className="rounded-lg border p-4">
            <div className="mb-3 flex items-center justify-between">
                <div>
                    <p className="text-sm font-medium text-gray-900">{label}</p>
                    <p className="text-xs text-gray-500">{hint}</p>
                </div>
                {currentUrl && onDelete && (
                    <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={onDelete}
                        disabled={deleting}
                        className="text-red-600 hover:border-red-300 hover:text-red-700"
                    >
                        <Trash2 className="h-4 w-4" />
                    </Button>
                )}
            </div>
            <FormField type="file" name={fieldName} accept="image/*" maxSize={maxSize} preview={true} currentUrl={currentUrl ?? undefined} />
        </div>
    );
}

// ── Main component ─────────────────────────────────────────────────────────

function LegalContentSheet({ title, fieldName, initialContent }: {
    title: string;
    fieldName: 'terms_content' | 'privacy_content';
    initialContent: string;
}) {
    const [open, setOpen] = useState(false);
    const [saving, setSaving] = useState(false);
    const methods = useForm({ defaultValues: { [fieldName]: initialContent } });

    const handleSave = () => {
        const content = methods.getValues(fieldName);
        setSaving(true);
        router.post(
            route('admin.settings.general.personalizer.update', { group: 'login' }),
            { [fieldName]: content },
            {
                preserveScroll: true,
                onSuccess: () => { setOpen(false); setSaving(false); },
                onError: () => setSaving(false),
            },
        );
    };

    return (
        <Sheet open={open} onOpenChange={setOpen}>
            <Button type="button" variant="outline" size="sm" onClick={() => setOpen(true)}>
                <Pencil className="mr-1 h-3.5 w-3.5" />
                Edit
            </Button>
            <SheetContent className="flex w-screen max-w-none flex-col overflow-y-auto">
                <SheetHeader>
                    <SheetTitle>Edit {title}</SheetTitle>
                </SheetHeader>
                <div className="flex-1 px-4 py-4">
                    <FormProvider {...methods}>
                        <TextEditor name={fieldName} minHeight="500px" />
                    </FormProvider>
                </div>
                <SheetFooter>
                    <SheetClose asChild>
                        <Button type="button" variant="outline">Cancel</Button>
                    </SheetClose>
                    <Button type="button" onClick={handleSave} disabled={saving}>
                        <Save className="mr-2 h-4 w-4" />
                        {saving ? 'Saving…' : 'Save'}
                    </Button>
                </SheetFooter>
            </SheetContent>
        </Sheet>
    );
}

export default function BrandingPanel({ branding, login }: { branding: BrandingSettings; login: LoginSettings }) {
    const [deletingKey, setDeletingKey] = useState<string | null>(null);
    const [adminLayout, setAdminLayout] = useState(login?.admin_login_layout || 'layout1');
    const [tenantLayout, setTenantLayout] = useState(login?.tenant_login_layout || 'layout1');

    const defaultValues = useMemo(() => ({
        // branding group
        primary_color:    branding?.primary_color    || '#4f46e5',
        secondary_color:  branding?.secondary_color  || '#7c3aed',
        default_logo:     branding?.default_logo     || '',
        default_icon:     branding?.default_icon     || '',
        default_favicon:  branding?.default_favicon  || '',
        // login group
        login_banner:         login?.login_banner         || '',
        login_title:          login?.login_title          || 'Welcome back',
        login_subtitle:       login?.login_subtitle       || 'Enter your email and password to sign in to your account',
        social_login_enabled: login?.social_login_enabled ?? false,
        terms_url:            login?.terms_url            || '',
        privacy_url:          login?.privacy_url          || '',
        terms_content:        login?.terms_content        || '',
        privacy_content:      login?.privacy_content      || '',
    }), [branding, login]);

    const handleSubmit = (data: any) => {
        // ── Branding payload ──
        const brandPayload: any = {
            primary_color:   data.primary_color,
            secondary_color: data.secondary_color,
        };
        ['default_logo', 'default_icon', 'default_favicon'].forEach((k) => {
            if (data[k] instanceof File) brandPayload[k] = data[k];
        });

        // ── Login payload ──
        const loginPayload: any = {
            admin_login_layout:  adminLayout,
            tenant_login_layout: tenantLayout,
            login_title:          data.login_title,
            login_subtitle:       data.login_subtitle,
            social_login_enabled: data.social_login_enabled,
            terms_url:            data.terms_url,
            privacy_url:          data.privacy_url,
            terms_content:        data.terms_content,
            privacy_content:      data.privacy_content,
        };
        if (data.login_banner instanceof File) loginPayload.login_banner = data.login_banner;

        // Fire branding first; on success fire login
        router.post(
            route('admin.settings.general.personalizer.update', { group: 'branding' }),
            brandPayload,
            {
                forceFormData: true,
                preserveScroll: true,
                onSuccess: () => {
                    router.post(
                        route('admin.settings.general.personalizer.update', { group: 'login' }),
                        loginPayload,
                        { forceFormData: true, preserveScroll: true },
                    );
                },
            },
        );
    };

    const deleteFile = (group: 'branding' | 'login', key: string) => {
        if (!confirm('Delete this image?')) return;
        setDeletingKey(key);
        router.delete(
            route('admin.settings.general.personalizer.file.delete', { group, key }),
            { preserveScroll: true, onFinish: () => setDeletingKey(null) },
        );
    };

    return (
        <Form submitHandler={handleSubmit} defaultValues={defaultValues}>
            <div className="space-y-8">

                {/* Brand Colors */}
                <div>
                    <h3 className="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Brand Colors</h3>
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <HexColorPicker name="primary_color" label="Primary Color" />
                        <HexColorPicker name="secondary_color" label="Secondary Color" />
                    </div>
                </div>

                {/* Identity */}
                <div>
                    <h3 className="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Identity</h3>
                    <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
                        <FileRow fieldName="default_logo"    label="Logo"         hint="Recommended: 500×200px. Max 5 MB."          maxSize={5} currentUrl={branding?.default_logo}    onDelete={() => deleteFile('branding', 'default_logo')}    deleting={deletingKey === 'default_logo'} />
                        <FileRow fieldName="default_icon"    label="Icon"         hint="Recommended: 256×256px. Max 2 MB."          maxSize={2} currentUrl={branding?.default_icon}    onDelete={() => deleteFile('branding', 'default_icon')}    deleting={deletingKey === 'default_icon'} />
                        <FileRow fieldName="default_favicon" label="Favicon"      hint="Recommended: 32×32px. Max 1 MB."            maxSize={1} currentUrl={branding?.default_favicon} onDelete={() => deleteFile('branding', 'default_favicon')} deleting={deletingKey === 'default_favicon'} />
                        <FileRow fieldName="login_banner"    label="Login Banner" hint="Used in login page layouts. 800×1200px. Max 5 MB." currentUrl={login?.login_banner}           onDelete={() => deleteFile('login', 'login_banner')}       deleting={deletingKey === 'login_banner'} />
                    </div>
                </div>

                {/* Default Login Layout */}
                <div>
                    <h3 className="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Default Login Layout</h3>
                    <div className="space-y-4">
                        <LayoutPickerModal label="Admin Default Login Layout" value={adminLayout} onChange={setAdminLayout} />
                        <LayoutPickerModal label="Tenant Default Login Layout" value={tenantLayout} onChange={setTenantLayout} />
                    </div>
                </div>

                {/* Login Page Content */}
                <div>
                    <h3 className="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Login Page Content</h3>
                    <div className="space-y-4">
                        <FormField type="text" name="login_title" label="Heading" placeholder="Welcome back" />
                        <FormField type="textarea" name="login_subtitle" label="Sub-heading" placeholder="Enter your email and password to sign in" rows={2} />
                    </div>
                </div>

                {/* Legal Links */}
                <div>
                    <h3 className="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Legal Links</h3>
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <div className="space-y-1">
                            <div className="flex items-center justify-between">
                                <span className="text-sm font-medium text-gray-700">Terms of Service</span>
                                <LegalContentSheet title="Terms of Service" fieldName="terms_content" initialContent={login?.terms_content || ''} />
                            </div>
                            <FormField type="text" name="terms_url" placeholder="https://example.com/terms" />
                        </div>
                        <div className="space-y-1">
                            <div className="flex items-center justify-between">
                                <span className="text-sm font-medium text-gray-700">Privacy Policy</span>
                                <LegalContentSheet title="Privacy Policy" fieldName="privacy_content" initialContent={login?.privacy_content || ''} />
                            </div>
                            <FormField type="text" name="privacy_url" placeholder="https://example.com/privacy" />
                        </div>
                    </div>
                </div>

                {/* Options */}
                <div>
                    <h3 className="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Options</h3>
                    <FormField type="checkbox" name="social_login_enabled" checkboxLabel="Enable social login buttons (Google, GitHub)" />
                </div>

                <div className="flex">
                    <Button type="submit" className="px-8">
                        <Save className="mr-2 h-4 w-4" />
                        Save Settings
                    </Button>
                </div>

            </div>
        </Form>
    );
}
