import Link from 'next/link';
import { api, isReviewer, me } from '@/lib/api';
import { date } from '@/lib/format';
import { Card, Empty, Flash, Forbidden, PageHeader, Pager, Pill, Tabs, type SP } from '@/components/ui';
import { BadgeCheckIcon, CheckIcon, FileTextIcon, MailIcon, UserIcon } from '@/components/Icons';

type Row = { id: number; status: string; claimantName: string; claimantEmail: string; emailMatch: boolean; licenseMatch: boolean; createdAt: string; lawyerId: number; lawyer: string; slug: string; documents: number };

const TABS = [
  { value: '', label: 'Needs review' },
  { value: 'documents_required', label: 'Waiting for documents' },
  { value: 'pending', label: 'Email not confirmed' },
  { value: 'approved', label: 'Approved' },
  { value: 'rejected', label: 'Rejected' },
  { value: 'expired', label: 'Expired' },
];

export default async function Claims({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const viewer = await me();
  if (!isReviewer(viewer.role)) return <Forbidden what="profile claims" />;
  const status = TABS.some((t) => t.value === sp.status) ? (sp.status ?? '') : '';
  const qs = new URLSearchParams({ ...(status ? { status } : {}), page: sp.page ?? '1' });
  const d = await api<{ items: Row[]; total: number; page: number; pageCount: number; counts: Record<string, number> }>(`/admin/claims?${qs}`);
  const review = (d.counts.email_verified ?? 0) + (d.counts.under_review ?? 0);
  return (
    <>
      <PageHeader
        title="Profile claims"
        icon={<UserIcon className="h-5 w-5" />}
        description="Lawyers asking to manage their profile. A claim reaches this queue only after the claimant confirmed their email. Check the automatic matches and any uploaded proof before approving."
        actions={
          <Tabs
            current={status}
            items={TABS.map((t) => ({ ...t, href: t.value ? `?status=${t.value}` : '/claims', count: t.value === '' ? review : (d.counts[t.value] ?? undefined) }))}
          />
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <Card>
        {d.items.length ? (
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Profile</th>
                  <th>Claimant</th>
                  <th>Evidence</th>
                  <th>Status</th>
                  <th>Submitted</th>
                </tr>
              </thead>
              <tbody>
                {d.items.map((c) => (
                  <tr key={c.id}>
                    <td>
                      <Link href={`/claims/${c.id}`} className="font-semibold hover:text-ledger hover:underline">
                        {c.lawyer}
                      </Link>
                      <span className="block text-xs text-muted">lawyer #{c.lawyerId}</span>
                    </td>
                    <td className="text-sm">
                      {c.claimantName}
                      <span className="flex items-center gap-1 text-xs text-muted">
                        <MailIcon className="h-3 w-3" /> {c.claimantEmail}
                      </span>
                    </td>
                    <td className="space-x-1 whitespace-nowrap">
                      {c.emailMatch && <Pill value="email match" tone="good" />}
                      {c.licenseMatch && <Pill value="licence match" tone="good" />}
                      {c.documents > 0 && <Pill value={`${c.documents} doc${c.documents > 1 ? 's' : ''}`} tone="info" />}
                      {!c.emailMatch && !c.licenseMatch && !c.documents && <span className="text-xs text-muted">none yet</span>}
                    </td>
                    <td>
                      <Pill value={c.status} tone={c.status === 'approved' ? 'good' : c.status === 'rejected' ? 'bad' : c.status === 'documents_required' ? 'warn' : 'info'} />
                    </td>
                    <td className="whitespace-nowrap text-xs text-muted">{date(c.createdAt, true)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<CheckIcon className="h-6 w-6" />}>Nothing here.</Empty>
        )}
        <Pager page={d.page} pageCount={d.pageCount} total={d.total} href={(p) => `/claims?${new URLSearchParams({ ...(status ? { status } : {}), page: String(p) })}`} />
      </Card>
      <p className="mt-4 flex items-center gap-2 text-xs text-muted">
        <BadgeCheckIcon className="h-4 w-4" /> <strong>Email match</strong> means the claimant’s address equals the profile email or uses the lawyer’s or firm’s own website domain.
        <FileTextIcon className="ml-2 h-4 w-4" /> Free mailboxes (Gmail, Outlook…) never count as a match.
      </p>
    </>
  );
}
