import BulkBar from '@/Components/admin/BulkBar';
import ConfirmDialog from '@/Components/admin/ConfirmDialog';
import DataTable, { Col, Pager } from '@/Components/admin/DataTable';
import { SearchInput, selectClass } 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 { Button } from '@/Components/ui/button';
import AdminLayout from '@/Layouts/AdminLayout';
import { LPage } from '@/types/admin';
import { Head, Link, router } from '@inertiajs/react';
import { Archive, Eye, EyeOff, Gamepad2, Pencil, Plus, RotateCcw, Star, Trash2, ExternalLink } from 'lucide-react';
import { useState } from 'react';

type Row = { id: number; title: string; slug: string; status: string; is_featured: boolean; cover: string | null; rating_avg: number; rating_count: number; wishlist_count: number; release_date: string | null; updated_at: string; deleted: boolean };
type Props = { games: LPage<Row>; filters: { q?: string; status?: string; trashed?: string; sort?: string }; counts: Record<string, number> };

export default function Index({ games, filters, counts }: Props) {
    const { q, setQ, go } = useAdminList('admin.games.index', filters);
    const [selected, setSelected] = useState<number[]>([]);
    const [confirm, setConfirm] = useState<null | 'delete'>(null);
    const [busy, setBusy] = useState(false);
    const trash = filters.trashed === 'only';

    const bulk = (action: string, done?: () => void) => router.post(route('admin.games.bulk'), { action, ids: selected }, {
        preserveScroll: true, onStart: () => setBusy(true), onSuccess: () => { setSelected([]); done?.(); }, onFinish: () => setBusy(false),
    });

    const tab = (label: string, patch: Record<string, string | undefined>, active: boolean, count?: number) => ({ label, count, active, href: route('admin.games.index', { ...patch, ...(filters.q ? { q: filters.q } : {}) }) });
    const total = ['published', 'upcoming', 'draft', 'archived'].reduce((n, k) => n + (counts[k] ?? 0), 0);

    const columns: Col<Row>[] = [
        { key: 'game', header: 'Game', cell: (g) => (
            <div className="flex items-center gap-3">
                <div className="h-12 w-9 shrink-0 overflow-hidden rounded-md border border-border bg-muted">{g.cover && <img src={g.cover} alt="" className="size-full object-cover" />}</div>
                <div className="min-w-0">
                    <Link href={route('admin.games.edit', g.slug)} className="flex items-center gap-1.5 font-medium hover:underline">{g.title}{g.is_featured && <Star className="size-3.5 fill-amber-400 text-amber-400" aria-label="Featured" />}</Link>
                    <p className="text-caption truncate">/{g.slug}</p>
                </div>
            </div>
        ) },
        { key: 'status', header: 'Status', cell: (g) => <StatusBadge value={g.status} /> },
        { key: 'rating', header: 'Rating', className: 'tabular-nums', cell: (g) => (g.rating_count ? <>{g.rating_avg.toFixed(1)} <span className="text-caption">({g.rating_count})</span></> : <span className="text-muted-foreground">—</span>) },
        { key: 'wl', header: 'Wishlists', className: 'tabular-nums', cell: (g) => g.wishlist_count },
        { key: 'rel', header: 'Release', className: 'whitespace-nowrap text-muted-foreground', cell: (g) => g.release_date ?? '—' },
        { key: 'upd', header: 'Updated', className: 'whitespace-nowrap text-muted-foreground', cell: (g) => g.updated_at },
        { key: 'act', header: '', className: 'w-24 text-right', cell: (g) => (
            <div className="flex justify-end gap-0.5">
                {!g.deleted && <Link href={route('admin.games.edit', g.slug)} aria-label={`Edit ${g.title}`} className="rounded-lg p-2 text-muted-foreground hover:bg-accent hover:text-foreground"><Pencil className="size-4" /></Link>}
                {!g.deleted && g.status !== 'draft' && <Link href={route('games.show', g.slug)} aria-label={`View ${g.title}`} className="rounded-lg p-2 text-muted-foreground hover:bg-accent hover:text-foreground"><ExternalLink className="size-4" /></Link>}
            </div>
        ) },
    ];

    return (
        <AdminLayout>
            <Head title="Games · Admin" />
            <PageHeader title="Games" description={`${total} in catalog`} actions={<Link href={route('admin.games.create')}><Button><Plus />New game</Button></Link>} />

            <Tabs items={[
                tab('All', {}, !filters.status && !trash, total),
                tab('Published', { status: 'published' }, filters.status === 'published', counts.published),
                tab('Upcoming', { status: 'upcoming' }, filters.status === 'upcoming', counts.upcoming),
                tab('Drafts', { status: 'draft' }, filters.status === 'draft', counts.draft),
                tab('Archived', { status: 'archived' }, filters.status === 'archived', counts.archived),
                tab('Trash', { trashed: 'only' }, trash, counts.trashed),
            ]} />

            <div className="mb-4 flex flex-wrap items-center gap-2">
                <SearchInput value={q} onChange={setQ} placeholder="Search games…" />
                <select aria-label="Sort" value={filters.sort ?? 'updated'} onChange={(e) => go({ sort: e.target.value === 'updated' ? undefined : e.target.value })} className={`${selectClass} !h-9 !w-auto`}>
                    <option value="updated">Recently updated</option><option value="title">Title</option><option value="rating">Rating</option><option value="released">Release date</option><option value="wishlists">Wishlists</option>
                </select>
            </div>

            <DataTable rows={games.data} columns={columns} selected={selected} onSelect={setSelected}
                rowClass={(g) => (g.deleted ? 'opacity-60' : undefined)}
                empty={<EmptyState icon={Gamepad2} title={trash ? 'Trash is empty' : 'No games found'} description={filters.q ? 'Try a different search.' : 'Add your first game to get started.'} action={!trash && <Link href={route('admin.games.create')}><Button><Plus />New game</Button></Link>} />} />
            <Pager page={games} />

            <BulkBar count={selected.length} onClear={() => setSelected([])} actions={trash ? [
                { label: 'Restore', icon: RotateCcw, run: () => bulk('restore') },
            ] : [
                { label: 'Publish', icon: Eye, run: () => bulk('publish') },
                { label: 'Draft', icon: EyeOff, run: () => bulk('draft') },
                { label: 'Archive', icon: Archive, run: () => bulk('archive') },
                { label: 'Feature', icon: Star, run: () => bulk('feature') },
                { label: 'Unfeature', run: () => bulk('unfeature') },
                { label: 'Trash', icon: Trash2, danger: true, run: () => setConfirm('delete') },
            ]} />

            <ConfirmDialog open={confirm === 'delete'} danger loading={busy} title={`Move ${selected.length} ${selected.length === 1 ? 'game' : 'games'} to trash?`} description="They disappear from the site and search. You can restore them from Trash." confirmLabel="Move to trash" onClose={() => setConfirm(null)} onConfirm={() => bulk('delete', () => setConfirm(null))} />
        </AdminLayout>
    );
}
