import AdminLayout from '@/Layouts/AdminLayout';
import { DataTable, type TableMeta } from '@/components/admin/DataTable';
import PageHeader from '@/components/admin/PageHeader';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useDataTable, type TableParams } from '@/hooks/useDataTable';
import { api } from '@/lib/api';
import { parseServerDate } from '@/lib/date';
import { cn } from '@/lib/utils';
import { Head, Link } from '@inertiajs/react';
import {
    keepPreviousData,
    useQuery,
    useQueryClient,
} from '@tanstack/react-query';
import type { ColumnDef } from '@tanstack/react-table';
import { formatDistanceToNow } from 'date-fns';
import {
    ArchiveRestore,
    ArrowLeft,
    MoreHorizontal,
    ShieldOff,
    Trash2,
} from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';

// ── Types ─────────────────────────────────────────────────────────────────────

interface TrashedTestimonial {
    id: string;
    name: string;
    company: string | null;
    quote_excerpt: string;
    deleted_at: string;
}

interface TrashResponse {
    data: TrashedTestimonial[];
    meta: TableMeta;
    filter_counts: Record<string, number>;
}

// ── API helpers ───────────────────────────────────────────────────────────────

function fetchTrash(params: TableParams): Promise<TrashResponse> {
    const sp = new URLSearchParams({ page: String(params.page) });
    if (params.sort) sp.set('sort', params.sort);
    if (params.dir !== 'asc') sp.set('dir', params.dir);
    if (params.search) sp.set('search', params.search);
    return api.get(`/admin/api/testimonials/trash?${sp}`);
}

const apiRestore = (id: string) =>
    api.post(`/admin/testimonials/${id}/restore`);
const apiForceDelete = (id: string) =>
    api.delete(`/admin/testimonials/${id}/force`);
const apiBulkRestore = (ids: string[]) =>
    api.post('/admin/testimonials/bulk-restore', { ids });
const apiBulkForceDelete = (ids: string[]) =>
    api.post('/admin/testimonials/bulk-force-delete', { ids });

// ── Delete dialog descriptions ────────────────────────────────────────────────

function SingleDeleteDescription({
    testimonial,
}: {
    testimonial: TrashedTestimonial;
}) {
    return (
        <p>
            You are about to permanently delete the testimonial from{' '}
            <strong>{testimonial.name}</strong>. This action{' '}
            <strong>cannot be undone</strong>.
        </p>
    );
}

function BulkDeleteDescription({
    testimonials,
}: {
    testimonials: TrashedTestimonial[];
}) {
    return (
        <p>
            You are about to permanently delete{' '}
            <strong>{testimonials.length} testimonials</strong>. This action{' '}
            <strong>cannot be undone</strong>.
        </p>
    );
}

// ── Row actions ───────────────────────────────────────────────────────────────

function RowActions({
    testimonial,
    onRestore,
    onForceDelete,
}: {
    testimonial: TrashedTestimonial;
    onRestore: (t: TrashedTestimonial) => void;
    onForceDelete: (t: TrashedTestimonial) => void;
}) {
    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <button className="text-muted-foreground hover:bg-muted/60 hover:text-foreground flex h-7 w-7 items-center justify-center rounded-md transition-colors focus:outline-none">
                    <MoreHorizontal className="h-4 w-4" />
                    <span className="sr-only">
                        Actions for {testimonial.name}
                    </span>
                </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-48">
                <DropdownMenuItem
                    className="gap-2 text-xs"
                    onClick={() => onRestore(testimonial)}
                >
                    <ArchiveRestore className="h-3.5 w-3.5" />
                    Restore
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                    className="gap-2 text-xs text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"
                    onClick={() => onForceDelete(testimonial)}
                >
                    <ShieldOff className="h-3.5 w-3.5" />
                    Delete permanently
                </DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
    );
}

// ── Empty meta ────────────────────────────────────────────────────────────────

const EMPTY_META: TableMeta = {
    current_page: 1,
    last_page: 1,
    total: 0,
    per_page: 25,
    from: 0,
    to: 0,
};

// ── Page ──────────────────────────────────────────────────────────────────────

type DeleteTarget =
    | { kind: 'single'; testimonial: TrashedTestimonial }
    | { kind: 'bulk'; testimonials: TrashedTestimonial[] };

export default function TestimonialsTrash() {
    const qc = useQueryClient();
    const { params, setParams } = useDataTable({
        sort: 'deleted_at',
        dir: 'desc',
    });

    const { data, isLoading, isFetching } = useQuery({
        queryKey: ['admin.testimonials.trash', params],
        queryFn: () => fetchTrash(params),
        placeholderData: keepPreviousData,
    });

    const invalidate = () => {
        qc.invalidateQueries({ queryKey: ['admin.testimonials.trash'] });
        qc.invalidateQueries({ queryKey: ['admin.testimonials'] });
    };

    // ── Delete modal state ─────────────────────────────────────────────────────
    const [deleteTarget, setDeleteTarget] = useState<DeleteTarget | null>(null);
    const [deleting, setDeleting] = useState(false);

    const openSingleDelete = (testimonial: TrashedTestimonial) =>
        setDeleteTarget({ kind: 'single', testimonial });
    const openBulkDelete = (testimonials: TrashedTestimonial[]) =>
        setDeleteTarget({ kind: 'bulk', testimonials });
    const closeDelete = () => {
        if (!deleting) setDeleteTarget(null);
    };

    const handleConfirmDelete = async () => {
        if (!deleteTarget) return;
        setDeleting(true);
        try {
            if (deleteTarget.kind === 'single') {
                await apiForceDelete(deleteTarget.testimonial.id);
                toast.success(
                    `Testimonial from ${deleteTarget.testimonial.name} permanently deleted`,
                );
            } else {
                await apiBulkForceDelete(
                    deleteTarget.testimonials.map((t) => t.id),
                );
                toast.success(
                    `${deleteTarget.testimonials.length} testimonials permanently deleted`,
                );
            }
            invalidate();
            setDeleteTarget(null);
        } catch {
            toast.error('Failed to permanently delete');
        } finally {
            setDeleting(false);
        }
    };

    // ── Restore handlers ───────────────────────────────────────────────────────
    const handleRestore = async (testimonial: TrashedTestimonial) => {
        try {
            await apiRestore(testimonial.id);
            toast.success(`Testimonial from ${testimonial.name} restored`);
            invalidate();
        } catch {
            toast.error('Failed to restore testimonial');
        }
    };

    const handleBulkRestore = async (rows: TrashedTestimonial[]) => {
        try {
            await apiBulkRestore(rows.map((t) => t.id));
            toast.success(`${rows.length} testimonials restored`);
            invalidate();
        } catch {
            toast.error('Failed to restore testimonials');
        }
    };

    // ── Columns ────────────────────────────────────────────────────────────────
    const columns: ColumnDef<TrashedTestimonial, unknown>[] = [
        {
            accessorKey: 'name',
            header: 'Name',
            meta: { sortable: true, label: 'Name' },
            cell: ({ row }) => (
                <div className="min-w-0">
                    <span className="text-foreground/60 block truncate text-sm font-medium line-through">
                        {row.original.name}
                    </span>
                    <p className="text-muted-foreground mt-0.5 truncate text-[11px]">
                        {row.original.quote_excerpt}
                    </p>
                </div>
            ),
        },
        {
            accessorKey: 'company',
            header: 'Company',
            meta: { label: 'Company' },
            cell: ({ row }) => (
                <span className="text-muted-foreground text-sm">
                    {row.original.company ?? '—'}
                </span>
            ),
        },
        {
            accessorKey: 'deleted_at',
            header: 'Deleted',
            meta: { sortable: true, label: 'Deleted' },
            cell: ({ row }) => (
                <span className="text-muted-foreground text-xs">
                    {formatDistanceToNow(
                        parseServerDate(row.original.deleted_at),
                        { addSuffix: true },
                    )}
                </span>
            ),
        },
        {
            id: '_actions',
            header: '',
            cell: ({ row }) => (
                <RowActions
                    testimonial={row.original}
                    onRestore={handleRestore}
                    onForceDelete={openSingleDelete}
                />
            ),
            enableHiding: false,
        },
    ];

    return (
        <AdminLayout
            title="Testimonials — Trash"
            breadcrumbs={[
                { label: 'Testimonials', href: '/admin/testimonials' },
                { label: 'Trash' },
            ]}
        >
            <Head title="Testimonials — Trash" />

            <div className="space-y-6 p-6 lg:p-8">
                <PageHeader
                    title="Testimonials Trash"
                    description="Deleted testimonials are kept here. Restore or permanently delete them."
                    action={
                        <Link
                            href="/admin/testimonials"
                            className={cn(
                                'border-border flex items-center gap-1.5 rounded-lg border px-3 py-2',
                                'text-muted-foreground hover:bg-muted/40 hover:text-foreground text-xs font-medium transition-colors',
                            )}
                        >
                            <ArrowLeft className="h-3.5 w-3.5" />
                            Back to Testimonials
                        </Link>
                    }
                />

                <DataTable
                    columns={columns}
                    data={data?.data ?? []}
                    meta={data?.meta ?? EMPTY_META}
                    params={params}
                    isLoading={isLoading}
                    isFetching={isFetching}
                    onParamsChange={setParams}
                    quickFilters={[
                        {
                            label: 'All Trash',
                            value: 'all',
                            count: data?.filter_counts.all,
                        },
                    ]}
                    bulkActions={[
                        {
                            label: 'Restore',
                            icon: ArchiveRestore,
                            onClick: handleBulkRestore,
                        },
                        {
                            label: 'Delete permanently',
                            icon: Trash2,
                            onClick: openBulkDelete,
                            variant: 'destructive',
                        },
                    ]}
                    onRefresh={invalidate}
                    searchPlaceholder="Search deleted testimonials…"
                    noun="testimonials"
                    getRowId={(row) => String(row.id)}
                />
            </div>

            {/* ── Permanent delete confirmation modal ─────────────────────── */}
            <ConfirmDialog
                open={deleteTarget !== null}
                onOpenChange={closeDelete}
                title="Permanently delete testimonial?"
                description={
                    deleteTarget?.kind === 'single' ? (
                        <SingleDeleteDescription
                            testimonial={deleteTarget.testimonial}
                        />
                    ) : deleteTarget?.kind === 'bulk' ? (
                        <BulkDeleteDescription
                            testimonials={deleteTarget.testimonials}
                        />
                    ) : null
                }
                confirmLabel="Delete permanently"
                loading={deleting}
                onConfirm={handleConfirmDelete}
            />
        </AdminLayout>
    );
}
