"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { useState } from "react";
import { api, type Tier } from "@/lib/api";
import { formatDate } from "@/lib/format";
import { PageHeader } from "@/components/PageHeader";

export default function LicensesPage() {
    const [tier, setTier] = useState<"" | Tier>("");
    const [reason, setReason] = useState("");
    const { data } = useQuery({ queryKey: ["staff-licenses"], queryFn: () => api.staff.licenses() });

    // Filtered here rather than server-side: the endpoint caps at 500 rows and
    // staff are narrowing a list they can already see.
    const rows = (data ?? []).filter(
        (l) => (!tier || l.tier === tier) && (!reason || l.reason === reason),
    );

    return (
        <div className="grid gap-6">
            <PageHeader
                title="Licences"
                subtitle="Append-only. A renewal writes a new row and supersedes the old one."
                record={[{ key: "Showing", value: `${rows.length} of ${(data ?? []).length}` }]}
            />
            <div className="flex flex-wrap gap-3">
                <select
                    value={tier}
                    onChange={(e) => setTier(e.target.value as Tier | "")}
                    className="rounded border border-rule bg-panel-2 px-2.5 py-2"
                    aria-label="Filter by tier"
                >
                    <option value="">All tiers</option>
                    <option value="free">Free</option>
                    <option value="professional">Professional</option>
                    <option value="enterprise">Enterprise</option>
                    <option value="self_hosted">Self-Hosted (legacy)</option>
                </select>
                <select
                    value={reason}
                    onChange={(e) => setReason(e.target.value)}
                    className="rounded border border-rule bg-panel-2 px-2.5 py-2"
                    aria-label="Filter by reason"
                >
                    <option value="">All reasons</option>
                    <option value="new">New</option>
                    <option value="renewal">Renewal</option>
                    <option value="tier_change">Tier change</option>
                    <option value="relink">Relink</option>
                    <option value="manual">Manual</option>
                </select>
            </div>
            <div className="overflow-x-auto rounded border border-rule bg-panel">
                <table className="w-full border-collapse text-left">
                    <thead>
                        <tr className="border-b border-rule bg-panel-2 font-mono text-[0.72rem] uppercase tracking-[0.08em] text-ink-3">
                            <th className="px-4 py-2.5">Issued</th>
                            <th className="px-4 py-2.5">Instance</th>
                            <th className="px-4 py-2.5">Tier</th>
                            <th className="px-4 py-2.5">Reason</th>
                            <th className="px-4 py-2.5">Expires</th>
                            <th className="px-4 py-2.5">State</th>
                        </tr>
                    </thead>
                    <tbody>
                        {rows.map((l) => (
                            <tr
                                key={l.license_id}
                                className="border-b border-rule-soft last:border-0"
                            >
                                <td className="px-4 py-3 font-mono tabular-nums">
                                    {formatDate(l.issued_at)}
                                </td>
                                <td className="px-4 py-3">
                                    <Link
                                        href={`/staff/instances/${l.instance_id}`}
                                        className="font-mono text-[0.82rem] text-accent underline"
                                    >
                                        {l.instance_id.slice(0, 8)}
                                    </Link>
                                </td>
                                <td className="px-4 py-3">{l.tier.replace("_", " ")}</td>
                                <td className="px-4 py-3">{l.reason.replace("_", " ")}</td>
                                <td className="px-4 py-3 font-mono tabular-nums">
                                    {formatDate(l.expires_at)}
                                </td>
                                <td className="px-4 py-3 text-ink-3">
                                    {l.superseded_by ? "superseded" : "current"}
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
                {rows.length === 0 && (
                    <p className="px-4 py-6 text-ink-3">No licences match those filters.</p>
                )}
            </div>
        </div>
    );
}
