import { Head, router } from '@inertiajs/react';
import { CheckCircle2, Eye, Mail, MousePointerClick, XCircle } from 'lucide-react';
import { useState } from 'react';
import { PageHeader } from '@/components/layout/page-header';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import adminSentEmails from '@/routes/admin/sent-emails';

type SentEmail = {
    id: string;
    to_email: string;
    to_name: string | null;
    subject: string;
    event_key: string | null;
    template: { id: number; name: string } | null;
    status: string;
    opened_at: string | null;
    open_count: number;
    click_count: number;
    created_at: string;
};

type Paginated<T> = {
    data: T[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    links: { url: string | null; label: string; active: boolean }[];
};

type Props = {
    emails: Paginated<SentEmail>;
    filters: { search?: string; event_key?: string; status?: string };
};

const STATUS_LABELS: Record<string, { label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline' }> = {
    queued: { label: 'Queued', variant: 'secondary' },
    sent: { label: 'Sent', variant: 'outline' },
    delivered: { label: 'Delivered', variant: 'default' },
    bounced: { label: 'Bounced', variant: 'destructive' },
    failed: { label: 'Failed', variant: 'destructive' },
};

function formatDate(iso: string): string {
    return new Date(iso).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
}

export default function AdminSentEmailsIndex({ emails, filters }: Props) {
    const [search, setSearch] = useState(filters.search ?? '');
    const [status, setStatus] = useState(filters.status ?? '');
    const [previewEmail, setPreviewEmail] = useState<SentEmail | null>(null);
    const [previewHtml, setPreviewHtml] = useState<string | null>(null);

    const applyFilters = (overrides: Partial<typeof filters> = {}) => {
        router.get(adminSentEmails.index.url(), {
            search: overrides.search ?? search,
            status: overrides.status ?? status,
        }, { preserveState: true, replace: true });
    };

    const openPreview = async (email: SentEmail) => {
        setPreviewEmail(email);
        setPreviewHtml(null);
        try {
            const res = await fetch(`/admin/sent-emails/${email.id}/html`);
            if (res.ok) setPreviewHtml(await res.text());
        } catch { /* silent */ }
    };

    const { data: rows, total, links } = emails;

    return (
        <>
            <Head title="Sent Emails" />
            <div className="flex flex-col gap-6 p-4 md:p-6">
                <PageHeader
                    title="Sent Emails"
                    description={`${total.toLocaleString()} emails in log`}
                />

                {/* Filters */}
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
                    <Input
                        placeholder="Search by email or subject…"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        onKeyDown={(e) => e.key === 'Enter' && applyFilters({ search })}
                        className="sm:max-w-xs"
                    />
                    <Select value={status || 'all'} onValueChange={(v) => { setStatus(v === 'all' ? '' : v); applyFilters({ status: v === 'all' ? '' : v }); }}>
                        <SelectTrigger className="w-40">
                            <SelectValue placeholder="All statuses" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="all">All statuses</SelectItem>
                            {Object.entries(STATUS_LABELS).map(([val, { label }]) => (
                                <SelectItem key={val} value={val}>{label}</SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                    <Button variant="outline" onClick={() => applyFilters({ search })}>Search</Button>
                </div>

                {/* Table — card layout on mobile, table on md+ */}
                <Card>
                    <CardContent className="p-0">
                        {/* Desktop */}
                        <div className="hidden md:block">
                            <table className="w-full text-sm">
                                <thead>
                                    <tr className="border-b text-xs text-muted-foreground">
                                        <th className="px-4 py-3 text-left font-medium">To</th>
                                        <th className="px-4 py-3 text-left font-medium">Subject</th>
                                        <th className="px-4 py-3 text-left font-medium">Template</th>
                                        <th className="px-4 py-3 text-left font-medium">Status</th>
                                        <th className="px-4 py-3 text-left font-medium">Opens</th>
                                        <th className="px-4 py-3 text-left font-medium">Clicks</th>
                                        <th className="px-4 py-3 text-left font-medium">Sent</th>
                                        <th className="px-4 py-3" />
                                    </tr>
                                </thead>
                                <tbody>
                                    {rows.map((email) => {
                                        const s = STATUS_LABELS[email.status] ?? { label: email.status, variant: 'secondary' as const };
                                        return (
                                            <tr key={email.id} className="border-b last:border-0 hover:bg-muted/30">
                                                <td className="px-4 py-3">
                                                    <div className="font-medium">{email.to_name ?? email.to_email}</div>
                                                    {email.to_name && <div className="text-xs text-muted-foreground">{email.to_email}</div>}
                                                </td>
                                                <td className="max-w-[260px] truncate px-4 py-3 text-xs">{email.subject}</td>
                                                <td className="px-4 py-3 text-xs text-muted-foreground">{email.template?.name ?? email.event_key ?? '—'}</td>
                                                <td className="px-4 py-3">
                                                    <Badge variant={s.variant} className="text-[10px]">{s.label}</Badge>
                                                </td>
                                                <td className="px-4 py-3">
                                                    <div className="flex items-center gap-1.5">
                                                        {email.opened_at
                                                            ? <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
                                                            : <XCircle className="h-3.5 w-3.5 text-muted-foreground/40" />
                                                        }
                                                        <span className="text-xs">{email.open_count}</span>
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3">
                                                    <div className="flex items-center gap-1.5">
                                                        <MousePointerClick className="h-3.5 w-3.5 text-muted-foreground" />
                                                        <span className="text-xs">{email.click_count}</span>
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3 text-xs text-muted-foreground">{formatDate(email.created_at)}</td>
                                                <td className="px-4 py-3">
                                                    <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openPreview(email)}>
                                                        <Eye className="h-3.5 w-3.5" />
                                                    </Button>
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>

                        {/* Mobile cards */}
                        <div className="flex flex-col divide-y md:hidden">
                            {rows.map((email) => {
                                const s = STATUS_LABELS[email.status] ?? { label: email.status, variant: 'secondary' as const };
                                return (
                                    <div key={email.id} className="flex items-start justify-between gap-3 p-4">
                                        <div className="flex min-w-0 flex-col gap-1">
                                            <div className="flex items-center gap-2">
                                                <Badge variant={s.variant} className="text-[10px]">{s.label}</Badge>
                                                {email.opened_at && <CheckCircle2 className="h-3 w-3 text-emerald-500" />}
                                            </div>
                                            <p className="truncate text-sm font-medium">{email.to_email}</p>
                                            <p className="truncate text-xs text-muted-foreground">{email.subject}</p>
                                            <p className="text-xs text-muted-foreground">{formatDate(email.created_at)}</p>
                                        </div>
                                        <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0" onClick={() => openPreview(email)}>
                                            <Eye className="h-3.5 w-3.5" />
                                        </Button>
                                    </div>
                                );
                            })}
                        </div>

                        {rows.length === 0 && (
                            <div className="flex flex-col items-center gap-2 py-16 text-center">
                                <Mail className="h-8 w-8 text-muted-foreground/40" />
                                <p className="text-sm text-muted-foreground">No emails found.</p>
                            </div>
                        )}
                    </CardContent>
                </Card>

                {/* Pagination */}
                {emails.last_page > 1 && (
                    <div className="flex items-center justify-center gap-1">
                        {links.map((link, i) => (
                            <Button
                                key={i}
                                variant={link.active ? 'default' : 'outline'}
                                size="sm"
                                disabled={!link.url}
                                onClick={() => link.url && router.visit(link.url)}
                                dangerouslySetInnerHTML={{ __html: link.label }}
                                className="min-w-[36px] text-xs"
                            />
                        ))}
                    </div>
                )}
            </div>

            {/* Preview sheet */}
            <Sheet open={!!previewEmail} onOpenChange={(open) => { if (!open) setPreviewEmail(null); }}>
                <SheetContent side="right" className="w-full max-w-2xl overflow-y-auto">
                    <SheetHeader>
                        <SheetTitle className="text-sm">Email Preview</SheetTitle>
                        {previewEmail && (
                            <div className="flex flex-col gap-1 text-xs text-muted-foreground">
                                <span><strong>To:</strong> {previewEmail.to_email}</span>
                                <span><strong>Subject:</strong> {previewEmail.subject}</span>
                                <span><strong>Sent:</strong> {formatDate(previewEmail.created_at)}</span>
                                <div className="flex gap-3">
                                    <span className="flex items-center gap-1">
                                        {previewEmail.opened_at ? <CheckCircle2 className="h-3 w-3 text-emerald-500" /> : <XCircle className="h-3 w-3 text-muted-foreground" />}
                                        {previewEmail.open_count} opens
                                    </span>
                                    <span className="flex items-center gap-1">
                                        <MousePointerClick className="h-3 w-3 text-muted-foreground" />
                                        {previewEmail.click_count} clicks
                                    </span>
                                </div>
                            </div>
                        )}
                    </SheetHeader>
                    <div className="mt-4 overflow-hidden rounded-lg border bg-[#f1f5f9]">
                        {previewHtml ? (
                            <iframe
                                srcDoc={previewHtml}
                                title="Email HTML"
                                className="w-full border-0"
                                style={{ height: 600 }}
                                sandbox="allow-same-origin"
                            />
                        ) : (
                            <div className="flex items-center justify-center py-20 text-sm text-muted-foreground">
                                Loading preview…
                            </div>
                        )}
                    </div>
                </SheetContent>
            </Sheet>
        </>
    );
}
