import { Head, Link, router } from '@inertiajs/react';
import { Gavel } from 'lucide-react';
import { EmptyState } from '@/components/empty-state';
import { Kpi } from '@/components/kpi';
import { PageHeader } from '@/components/page-header';
import {  Pagination } from '@/components/pagination';
import type {Paginated} from '@/components/pagination';
import { StatusBadge  } from '@/components/status-badge';
import type {StatusTone} from '@/components/status-badge';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { index } from '@/routes/hearings';
import { show as matterShow } from '@/routes/matters';

type Row = {
    id: string;
    matter_id: string;
    matter_number: string;
    matter_title: string;
    client: string;
    hearing_date: string;
    hearing_time: string | null;
    type: string;
    purpose: string | null;
    court: string | null;
    status: string;
    status_label: string;
    status_tone: StatusTone;
    outcome: string | null;
};

type Option = { value: number | string; label: string };

type Props = {
    hearings: Paginated<Row>;
    filters: { status: string; court: number | null; from: string | null; to: string | null };
    courts: Option[];
    statuses: Option[];
    stats: { upcoming: number; today: number; this_week: number; missed: number };
};

const ALL = 'all';

export default function HearingsIndex({ hearings, filters, courts, statuses, stats }: Props) {
    const apply = (patch: Record<string, string | number | null | undefined>) => {
        router.get(
            index().url,
            {
                status: filters.status || undefined,
                court: filters.court || undefined,
                from: filters.from || undefined,
                to: filters.to || undefined,
                ...patch,
            },
            { preserveState: true, replace: true },
        );
    };

    return (
        <>
            <Head title="Hearings" />
            <div className="flex flex-col gap-6 p-4">
                <PageHeader title="Hearings" subtitle="Every scheduled and past court appearance." />

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <Kpi label="Upcoming" value={stats.upcoming} />
                    <Kpi label="Today" value={stats.today} />
                    <Kpi label="Next 7 days" value={stats.this_week} />
                    <Kpi label="Missed" value={stats.missed} />
                </div>

                <Card>
                    <CardContent className="flex flex-wrap items-end gap-3 py-4">
                        <Select value={filters.status || ALL} onValueChange={(v) => apply({ status: v === ALL ? undefined : v })}>
                            <SelectTrigger className="w-44"><SelectValue placeholder="Status" /></SelectTrigger>
                            <SelectContent>
                                <SelectItem value={ALL}>All statuses</SelectItem>
                                {statuses.map((s) => (
                                    <SelectItem key={s.value} value={String(s.value)}>{s.label}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <Select value={filters.court ? String(filters.court) : ALL} onValueChange={(v) => apply({ court: v === ALL ? undefined : v })}>
                            <SelectTrigger className="w-52"><SelectValue placeholder="Court" /></SelectTrigger>
                            <SelectContent>
                                <SelectItem value={ALL}>All courts</SelectItem>
                                {courts.map((c) => (
                                    <SelectItem key={c.value} value={String(c.value)}>{c.label}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <div className="grid gap-1">
                            <span className="text-xs text-muted-foreground">From</span>
                            <Input type="date" value={filters.from ?? ''} onChange={(e) => apply({ from: e.target.value || undefined })} className="w-40" />
                        </div>
                        <div className="grid gap-1">
                            <span className="text-xs text-muted-foreground">To</span>
                            <Input type="date" value={filters.to ?? ''} onChange={(e) => apply({ to: e.target.value || undefined })} className="w-40" />
                        </div>
                    </CardContent>
                </Card>

                <Card>
                    <CardContent className="p-0">
                        {hearings.data.length === 0 ? (
                            <EmptyState icon={Gavel} title="No hearings found" description="Adjust the filters to see scheduled court dates." />
                        ) : (
                            <>
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Date</TableHead>
                                            <TableHead>Matter</TableHead>
                                            <TableHead>Type</TableHead>
                                            <TableHead>Court</TableHead>
                                            <TableHead>Status</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {hearings.data.map((h) => (
                                            <TableRow key={h.id}>
                                                <TableCell className="whitespace-nowrap font-medium text-foreground">
                                                    {h.hearing_date}
                                                    {h.hearing_time && (
                                                        <span className="ml-1 text-xs text-muted-foreground">{h.hearing_time}</span>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    <Link href={matterShow(h.matter_id)} className="hover:text-primary">
                                                        <span className="font-mono text-xs text-muted-foreground">{h.matter_number}</span>
                                                        <span className="ml-2">{h.matter_title}</span>
                                                    </Link>
                                                </TableCell>
                                                <TableCell>{h.type}</TableCell>
                                                <TableCell>{h.court ?? '—'}</TableCell>
                                                <TableCell>
                                                    <StatusBadge tone={h.status_tone}>{h.status_label}</StatusBadge>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                                <Pagination page={hearings} />
                            </>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}
