import { Head, Link, router } from '@inertiajs/react';
import { Plus, Scale, Search } from 'lucide-react';
import { useState } from '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 { 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 {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { usePermissions } from '@/hooks/use-permissions';
import { create, index, show } from '@/routes/matters';

type Row = {
    id: string;
    matter_number: string;
    title: string;
    type: string;
    client: string;
    court: string | null;
    stage: string | null;
    status: string;
    status_label: string;
    status_tone: StatusTone;
    priority_label: string;
    priority_tone: StatusTone;
    team: { name: string }[];
    next_hearing: string | null;
};

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

type Props = {
    matters: Paginated<Row>;
    filters: {
        search: string;
        status: string;
        practice_area: number | null;
        stage: number | null;
        partner: number | null;
        client: number | null;
    };
    options: {
        statuses: Option[];
        practiceAreas: Option[];
        stages: Option[];
        partners: Option[];
        clients: Option[];
    };
    stats: {
        open: number;
        on_hold: number;
        closed_this_month: number;
        urgent: number;
    };
};

const ALL = 'all';

function TeamAvatars({ team }: { team: { name: string }[] }) {
    if (team.length === 0) {
        return <span className="text-muted-foreground">—</span>;
    }

    return (
        <div className="flex -space-x-2">
            {team.slice(0, 3).map((m, i) => (
                <span
                    key={i}
                    title={m.name}
                    className="flex size-7 items-center justify-center rounded-full border border-card bg-muted text-xs font-medium text-foreground"
                >
                    {m.name
                        .split(' ')
                        .map((p) => p[0])
                        .slice(0, 2)
                        .join('')}
                </span>
            ))}
            {team.length > 3 && (
                <span className="flex size-7 items-center justify-center rounded-full border border-card bg-muted text-xs text-muted-foreground">
                    +{team.length - 3}
                </span>
            )}
        </div>
    );
}

export default function MattersIndex({
    matters,
    filters,
    options,
    stats,
}: Props) {
    const { can } = usePermissions();
    const [search, setSearch] = useState(filters.search ?? '');

    const applyFilters = (
        patch: Record<string, string | number | undefined>,
    ) => {
        router.get(
            index().url,
            {
                search: search || undefined,
                status: filters.status || undefined,
                practice_area: filters.practice_area || undefined,
                stage: filters.stage || undefined,
                partner: filters.partner || undefined,
                client: filters.client || undefined,
                ...patch,
            },
            { preserveState: true, replace: true },
        );
    };

    const filterSelect = (
        key: string,
        value: number | null,
        placeholder: string,
        opts: Option[],
    ) => (
        <Select
            value={value ? String(value) : ALL}
            onValueChange={(v) =>
                applyFilters({ [key]: v === ALL ? undefined : v })
            }
        >
            <SelectTrigger className="w-44">
                <SelectValue placeholder={placeholder} />
            </SelectTrigger>
            <SelectContent>
                <SelectItem value={ALL}>
                    All {placeholder.toLowerCase()}
                </SelectItem>
                {opts.map((o) => (
                    <SelectItem key={o.value} value={String(o.value)}>
                        {o.label}
                    </SelectItem>
                ))}
            </SelectContent>
        </Select>
    );

    return (
        <>
            <Head title="Matters" />
            <div className="flex flex-col gap-6 p-4">
                <PageHeader
                    title="Matters"
                    subtitle="Every litigation and advisory matter the firm is handling."
                    action={
                        can('matters.create') && (
                            <Button asChild>
                                <Link href={create()}>
                                    <Plus /> New matter
                                </Link>
                            </Button>
                        )
                    }
                />

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <Kpi label="Open" value={stats.open} />
                    <Kpi label="On hold" value={stats.on_hold} />
                    <Kpi
                        label="Closed this month"
                        value={stats.closed_this_month}
                    />
                    <Kpi label="Urgent" value={stats.urgent} />
                </div>

                <Card>
                    <CardContent className="flex flex-wrap items-end gap-3 py-4">
                        <form
                            className="min-w-56 flex-1"
                            onSubmit={(e) => {
                                e.preventDefault();
                                applyFilters({ search });
                            }}
                        >
                            <div className="relative">
                                <Search className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
                                <Input
                                    className="pl-8"
                                    placeholder="Search title or matter number…"
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                />
                            </div>
                        </form>
                        <Select
                            value={filters.status || ALL}
                            onValueChange={(v) =>
                                applyFilters({
                                    status: v === ALL ? undefined : v,
                                })
                            }
                        >
                            <SelectTrigger className="w-44">
                                <SelectValue placeholder="Status" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value={ALL}>
                                    All statuses
                                </SelectItem>
                                {options.statuses.map((s) => (
                                    <SelectItem
                                        key={s.value}
                                        value={String(s.value)}
                                    >
                                        {s.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        {filterSelect(
                            'practice_area',
                            filters.practice_area,
                            'Practice area',
                            options.practiceAreas,
                        )}
                        {filterSelect(
                            'stage',
                            filters.stage,
                            'Stage',
                            options.stages,
                        )}
                        {filterSelect(
                            'partner',
                            filters.partner,
                            'Partner',
                            options.partners,
                        )}
                    </CardContent>
                </Card>

                <Card>
                    <CardContent className="p-0">
                        {matters.data.length === 0 ? (
                            <EmptyState
                                icon={Scale}
                                title="No matters found"
                                description="Adjust your filters, or register the firm's first matter."
                                action={
                                    can('matters.create') && (
                                        <Button asChild>
                                            <Link href={create()}>
                                                <Plus /> New matter
                                            </Link>
                                        </Button>
                                    )
                                }
                            />
                        ) : (
                            <>
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Matter no.</TableHead>
                                            <TableHead>Title</TableHead>
                                            <TableHead>Client</TableHead>
                                            <TableHead>Court</TableHead>
                                            <TableHead>Stage</TableHead>
                                            <TableHead>Next hearing</TableHead>
                                            <TableHead>Team</TableHead>
                                            <TableHead>Status</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {matters.data.map((m) => (
                                            <TableRow key={m.id}>
                                                <TableCell className="font-mono text-xs text-muted-foreground">
                                                    <Link
                                                        href={show(m.id)}
                                                        className="hover:text-primary"
                                                    >
                                                        {m.matter_number}
                                                    </Link>
                                                </TableCell>
                                                <TableCell className="max-w-64 font-medium text-foreground">
                                                    <Link
                                                        href={show(m.id)}
                                                        className="hover:text-primary"
                                                    >
                                                        {m.title}
                                                    </Link>
                                                </TableCell>
                                                <TableCell>
                                                    {m.client}
                                                </TableCell>
                                                <TableCell>
                                                    {m.court ?? '—'}
                                                </TableCell>
                                                <TableCell>
                                                    {m.stage ?? '—'}
                                                </TableCell>
                                                <TableCell className="text-muted-foreground">
                                                    {m.next_hearing ?? '—'}
                                                </TableCell>
                                                <TableCell>
                                                    <TeamAvatars
                                                        team={m.team}
                                                    />
                                                </TableCell>
                                                <TableCell>
                                                    <StatusBadge
                                                        tone={m.status_tone}
                                                    >
                                                        {m.status_label}
                                                    </StatusBadge>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                                <Pagination page={matters} />
                            </>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}
