import BulkBar from '@/Components/admin/BulkBar';
import ConfirmDialog from '@/Components/admin/ConfirmDialog';
import DataTable, { Col, Pager } from '@/Components/admin/DataTable';
import { SearchInput } from '@/Components/admin/fields';
import { PageHeader, StatusBadge, Tabs } from '@/Components/admin/primitives';
import { useAdminList } from '@/Components/admin/useAdminList';
import EmptyState from '@/Components/shared/EmptyState';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import AdminLayout from '@/Layouts/AdminLayout';
import { LPage } from '@/types/admin';
import { Head, Link, router } from '@inertiajs/react';
import { Check, EyeOff, MessageSquare, Star, Trash2 } from 'lucide-react';
import { useState } from 'react';

type Row = { id: number; title: string | null; body: string; status: string; contains_spoilers: boolean; score: number | null; user: { name: string; username: string | null } | null; game: { title: string; slug: string } | null; created_at: string };
type Props = { reviews: LPage<Row>; filters: { q?: string; status?: string }; counts: Record<string, number> };

export default function Index({ reviews, filters, counts }: Props) {
    const { q, setQ } = useAdminList('admin.reviews.index', filters);
    const [selected, setSelected] = useState<number[]>([]);
    const [confirm, setConfirm] = useState<{ ids: number[] } | null>(null);
    const [busy, setBusy] = useState(false);
    const total = Object.values(counts).reduce((a, b) => a + b, 0);

    const setStatus = (id: number, status: string) => router.patch(route('admin.reviews.update', id), { status }, { preserveScroll: true });
    const bulk = (action: string, ids = selected, done?: () => void) => router.post(route('admin.reviews.bulk'), { action, ids }, { preserveScroll: true, onStart: () => setBusy(true), onSuccess: () => { setSelected([]); done?.(); }, onFinish: () => setBusy(false) });
    const tab = (label: string, status: string | undefined, count?: number) => ({ label, count, active: filters.status === status, href: route('admin.reviews.index', { ...(status ? { status } : {}), ...(filters.q ? { q: filters.q } : {}) }) });

    const columns: Col<Row>[] = [
        { key: 'review', header: 'Review', className: 'max-w-md', cell: (r) => (
            <div className="space-y-1">
                <div className="flex flex-wrap items-center gap-2 text-sm">
                    <span className="font-medium">{r.user?.name ?? 'Deleted user'}</span>
                    {r.score && <span className="inline-flex items-center gap-0.5 text-xs"><Star className="size-3 fill-amber-400 text-amber-400" />{r.score}</span>}
                    <span className="text-muted-foreground">on</span>
                    {r.game ? <Link href={route('games.show', r.game.slug)} className="text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">{r.game.title}</Link> : '—'}
                    {r.contains_spoilers && <Badge variant="outline">Spoilers</Badge>}
                </div>
                {r.title && <p className="text-sm font-medium">{r.title}</p>}
                <p className="line-clamp-3 text-sm text-muted-foreground">{r.body}</p>
            </div>
        ) },
        { key: 'status', header: 'Status', cell: (r) => <StatusBadge value={r.status} /> },
        { key: 'at', header: 'Posted', className: 'whitespace-nowrap text-muted-foreground', cell: (r) => r.created_at },
        { key: 'act', header: '', className: 'w-36 text-right', cell: (r) => (
            <div className="flex justify-end gap-1">
                {r.status !== 'published' && <Button size="sm" variant="secondary" onClick={() => setStatus(r.id, 'published')}><Check />Publish</Button>}
                {r.status !== 'hidden' && <Button size="sm" variant="ghost" onClick={() => setStatus(r.id, 'hidden')}><EyeOff />Hide</Button>}
                <Button size="icon" variant="ghost" aria-label="Delete review" className="size-8 text-muted-foreground hover:text-destructive" onClick={() => setConfirm({ ids: [r.id] })}><Trash2 /></Button>
            </div>
        ) },
    ];

    return (
        <AdminLayout>
            <Head title="Reviews · Admin" />
            <PageHeader title="Reviews" description="Moderate what users write." />
            <Tabs items={[tab('All', undefined, total), tab('Published', 'published', counts.published), tab('Pending', 'pending', counts.pending), tab('Hidden', 'hidden', counts.hidden)]} />
            <div className="mb-4"><SearchInput value={q} onChange={setQ} placeholder="Search text, user or game…" /></div>

            <DataTable rows={reviews.data} columns={columns} selected={selected} onSelect={setSelected} empty={<EmptyState icon={MessageSquare} title="No reviews here" description="Nothing matches this view." />} />
            <Pager page={reviews} />

            <BulkBar count={selected.length} onClear={() => setSelected([])} actions={[
                { label: 'Publish', icon: Check, run: () => bulk('publish') },
                { label: 'Hide', icon: EyeOff, run: () => bulk('hide') },
                { label: 'Delete', icon: Trash2, danger: true, run: () => setConfirm({ ids: selected }) },
            ]} />
            <ConfirmDialog open={!!confirm} danger loading={busy} title={`Delete ${confirm?.ids.length} ${confirm?.ids.length === 1 ? 'review' : 'reviews'}?`} description="Deleted reviews are removed from the site." confirmLabel="Delete" onClose={() => setConfirm(null)} onConfirm={() => bulk('delete', confirm!.ids, () => setConfirm(null))} />
        </AdminLayout>
    );
}
