import { Head, useForm } from '@inertiajs/react';
import {
    Check,
    CheckCircle2,
    GalleryHorizontal,
    Info,
    LayoutGrid,
    Rows3,
    Sparkles,
    Star,
    Store,
    type LucideIcon,
} from 'lucide-react';
import { type FormEvent, useState } from 'react';
import { FormField } from '@/components/form-field';
import { PageHeader } from '@/components/layout/page-header';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
import { cn } from '@/lib/utils';
import AppLayout from '@/layouts/app-layout';
import adminHomepageLayout from '@/routes/admin/homepage-layout';

type AdminPackage = {
    id: number;
    name: string;
    is_featured: boolean;
};

type ServicesStyle = 'bento' | 'list' | 'marquee';

type Props = {
    bentoLayout: string;
    servicesStyle: ServicesStyle;
    servicesSectionEnabled: boolean;
    packages: AdminPackage[];
    maxCols: number;
    maxRows: number;
    headerBrandName: string;
    headerTagline: string;
    headerPhone: string;
};

type Size = { cols: number; rows: number };

const STYLE_OPTIONS: {
    value: ServicesStyle;
    label: string;
    hint: string;
    icon: LucideIcon;
    badge?: string;
}[] = [
    {
        value: 'bento',
        label: 'Bento grid',
        hint: 'Configurable tile layout with variable sizing',
        icon: LayoutGrid,
        badge: 'Recommended',
    },
    {
        value: 'list',
        label: 'List view',
        hint: 'Stacked rows with pricing visible at a glance',
        icon: Rows3,
    },
    {
        value: 'marquee',
        label: 'Scrolling marquee',
        hint: 'Infinite horizontal scroll of service titles only',
        icon: GalleryHorizontal,
    },
];

const PREVIEW_COL: Record<number, string> = {
    1: 'col-span-1',
    2: 'col-span-2',
    3: 'col-span-3',
    4: 'col-span-4',
};

const PREVIEW_ROW: Record<number, string> = {
    1: 'row-span-1',
    2: 'row-span-2',
    3: 'row-span-3',
    4: 'row-span-4',
};

function clamp(value: number, max: number): number {
    return Math.max(1, Math.min(value, max));
}

function parseLayout(layout: string, maxCols: number, maxRows: number): Size[] {
    if (!layout.trim()) return [];
    const sizes: Size[] = [];
    for (const raw of layout.split(',')) {
        const match = /^(\d+)x(\d+)$/i.exec(raw.trim());
        if (!match) continue;
        sizes.push({
            cols: clamp(Number(match[1]), maxCols),
            rows: clamp(Number(match[2]), maxRows),
        });
    }
    return sizes;
}

function sizeForIndex(sizes: Size[], index: number, isFeatured: boolean): Size {
    return sizes[index] ?? (isFeatured ? { cols: 2, rows: 2 } : { cols: 1, rows: 1 });
}

function SaveButton({ processing, saved }: { processing: boolean; saved: boolean }) {
    return (
        <Button type="submit" disabled={processing} className="gap-2">
            {processing ? (
                <>
                    <span className="size-3.5 animate-spin rounded-full border-2 border-current border-t-transparent" />
                    Saving…
                </>
            ) : saved ? (
                <>
                    <CheckCircle2 className="size-4" />
                    Saved
                </>
            ) : (
                'Save changes'
            )}
        </Button>
    );
}

export default function AdminHomepageLayoutEdit({
    bentoLayout,
    servicesStyle,
    servicesSectionEnabled,
    packages,
    maxCols,
    maxRows,
    headerBrandName,
    headerTagline,
    headerPhone,
}: Props) {
    const form = useForm({
        brand_name: headerBrandName,
        tagline: headerTagline,
        phone: headerPhone,
        services_style: servicesStyle,
        services_section_enabled: servicesSectionEnabled,
        bento_layout: bentoLayout ?? '',
    });
    const [saved, setSaved] = useState(false);
    const sizes = parseLayout(form.data.bento_layout, maxCols, maxRows);
    const isBento = form.data.services_style === 'bento';

    const submit = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        form.patch(adminHomepageLayout.update.url(), {
            onSuccess: () => {
                setSaved(true);
                setTimeout(() => setSaved(false), 3000);
            },
        });
    };

    return (
        <>
            <Head title="Homepage layout" />

            <div className="flex h-full flex-1 flex-col gap-6">

                {/* ── Page header ── */}
                <div className="flex items-start justify-between gap-4">
                    <PageHeader
                        title="Homepage layout"
                        description="Control how the services section renders on the public-facing homepage."
                    />
                    <div className="flex shrink-0 items-center gap-2 pt-1">
                        {saved && (
                            <span className="hidden items-center gap-1.5 text-sm text-emerald-600 sm:flex dark:text-emerald-400">
                                <CheckCircle2 className="size-4" />
                                Saved
                            </span>
                        )}
                        <Badge variant="outline" className="hidden text-xs sm:inline-flex">
                            {packages.length} package{packages.length !== 1 ? 's' : ''}
                        </Badge>
                    </div>
                </div>

                {/* ── Form ── extra bottom padding on mobile clears the fixed save bar */}
                <form onSubmit={submit} className="pb-24 lg:pb-0">
                    <div className="grid gap-6 lg:grid-cols-[1fr_360px] lg:items-start">


                        {/* ── LEFT COLUMN ── settings */}
                        <div className="space-y-5">

                            {/* Header identity */}
                            <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
                                <div className="border-b bg-muted/30 px-6 py-4">
                                    <div className="flex items-center gap-2">
                                        <Store className="size-4 text-primary" />
                                        <h2 className="text-sm font-semibold">Header identity</h2>
                                    </div>
                                    <p className="mt-0.5 text-xs text-muted-foreground">
                                        Shown in the sticky header across the homepage, booking wizard, and customer portal.
                                    </p>
                                </div>
                                <div className="grid gap-5 p-6 sm:grid-cols-3">
                                    <FormField label="Brand name" htmlFor="brand-name" error={form.errors.brand_name}>
                                        <Input
                                            id="brand-name"
                                            placeholder="AIO Car Wash"
                                            value={form.data.brand_name}
                                            onChange={(e) => form.setData('brand_name', e.target.value)}
                                        />
                                    </FormField>
                                    <FormField label="Tagline" htmlFor="tagline" error={form.errors.tagline}>
                                        <Input
                                            id="tagline"
                                            placeholder="Premium Auto Care"
                                            value={form.data.tagline}
                                            onChange={(e) => form.setData('tagline', e.target.value)}
                                        />
                                    </FormField>
                                    <FormField label="Phone number" htmlFor="header-phone" error={form.errors.phone}>
                                        <Input
                                            id="header-phone"
                                            placeholder="(800) 555-1234"
                                            value={form.data.phone}
                                            onChange={(e) => form.setData('phone', e.target.value)}
                                        />
                                    </FormField>
                                </div>
                            </div>

                            {/* Display style */}
                            <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
                                <div className="border-b bg-muted/30 px-6 py-4">
                                    <div className="flex items-center justify-between gap-2">
                                        <div className="flex items-center gap-2">
                                            <Sparkles className={cn('size-4 transition-colors', form.data.services_section_enabled ? 'text-primary' : 'text-muted-foreground')} />
                                            <h2 className="text-sm font-semibold">Display style</h2>
                                        </div>
                                        <div className="flex items-center gap-2">
                                            <span className="text-xs text-muted-foreground">
                                                {form.data.services_section_enabled ? 'Enabled' : 'Disabled'}
                                            </span>
                                            <Switch
                                                checked={form.data.services_section_enabled}
                                                onCheckedChange={(checked) => form.setData('services_section_enabled', checked)}
                                                aria-label="Toggle services section"
                                            />
                                        </div>
                                    </div>
                                    <p className="mt-0.5 text-xs text-muted-foreground">
                                        Choose how packages are presented to visitors.
                                    </p>
                                </div>
                                <div className={cn('p-6 transition-opacity', !form.data.services_section_enabled && 'pointer-events-none opacity-40')}>
                                    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                                        {STYLE_OPTIONS.map((option) => {
                                            const active = form.data.services_style === option.value;
                                            const Icon = option.icon;
                                            return (
                                                <button
                                                    key={option.value}
                                                    type="button"
                                                    aria-pressed={active}
                                                    onClick={() => form.setData('services_style', option.value)}
                                                    className={cn(
                                                        'group relative flex items-start gap-3 overflow-hidden rounded-xl border p-4 text-left transition-all duration-200',
                                                        'focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:outline-none',
                                                        active
                                                            ? 'border-primary bg-primary/5 shadow-sm ring-1 ring-primary/20'
                                                            : 'border-border hover:border-primary/30 hover:bg-muted/40',
                                                    )}
                                                >
                                                    <span className={cn(
                                                        'flex size-10 shrink-0 items-center justify-center rounded-lg transition-colors duration-200',
                                                        active
                                                            ? 'bg-primary text-primary-foreground'
                                                            : 'bg-muted text-muted-foreground group-hover:text-foreground',
                                                    )}>
                                                        <Icon className="size-5" />
                                                    </span>
                                                    <span className="min-w-0 flex-1">
                                                        <span className="flex items-center gap-2">
                                                            <span className="block text-sm font-semibold">{option.label}</span>
                                                            {option.badge && (
                                                                <span className="rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
                                                                    {option.badge}
                                                                </span>
                                                            )}
                                                        </span>
                                                        <span className="mt-0.5 block text-xs leading-relaxed text-muted-foreground">
                                                            {option.hint}
                                                        </span>
                                                    </span>
                                                    <span className={cn(
                                                        'flex size-4 shrink-0 items-center justify-center rounded-full border-2 transition-all duration-200',
                                                        active
                                                            ? 'border-primary bg-primary text-primary-foreground scale-100 opacity-100'
                                                            : 'border-border scale-90 opacity-50',
                                                    )}>
                                                        {active && <Check className="size-2.5" />}
                                                    </span>
                                                </button>
                                            );
                                        })}
                                    </div>
                                </div>
                            </div>

                            {/* Bento configuration */}
                            {isBento && (
                                <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
                                    <div className="border-b bg-muted/30 px-6 py-4">
                                        <div className="flex items-center gap-2">
                                            <LayoutGrid className="size-4 text-primary" />
                                            <h2 className="text-sm font-semibold">Bento grid configuration</h2>
                                        </div>
                                        <p className="mt-0.5 text-xs text-muted-foreground">
                                            Define tile sizes for each package in display order.
                                        </p>
                                    </div>
                                    <div className="space-y-5 p-6">
                                        <FormField label="Tile sizes" htmlFor="bento-layout" error={form.errors.bento_layout}>
                                            <Input
                                                id="bento-layout"
                                                placeholder="e.g. 2x2, 2x1, 1x1, 1x1"
                                                value={form.data.bento_layout}
                                                onChange={(e) => form.setData('bento_layout', e.target.value)}
                                                className="font-mono text-sm"
                                            />
                                        </FormField>
                                        <div className="space-y-3 rounded-lg border bg-muted/20 p-4">
                                            <div className="flex items-center gap-2 text-xs font-semibold text-foreground">
                                                <Info className="size-3.5 text-muted-foreground" />
                                                Syntax reference
                                            </div>
                                            <Separator />
                                            <div className="grid gap-2 text-xs text-muted-foreground">
                                                <div className="flex items-start gap-2">
                                                    <code className="shrink-0 rounded border bg-background px-1.5 py-0.5 font-mono text-foreground">WxH</code>
                                                    <span>Width × height in grid cells, comma-separated per package.</span>
                                                </div>
                                                <div className="flex items-start gap-2">
                                                    <code className="shrink-0 rounded border bg-background px-1.5 py-0.5 font-mono text-foreground">W</code>
                                                    <span>1–{maxCols} columns ({maxCols} = full width).</span>
                                                </div>
                                                <div className="flex items-start gap-2">
                                                    <code className="shrink-0 rounded border bg-background px-1.5 py-0.5 font-mono text-foreground">H</code>
                                                    <span>1–{maxRows} rows tall.</span>
                                                </div>
                                                <div className="flex items-start gap-2">
                                                    <span className="shrink-0 rounded border bg-background px-1.5 py-0.5 font-mono text-foreground">—</span>
                                                    <span>Omitted entries fall back to defaults: featured = 2×2, others = 1×1.</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* List view info */}
                            {!isBento && (
                                <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
                                    <div className="border-b bg-muted/30 px-6 py-4">
                                        <div className="flex items-center gap-2">
                                            <Rows3 className="size-4 text-primary" />
                                            <h2 className="text-sm font-semibold">List view settings</h2>
                                        </div>
                                    </div>
                                    <div className="p-6">
                                        <div className="flex items-start gap-3 rounded-lg border bg-muted/20 p-4">
                                            <Info className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
                                            <div className="text-sm text-muted-foreground">
                                                <p className="font-medium text-foreground">Automatic layout</p>
                                                <p className="mt-1">Packages render as stacked rows in display order. Tile sizing options are not applicable to this view style.</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* Desktop save bar — hidden on mobile */}
                            <div className="hidden items-center justify-between rounded-xl border bg-card px-6 py-4 shadow-sm lg:flex">
                                <p className="text-sm text-muted-foreground">
                                    Changes take effect immediately after saving.
                                </p>
                                <SaveButton processing={form.processing} saved={saved} />
                            </div>
                        </div>

                        {/* ── RIGHT COLUMN ── live preview (sticky on desktop) */}
                        <div className="lg:sticky lg:top-6 space-y-0">
                            <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
                                {/* Preview header with save button on desktop */}
                                <div className="border-b bg-muted/30 px-5 py-3.5">
                                    <div className="flex items-center justify-between gap-3">
                                        <p className="text-sm font-semibold">Live preview</p>
                                        <Badge variant="secondary" className="text-[10px]">
                                            {isBento ? 'Bento' : 'List'}
                                        </Badge>
                                    </div>
                                </div>

                                <div className="p-5">
                                    {packages.length === 0 ? (
                                        <div className="flex flex-col items-center justify-center gap-2 py-10 text-center">
                                            <div className="flex size-10 items-center justify-center rounded-full bg-muted">
                                                <LayoutGrid className="size-5 text-muted-foreground" />
                                            </div>
                                            <p className="text-sm text-muted-foreground">No active packages to preview.</p>
                                        </div>
                                    ) : (
                                        <div className="space-y-4">
                                            {/* Bento grid thumbnail */}
                                            {isBento && (
                                                <div className="grid auto-rows-[36px] grid-cols-4 gap-1.5 rounded-lg border bg-muted/20 p-3">
                                                    {packages.map((pkg, index) => {
                                                        const size = sizeForIndex(sizes, index, pkg.is_featured);
                                                        return (
                                                            <div
                                                                key={pkg.id}
                                                                title={pkg.name}
                                                                className={cn(
                                                                    'flex items-center justify-center rounded-md border text-[11px] font-bold transition-all',
                                                                    PREVIEW_COL[size.cols],
                                                                    PREVIEW_ROW[size.rows],
                                                                    pkg.is_featured
                                                                        ? 'border-primary/40 bg-primary/10 text-primary'
                                                                        : 'border-border bg-background text-muted-foreground',
                                                                )}
                                                            >
                                                                {index + 1}
                                                            </div>
                                                        );
                                                    })}
                                                </div>
                                            )}

                                            {/* Package legend */}
                                            <div className="space-y-1.5">
                                                {packages.map((pkg, index) => {
                                                    const size = sizeForIndex(sizes, index, pkg.is_featured);
                                                    const hasExplicit = index < sizes.length;
                                                    return (
                                                        <div
                                                            key={pkg.id}
                                                            className="flex items-center justify-between gap-3 rounded-lg px-3 py-2 text-sm transition-colors hover:bg-muted/40"
                                                        >
                                                            <span className="flex min-w-0 items-center gap-2.5">
                                                                <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-muted text-[10px] font-bold">
                                                                    {index + 1}
                                                                </span>
                                                                <span className="truncate font-medium">{pkg.name}</span>
                                                                {pkg.is_featured && (
                                                                    <Star className="size-3 shrink-0 fill-amber-400 text-amber-400" />
                                                                )}
                                                            </span>
                                                            {isBento && (
                                                                <span className={cn(
                                                                    'shrink-0 font-mono text-xs tabular-nums',
                                                                    hasExplicit ? 'text-foreground' : 'text-muted-foreground',
                                                                )}>
                                                                    {size.cols}×{size.rows}
                                                                    {!hasExplicit && (
                                                                        <span className="ml-1 text-[10px] text-muted-foreground/60">default</span>
                                                                    )}
                                                                </span>
                                                            )}
                                                        </div>
                                                    );
                                                })}
                                            </div>

                                            <Separator />
                                            <div className="flex flex-wrap gap-3 text-xs text-muted-foreground">
                                                <span className="flex items-center gap-1.5">
                                                    <Star className="size-3 fill-amber-400 text-amber-400" />
                                                    Featured package
                                                </span>
                                                {isBento && (
                                                    <span className="flex items-center gap-1.5">
                                                        <code className="rounded bg-muted px-1 text-[10px]">default</code>
                                                        Auto-sized
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>

                    </div>
                    {/* ── Mobile fixed bottom save bar (inside form so submit works) ── */}
                    <div className="fixed inset-x-0 bottom-0 z-30 border-t bg-background/95 px-4 py-3 backdrop-blur-sm lg:hidden">
                        <div className="mx-auto flex max-w-lg items-center justify-between gap-4">
                            <p className="text-sm text-muted-foreground">
                                {saved ? (
                                    <span className="flex items-center gap-1.5 text-emerald-600 dark:text-emerald-400">
                                        <CheckCircle2 className="size-4" />
                                        Changes saved
                                    </span>
                                ) : (
                                    'Tap to save your changes.'
                                )}
                            </p>
                            <SaveButton processing={form.processing} saved={saved} />
                        </div>
                    </div>
                </form>

            </div>
        </>
    );
}

AdminHomepageLayoutEdit.layout = (page: React.ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Website settings', href: '#' },
            { title: 'Homepage layout', href: adminHomepageLayout.edit.url() },
        ]}
    >
        {page}
    </AppLayout>
);
