import { Head, Link, router, useForm } from '@inertiajs/react';
import {
    Bell,
    CalendarDays,
    CheckCircle2,
    CreditCard,
    Eye,
    FileText,
    FlaskConical,
    Mail,
    Navigation,
    Pencil,
    Plus,
    Search,
    Trash2,
    Users,
    X,
    XCircle,
} from 'lucide-react';
import { useMemo, useState } from 'react';
import { FormDrawer } from '@/components/layout/form-drawer';
import { PageHeader } from '@/components/layout/page-header';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
    InputGroup,
    InputGroupAddon,
    InputGroupButton,
    InputGroupInput,
} from '@/components/ui/input-group';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import { EVENT_KEYS, RECIPIENT_TYPES, VARIABLES } from '@/lib/email-template-constants';
import { cn } from '@/lib/utils';
import adminEmailTemplates from '@/routes/admin/email-templates';

type TemplateEvent = { id: number; event_key: string; is_active: boolean };

type Template = {
    id: number;
    name: string;
    slug: string;
    description: string | null;
    subject: string;
    body_html: string;
    body_text: string | null;
    from_name: string | null;
    from_email: string | null;
    reply_to: string | null;
    is_active: boolean;
    is_system: boolean;
    sent_emails_count: number;
    open_rate: number | null;
    events: TemplateEvent[];
};

type Props = { templates: Template[] };

type TemplateCategory = 'bookings' | 'reminders' | 'service' | 'payments' | 'account' | 'custom';

type CategoryTab = 'all' | TemplateCategory;

const TEMPLATE_CATEGORIES: {
    id: TemplateCategory;
    label: string;
    description: string;
    icon: typeof Mail;
    accent: string;
    iconBg: string;
}[] = [
    {
        id: 'bookings',
        label: 'Bookings',
        description: 'Confirmations, cancellations, reschedules, and no-shows',
        icon: CalendarDays,
        accent: 'border-l-blue-500',
        iconBg: 'bg-blue-500/10 text-blue-600 dark:text-blue-400',
    },
    {
        id: 'reminders',
        label: 'Reminders',
        description: 'Automated nudges before the appointment',
        icon: Bell,
        accent: 'border-l-amber-500',
        iconBg: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',
    },
    {
        id: 'service',
        label: 'Service day',
        description: 'Technician en route, arrival, and job completion',
        icon: Navigation,
        accent: 'border-l-emerald-500',
        iconBg: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
    },
    {
        id: 'payments',
        label: 'Payments',
        description: 'Stripe receipts, failures, refunds, and balance due',
        icon: CreditCard,
        accent: 'border-l-violet-500',
        iconBg: 'bg-violet-500/10 text-violet-600 dark:text-violet-400',
    },
    {
        id: 'account',
        label: 'Account',
        description: 'Welcome emails and membership updates',
        icon: Users,
        accent: 'border-l-rose-500',
        iconBg: 'bg-rose-500/10 text-rose-600 dark:text-rose-400',
    },
    {
        id: 'custom',
        label: 'Custom',
        description: 'Templates you created for specific workflows',
        icon: FileText,
        accent: 'border-l-slate-500',
        iconBg: 'bg-slate-500/10 text-slate-600 dark:text-slate-400',
    },
];

function resolveTemplateCategory(template: Template): TemplateCategory {
    if (!template.is_system) {
        return 'custom';
    }

    const key = template.events[0]?.event_key ?? '';

    if (key === 'booking.balance_due' || key.startsWith('payment.')) {
        return 'payments';
    }

    if (key.startsWith('booking.reminder')) {
        return 'reminders';
    }

    if (key.startsWith('job.') || key === 'booking.arrived' || key === 'booking.completed') {
        return 'service';
    }

    if (key.startsWith('booking.')) {
        return 'bookings';
    }

    if (key.startsWith('customer.') || key.startsWith('membership.')) {
        return 'account';
    }

    return 'custom';
}

function categoryMeta(category: TemplateCategory) {
    return TEMPLATE_CATEGORIES.find((item) => item.id === category) ?? TEMPLATE_CATEGORIES[0];
}

function eventLabel(key: string) {
    return EVENT_KEYS.find((event) => event.value === key)?.label ?? key;
}

type EventFormRow = {
    id?: number;
    event_key: string;
    delay_minutes: number;
    is_active: boolean;
    recipients: string[];
    custom_email: string;
};

function emptyEvent(): EventFormRow {
    return { event_key: 'booking.confirmed', delay_minutes: 0, is_active: true, recipients: ['customer'], custom_email: '' };
}

type FormData = {
    name: string;
    description: string;
    subject: string;
    body_html: string;
    body_text: string;
    from_name: string;
    from_email: string;
    reply_to: string;
    is_active: boolean;
    events: EventFormRow[];
};

function emptyForm(): FormData {
    return {
        name: '',
        description: '',
        subject: '',
        body_html: '',
        body_text: '',
        from_name: '',
        from_email: '',
        reply_to: '',
        is_active: true,
        events: [emptyEvent()],
    };
}

function TemplateForm({
    form,
    setData,
    errors,
    processing,
    onSubmit,
}: {
    form: FormData;
    setData: (key: keyof FormData, value: unknown) => void;
    errors: Partial<Record<string, string>>;
    processing: boolean;
    onSubmit: (e: React.FormEvent) => void;
}) {
    const [previewHtml, setPreviewHtml] = useState<string | null>(null);
    const [previewLoading, setPreviewLoading] = useState(false);
    const [previewMode, setPreviewMode] = useState<'desktop' | 'mobile'>('desktop');

    const insertVariable = (variable: string, field: 'subject' | 'body_html' | 'body_text') => {
        setData(field, (form[field] as string) + variable);
    };

    const loadPreview = async () => {
        setPreviewLoading(true);

        try {
            setPreviewHtml(`<html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="margin:0;background:#f1f5f9;">${form.body_html}</body></html>`);
        } finally {
            setPreviewLoading(false);
        }
    };

    const updateEvent = (index: number, key: keyof EventFormRow, value: unknown) => {
        const events = [...form.events];
        (events[index] as Record<string, unknown>)[key] = value;
        setData('events', events);
    };

    const toggleRecipient = (eventIndex: number, type: string) => {
        const events = [...form.events];
        const current = events[eventIndex].recipients;
        events[eventIndex].recipients = current.includes(type)
            ? current.filter((r) => r !== type)
            : [...current, type];
        setData('events', events);
    };

    const addEvent = () => setData('events', [...form.events, emptyEvent()]);
    const removeEvent = (i: number) => setData('events', form.events.filter((_, idx) => idx !== i));

    return (
        <form onSubmit={onSubmit} className="flex flex-col gap-6">
            {/* Basic info */}
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div className="flex flex-col gap-1.5">
                    <Label>Name</Label>
                    <Input value={form.name} onChange={(e) => setData('name', e.target.value)} placeholder="Booking Confirmed" />
                    {errors.name && <p className="text-xs text-destructive">{errors.name}</p>}
                </div>
                <div className="flex flex-col gap-1.5">
                    <Label>Description</Label>
                    <Input value={form.description} onChange={(e) => setData('description', e.target.value)} placeholder="Optional" />
                </div>
            </div>

            <div className="flex flex-col gap-1.5">
                <Label>Subject</Label>
                <Input value={form.subject} onChange={(e) => setData('subject', e.target.value)} placeholder="Your booking is confirmed — {{booking_datetime}}" />
                {errors.subject && <p className="text-xs text-destructive">{errors.subject}</p>}
            </div>

            {/* Variables picker */}
            <div className="flex flex-col gap-2">
                <Label className="text-xs text-muted-foreground">Insert variable</Label>
                <div className="flex flex-wrap gap-1.5">
                    {VARIABLES.map((v) => (
                        <button
                            key={v}
                            type="button"
                            onClick={() => insertVariable(v, 'body_html')}
                            className="rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground hover:bg-primary/10 hover:text-primary"
                        >
                            {v}
                        </button>
                    ))}
                </div>
            </div>

            {/* HTML body */}
            <div className="flex flex-col gap-1.5">
                <div className="flex items-center justify-between">
                    <Label>HTML Body</Label>
                    <div className="flex gap-2">
                        <Button type="button" variant="outline" size="sm" onClick={loadPreview} disabled={previewLoading}>
                            <Eye className="mr-1 h-3.5 w-3.5" />
                            {previewLoading ? 'Loading…' : 'Preview'}
                        </Button>
                    </div>
                </div>
                <Textarea
                    value={form.body_html}
                    onChange={(e) => setData('body_html', e.target.value)}
                    className="min-h-[260px] font-mono text-xs"
                    placeholder="<!DOCTYPE html>…"
                />
                {errors.body_html && <p className="text-xs text-destructive">{errors.body_html}</p>}
            </div>

            {/* Live preview iframe */}
            {previewHtml && (
                <div className="flex flex-col gap-2">
                    <div className="flex items-center gap-2">
                        <Label>Preview</Label>
                        <div className="flex rounded-md border text-xs">
                            <button type="button" onClick={() => setPreviewMode('desktop')} className={`px-3 py-1 ${previewMode === 'desktop' ? 'bg-muted font-semibold' : ''}`}>Desktop</button>
                            <button type="button" onClick={() => setPreviewMode('mobile')} className={`px-3 py-1 ${previewMode === 'mobile' ? 'bg-muted font-semibold' : ''}`}>Mobile</button>
                        </div>
                    </div>
                    <div className={`overflow-hidden rounded-lg border bg-[#f1f5f9] transition-all ${previewMode === 'mobile' ? 'mx-auto max-w-[390px]' : 'w-full'}`}>
                        <iframe
                            srcDoc={previewHtml}
                            title="Email Preview"
                            className="w-full border-0"
                            style={{ height: 600 }}
                            sandbox="allow-same-origin"
                        />
                    </div>
                </div>
            )}

            {/* Plain text */}
            <div className="flex flex-col gap-1.5">
                <Label>Plain Text Fallback <span className="text-xs text-muted-foreground">(optional)</span></Label>
                <Textarea
                    value={form.body_text}
                    onChange={(e) => setData('body_text', e.target.value)}
                    className="min-h-[100px] font-mono text-xs"
                    placeholder="Hi {{customer_name}}, your booking is confirmed…"
                />
            </div>

            {/* From / Reply-to */}
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                <div className="flex flex-col gap-1.5">
                    <Label>From Name <span className="text-xs text-muted-foreground">(leave blank for default)</span></Label>
                    <Input value={form.from_name} onChange={(e) => setData('from_name', e.target.value)} placeholder="AIO Car Wash" />
                </div>
                <div className="flex flex-col gap-1.5">
                    <Label>From Email</Label>
                    <Input type="email" value={form.from_email} onChange={(e) => setData('from_email', e.target.value)} placeholder="hello@example.com" />
                </div>
                <div className="flex flex-col gap-1.5">
                    <Label>Reply-To</Label>
                    <Input type="email" value={form.reply_to} onChange={(e) => setData('reply_to', e.target.value)} placeholder="support@example.com" />
                </div>
            </div>

            {/* Active toggle */}
            <div className="flex items-center gap-3">
                <Switch checked={form.is_active} onCheckedChange={(v) => setData('is_active', v)} id="is_active" />
                <Label htmlFor="is_active">Active</Label>
            </div>

            {/* Events */}
            <div className="flex flex-col gap-3">
                <div className="flex items-center justify-between">
                    <Label>Event Triggers</Label>
                    <Button type="button" variant="outline" size="sm" onClick={addEvent}>
                        <Plus className="mr-1 h-3.5 w-3.5" /> Add Event
                    </Button>
                </div>

                {form.events.map((event, i) => (
                    <Card key={i} className="p-4">
                        <div className="flex flex-col gap-3">
                            <div className="flex items-start justify-between gap-2">
                                <div className="flex flex-1 flex-col gap-1.5">
                                    <Label className="text-xs">Event</Label>
                                    <Select value={event.event_key} onValueChange={(v) => updateEvent(i, 'event_key', v)}>
                                        <SelectTrigger className="h-8 text-xs">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {EVENT_KEYS.map((ek) => (
                                                <SelectItem key={ek.value} value={ek.value} className="text-xs">{ek.label}</SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div className="flex flex-col gap-1.5">
                                    <Label className="text-xs">Delay (min)</Label>
                                    <Input
                                        type="number"
                                        min="0"
                                        value={event.delay_minutes}
                                        onChange={(e) => updateEvent(i, 'delay_minutes', parseInt(e.target.value) || 0)}
                                        className="h-8 w-24 text-xs"
                                    />
                                </div>
                                <div className="mt-5 flex items-center gap-1.5">
                                    <Switch checked={event.is_active} onCheckedChange={(v) => updateEvent(i, 'is_active', v)} />
                                    {form.events.length > 1 && (
                                        <Button type="button" variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => removeEvent(i)}>
                                            <Trash2 className="h-3.5 w-3.5" />
                                        </Button>
                                    )}
                                </div>
                            </div>

                            <div className="flex flex-col gap-1.5">
                                <Label className="text-xs">Recipients</Label>
                                <div className="flex flex-wrap gap-2">
                                    {RECIPIENT_TYPES.map((r) => (
                                        <button
                                            key={r.value}
                                            type="button"
                                            onClick={() => toggleRecipient(i, r.value)}
                                            className={`rounded-full border px-3 py-0.5 text-xs font-medium transition-colors ${
                                                event.recipients.includes(r.value)
                                                    ? 'border-primary bg-primary/10 text-primary'
                                                    : 'border-border text-muted-foreground hover:border-primary/50'
                                            }`}
                                        >
                                            {r.label}
                                        </button>
                                    ))}
                                </div>
                                {event.recipients.includes('custom_email') && (
                                    <Input
                                        type="email"
                                        value={event.custom_email}
                                        onChange={(e) => updateEvent(i, 'custom_email', e.target.value)}
                                        placeholder="custom@email.com"
                                        className="mt-1 h-8 text-xs"
                                    />
                                )}
                            </div>
                        </div>
                    </Card>
                ))}
            </div>

            <Button type="submit" disabled={processing} className="w-full sm:w-auto">
                {processing ? 'Saving…' : 'Save Template'}
            </Button>
        </form>
    );
}

function TemplateCard({
    template,
    category,
    onTest,
    onDelete,
}: {
    template: Template;
    category: TemplateCategory;
    onTest: (template: Template) => void;
    onDelete: (template: Template) => void;
}) {
    const meta = categoryMeta(category);
    const CategoryIcon = meta.icon;

    return (
        <Card
            className={cn(
                'flex flex-col border-l-4 transition-shadow hover:shadow-md',
                meta.accent,
                !template.is_active && 'opacity-60',
            )}
        >
            <CardHeader className="gap-3 pb-3">
                <div className="flex items-start justify-between gap-3">
                    <div className="flex min-w-0 items-start gap-3">
                        <div className={cn('mt-0.5 rounded-lg p-2', meta.iconBg)}>
                            <CategoryIcon className="h-4 w-4" />
                        </div>
                        <div className="min-w-0 flex-1">
                            <div className="flex flex-wrap items-center gap-2">
                                <CardTitle className="text-sm leading-tight">{template.name}</CardTitle>
                                {template.is_system ? (
                                    <Badge variant="secondary" className="text-[10px]">System</Badge>
                                ) : (
                                    <Badge variant="outline" className="text-[10px]">Custom</Badge>
                                )}
                            </div>
                            {template.description && (
                                <p className="mt-1 line-clamp-2 text-xs text-muted-foreground">{template.description}</p>
                            )}
                        </div>
                    </div>
                    {template.is_active ? (
                        <CheckCircle2 className="h-4 w-4 shrink-0 text-emerald-500" aria-label="Active" />
                    ) : (
                        <XCircle className="h-4 w-4 shrink-0 text-muted-foreground" aria-label="Inactive" />
                    )}
                </div>
            </CardHeader>
            <CardContent className="flex flex-1 flex-col gap-3 pt-0">
                <div className="flex flex-wrap gap-1">
                    {template.events.map((event) => (
                        <Badge
                            key={event.id}
                            variant={event.is_active ? 'outline' : 'secondary'}
                            className="text-[10px] font-normal"
                        >
                            {eventLabel(event.event_key)}
                        </Badge>
                    ))}
                    {template.events.length === 0 && (
                        <span className="text-xs text-muted-foreground">No triggers configured</span>
                    )}
                </div>

                <div className="rounded-md border bg-muted/30 px-3 py-2">
                    <p className="mb-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">Subject</p>
                    <p className="truncate font-mono text-xs">{template.subject}</p>
                </div>

                <div className="flex items-center gap-4 text-xs text-muted-foreground">
                    <span>{template.sent_emails_count.toLocaleString()} sent</span>
                    {template.open_rate !== null && (
                        <span>{template.open_rate}% open rate</span>
                    )}
                </div>

                <div className="mt-auto flex gap-2 pt-1">
                    <Link
                        href={adminEmailTemplates.edit.url(template.id)}
                        className="flex flex-1 items-center justify-center gap-1 rounded-md border border-input bg-background px-3 py-1.5 text-xs font-medium hover:bg-accent hover:text-accent-foreground"
                    >
                        <Pencil className="h-3 w-3" /> Edit
                    </Link>
                    <Button variant="outline" size="sm" className="text-xs" onClick={() => onTest(template)}>
                        <FlaskConical className="mr-1 h-3 w-3" /> Test
                    </Button>
                    {!template.is_system && (
                        <Button
                            variant="ghost"
                            size="sm"
                            className="text-xs text-destructive hover:text-destructive"
                            onClick={() => onDelete(template)}
                        >
                            <Trash2 className="h-3 w-3" />
                        </Button>
                    )}
                </div>
            </CardContent>
        </Card>
    );
}

export default function AdminEmailTemplatesIndex({ templates }: Props) {
    const [search, setSearch] = useState('');
    const [activeTab, setActiveTab] = useState<CategoryTab>('all');
    const [createOpen, setCreateOpen] = useState(false);
    const [sendTestOpen, setSendTestOpen] = useState<Template | null>(null);

    const templatesWithCategory = useMemo(
        () => templates.map((template) => ({ template, category: resolveTemplateCategory(template) })),
        [templates],
    );

    const searched = useMemo(() => {
        const q = search.trim().toLowerCase();

        if (!q) {
            return templatesWithCategory;
        }

        return templatesWithCategory.filter(
            ({ template }) =>
                template.name.toLowerCase().includes(q) ||
                (template.description ?? '').toLowerCase().includes(q) ||
                template.subject.toLowerCase().includes(q) ||
                template.events.some((event) => event.event_key.toLowerCase().includes(q)),
        );
    }, [templatesWithCategory, search]);

    const tabCounts = useMemo(() => {
        const counts: Record<CategoryTab, number> = {
            all: searched.length,
            bookings: 0,
            reminders: 0,
            service: 0,
            payments: 0,
            account: 0,
            custom: 0,
        };

        for (const item of searched) {
            counts[item.category] += 1;
        }

        return counts;
    }, [searched]);

    const visibleItems = useMemo(() => {
        if (activeTab === 'all') {
            return searched;
        }

        return searched.filter((item) => item.category === activeTab);
    }, [searched, activeTab]);

    const groupedItems = useMemo(() => {
        return TEMPLATE_CATEGORIES.map((category) => ({
            category,
            items: visibleItems.filter((item) => item.category === category.id),
        })).filter((group) => group.items.length > 0);
    }, [visibleItems]);

    const stats = useMemo(() => {
        const activeCount = templates.filter((template) => template.is_active).length;
        const totalSent = templates.reduce((sum, template) => sum + template.sent_emails_count, 0);
        const openRates = templates
            .map((template) => template.open_rate)
            .filter((rate): rate is number => rate !== null);
        const avgOpenRate = openRates.length > 0
            ? Math.round((openRates.reduce((sum, rate) => sum + rate, 0) / openRates.length) * 10) / 10
            : null;

        return { activeCount, totalSent, avgOpenRate, customCount: templates.filter((template) => !template.is_system).length };
    }, [templates]);
    const [testEmail, setTestEmail] = useState('');
    const [testLoading, setTestLoading] = useState(false);
    const [testResult, setTestResult] = useState<string | null>(null);

    const createForm = useForm<FormData>(emptyForm());

    const submitCreate = (e: React.FormEvent) => {
        e.preventDefault();
        createForm.post(adminEmailTemplates.store.url(), {
            onSuccess: () => {
 setCreateOpen(false); createForm.reset();
},
        });
    };

    const deleteTemplate = (template: Template) => {
        if (!confirm(`Delete "${template.name}"?`)) {
return;
}

        router.delete(adminEmailTemplates.destroy.url(template.id));
    };

    const sendTest = async () => {
        if (!sendTestOpen || !testEmail) {
return;
}

        setTestLoading(true);
        setTestResult(null);

        try {
            const res = await fetch(adminEmailTemplates.sendTest.url(sendTestOpen.id), {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '' },
                body: JSON.stringify({ to_email: testEmail }),
            });
            const data = await res.json();
            setTestResult(data.message ?? 'Sent!');
        } catch {
            setTestResult('Failed to send test email.');
        } finally {
            setTestLoading(false);
        }
    };

    const openSendTest = (template: Template) => {
        setSendTestOpen(template);
        setTestEmail('');
        setTestResult(null);
    };

    const renderTemplateGrid = (items: { template: Template; category: TemplateCategory }[]) => (
        <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
            {items.map(({ template, category }) => (
                <TemplateCard
                    key={template.id}
                    template={template}
                    category={category}
                    onTest={openSendTest}
                    onDelete={deleteTemplate}
                />
            ))}
        </div>
    );

    return (
        <>
            <Head title="Email Templates" />
            <div className="flex flex-col gap-6 p-4 md:p-6">
                <PageHeader
                    title="Email Templates"
                    description="Manage transactional email templates sent to customers and staff."
                    actions={
                        <Button onClick={() => setCreateOpen(true)}>
                            <Plus className="mr-1.5 h-4 w-4" /> New Template
                        </Button>
                    }
                />

                <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
                    <Card size="sm">
                        <CardHeader>
                            <CardDescription>Templates</CardDescription>
                            <CardTitle>{templates.length}</CardTitle>
                        </CardHeader>
                        <CardContent className="flex items-center gap-2 text-muted-foreground">
                            <Mail className="size-4" />
                            <span className="text-xs">{stats.customCount} custom</span>
                        </CardContent>
                    </Card>
                    <Card size="sm">
                        <CardHeader>
                            <CardDescription>Active</CardDescription>
                            <CardTitle>{stats.activeCount}</CardTitle>
                        </CardHeader>
                        <CardContent className="flex items-center gap-2 text-muted-foreground">
                            <CheckCircle2 className="size-4" />
                            <span className="text-xs">Sending on trigger</span>
                        </CardContent>
                    </Card>
                    <Card size="sm">
                        <CardHeader>
                            <CardDescription>Total sent</CardDescription>
                            <CardTitle>{stats.totalSent.toLocaleString()}</CardTitle>
                        </CardHeader>
                        <CardContent className="flex items-center gap-2 text-muted-foreground">
                            <FlaskConical className="size-4" />
                            <span className="text-xs">Across all templates</span>
                        </CardContent>
                    </Card>
                    <Card size="sm">
                        <CardHeader>
                            <CardDescription>Avg. open rate</CardDescription>
                            <CardTitle>{stats.avgOpenRate !== null ? `${stats.avgOpenRate}%` : '—'}</CardTitle>
                        </CardHeader>
                        <CardContent className="flex items-center gap-2 text-muted-foreground">
                            <Eye className="size-4" />
                            <span className="text-xs">Tracked deliveries</span>
                        </CardContent>
                    </Card>
                </div>

                <div className="rounded-xl border bg-card shadow-sm">
                    <div className="flex flex-col gap-3 border-b px-4 py-3 lg:flex-row lg:items-center lg:justify-between">
                        <Tabs
                            value={activeTab}
                            onValueChange={(value) => setActiveTab(value as CategoryTab)}
                        >
                            <TabsList className="h-auto flex-wrap justify-start">
                                <TabsTrigger value="all" className="gap-1.5">
                                    <Mail className="size-3.5" />
                                    All
                                    {tabCounts.all > 0 && (
                                        <span className="rounded-full bg-background/60 px-1.5 py-0.5 text-[10px] font-medium tabular-nums">
                                            {tabCounts.all}
                                        </span>
                                    )}
                                </TabsTrigger>
                                {TEMPLATE_CATEGORIES.map((category) => {
                                    const Icon = category.icon;

                                    return (
                                        <TabsTrigger key={category.id} value={category.id} className="gap-1.5">
                                            <Icon className="size-3.5" />
                                            {category.label}
                                            {tabCounts[category.id] > 0 && (
                                                <span className="rounded-full bg-background/60 px-1.5 py-0.5 text-[10px] font-medium tabular-nums">
                                                    {tabCounts[category.id]}
                                                </span>
                                            )}
                                        </TabsTrigger>
                                    );
                                })}
                            </TabsList>
                        </Tabs>

                        <div className="flex items-center gap-3">
                            <InputGroup className="h-9 w-full sm:w-64">
                                <InputGroupAddon align="inline-start">
                                    <Search className="size-3.5 text-muted-foreground" />
                                </InputGroupAddon>
                                <InputGroupInput
                                    placeholder="Search templates…"
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                />
                                {search && (
                                    <InputGroupAddon align="inline-end">
                                        <InputGroupButton
                                            size="icon-xs"
                                            variant="ghost"
                                            onClick={() => setSearch('')}
                                        >
                                            <X className="pointer-events-none" />
                                        </InputGroupButton>
                                    </InputGroupAddon>
                                )}
                            </InputGroup>
                            {search && (
                                <span className="shrink-0 text-xs text-muted-foreground">
                                    {searched.length} of {templates.length}
                                </span>
                            )}
                        </div>
                    </div>

                    <div className="p-4 md:p-6">
                        {templates.length === 0 ? (
                            <div className="flex flex-col items-center gap-3 py-16 text-center">
                                <Mail className="h-10 w-10 text-muted-foreground/40" />
                                <p className="text-sm text-muted-foreground">No email templates yet.</p>
                                <Button onClick={() => setCreateOpen(true)}>
                                    <Plus className="mr-1.5 h-4 w-4" /> Create First Template
                                </Button>
                            </div>
                        ) : visibleItems.length === 0 ? (
                            <div className="flex flex-col items-center gap-2 py-16 text-center">
                                <Search className="h-8 w-8 text-muted-foreground/40" />
                                <p className="text-sm font-medium">No templates in this category</p>
                                <p className="max-w-sm text-xs text-muted-foreground">
                                    Try another tab or clear your search to see more templates.
                                </p>
                            </div>
                        ) : activeTab === 'all' ? (
                            <div className="flex flex-col gap-10">
                                {groupedItems.map(({ category, items }) => {
                                    const Icon = category.icon;

                                    return (
                                        <section key={category.id} className="flex flex-col gap-4">
                                            <div className="flex items-start gap-3">
                                                <div className={cn('rounded-lg p-2.5', category.iconBg)}>
                                                    <Icon className="h-4 w-4" />
                                                </div>
                                                <div className="min-w-0 flex-1">
                                                    <div className="flex flex-wrap items-center gap-2">
                                                        <h2 className="text-sm font-semibold">{category.label}</h2>
                                                        <Badge variant="secondary" className="text-[10px]">
                                                            {items.length}
                                                        </Badge>
                                                    </div>
                                                    <p className="mt-0.5 text-xs text-muted-foreground">{category.description}</p>
                                                </div>
                                            </div>
                                            {renderTemplateGrid(items)}
                                        </section>
                                    );
                                })}
                            </div>
                        ) : (
                            <div className="flex flex-col gap-4">
                                <div className="flex items-start gap-3">
                                    {(() => {
                                        const category = categoryMeta(activeTab);
                                        const Icon = category.icon;

                                        return (
                                            <>
                                                <div className={cn('rounded-lg p-2.5', category.iconBg)}>
                                                    <Icon className="h-4 w-4" />
                                                </div>
                                                <div>
                                                    <h2 className="text-sm font-semibold">{category.label}</h2>
                                                    <p className="mt-0.5 text-xs text-muted-foreground">{category.description}</p>
                                                </div>
                                            </>
                                        );
                                    })()}
                                </div>
                                {renderTemplateGrid(visibleItems)}
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Create drawer */}
            <FormDrawer
                open={createOpen}
                onOpenChange={setCreateOpen}
                title="New Email Template"
                description="Create a new transactional email template."
            >
                <TemplateForm
                    form={createForm.data}
                    setData={(k, v) => createForm.setData(k, v as never)}
                    errors={createForm.errors}
                    processing={createForm.processing}
                    onSubmit={submitCreate}
                />
            </FormDrawer>

            {/* Send test drawer */}
            <FormDrawer
                open={!!sendTestOpen}
                onOpenChange={(open) => {
 if (!open) {
setSendTestOpen(null);
}
}}
                title="Send Test Email"
                description={sendTestOpen ? `Send a test of "${sendTestOpen.name}" to an email address.` : ''}
            >
                <div className="flex flex-col gap-4">
                    <div className="flex flex-col gap-1.5">
                        <Label>Send to</Label>
                        <Input
                            type="email"
                            value={testEmail}
                            onChange={(e) => setTestEmail(e.target.value)}
                            placeholder="you@example.com"
                        />
                    </div>
                    {testResult && (
                        <p className={`text-sm ${testResult.startsWith('Failed') ? 'text-destructive' : 'text-emerald-600'}`}>
                            {testResult}
                        </p>
                    )}
                    <Button onClick={sendTest} disabled={testLoading || !testEmail}>
                        <FlaskConical className="mr-1.5 h-4 w-4" />
                        {testLoading ? 'Sending…' : 'Send Test'}
                    </Button>
                </div>
            </FormDrawer>
        </>
    );
}
