import { api, isAdmin, me } from '@/lib/api';
import { date, n, PUBLIC_SITE } from '@/lib/format';
import { Card, Empty, Flash, PageHeader, Pill, Tabs, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { BadgeCheckIcon, CalendarIcon, CheckIcon, DatabaseIcon, MapPinIcon, ShieldCheckIcon, XIcon } from '@/components/Icons';
import { decideVerification } from '../../actions';

type Item = {
  id: number;
  entity_type: string;
  entity_id: number;
  check_type: string;
  status: string;
  notes: string | null;
  created_at: string;
  lawyer_name: string | null;
  lawyer_slug: string | null;
  city: string | null;
  license_number: string | null;
  jurisdiction: string | null;
  issuing_body: string | null;
  source: string | null;
};

const STATUSES = ['pending', 'verified', 'rejected'];

export default async function Verification({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const status = STATUSES.includes(sp.status ?? '') ? sp.status! : 'pending';
  const [d, user] = await Promise.all([api<{ items: Item[]; total: number }>(`/admin/verification-queue?status=${status}&pageSize=50`), me()]);
  // Decisions are open to admins and verifiers (not editors) — mirror the API guard
  const canDecide = isAdmin(user.role) || user.role === 'verifier';
  return (
    <>
      <PageHeader
        title="Verification queue"
        icon={<ShieldCheckIcon className="h-5 w-5" />}
        description="Check each item against the issuing body’s public register before deciding. Approving a licence marks the lawyer verified and refreshes their last-verified date."
        actions={<Tabs current={status} items={STATUSES.map((s) => ({ value: s, label: s, href: `?status=${s}` }))} />}
      />
      <Flash ok={sp.ok} err={sp.err} />
      <p className="mb-3 text-sm text-muted">
        <span className="num font-semibold text-ink">{n(d.total)}</span> {status} items{status === 'pending' ? ', oldest first' : ''}
        {d.total > d.items.length && ` — showing the first ${d.items.length}`}.
      </p>
      <Card>
        {d.items.length ? (
          <ul className="divide-y divide-rule">
            {d.items.map((v) => (
              <li key={v.id} className="grid gap-4 p-4 transition-colors hover:bg-paper/60 lg:grid-cols-[1fr_24rem] lg:items-start">
                <div className="min-w-0 text-sm">
                  <p className="flex flex-wrap items-center gap-2">
                    <Pill value={v.check_type} tone="info" />
                    {v.lawyer_slug ? (
                      <a href={`${PUBLIC_SITE}/lawyers/${v.lawyer_slug}/`} target="_blank" rel="noopener" className="font-semibold hover:text-ledger hover:underline">
                        {v.lawyer_name}
                      </a>
                    ) : (
                      <span className="font-semibold">
                        {v.entity_type} #{v.entity_id}
                      </span>
                    )}
                    {v.city && (
                      <span className="inline-flex items-center gap-1 text-muted">
                        <MapPinIcon className="h-3.5 w-3.5" />
                        {v.city}
                      </span>
                    )}
                  </p>
                  {v.license_number && (
                    <p className="mt-2 flex flex-wrap items-center gap-x-2 rounded-lg bg-paper px-3 py-2">
                      <BadgeCheckIcon className="h-4 w-4 text-muted" />
                      Licence <span className="num font-semibold">{v.license_number}</span>
                      <span className="text-muted">·</span> {v.jurisdiction} <span className="text-muted">·</span> <span className="text-ink-2">{v.issuing_body}</span>
                    </p>
                  )}
                  <p className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted">
                    <span className="inline-flex items-center gap-1">
                      <CalendarIcon className="h-3.5 w-3.5" /> Submitted {date(v.created_at)}
                    </span>
                    {v.source && (
                      <span className="inline-flex items-center gap-1">
                        <DatabaseIcon className="h-3.5 w-3.5" /> {v.source}
                      </span>
                    )}
                    {v.notes && <span>· {v.notes}</span>}
                  </p>
                </div>
                {v.status === 'pending' ? (
                  canDecide ? (
                    <form className="flex flex-col gap-2">
                      <input type="hidden" name="id" value={v.id} />
                      <input name="notes" maxLength={500} placeholder="Evidence or reason (optional)" aria-label="Notes" className="field text-xs" />
                      <div className="flex gap-2">
                        <SubmitButton formAction={decideVerification.bind(null, 'verified')} className="btn btn-primary btn-sm flex-1">
                          <CheckIcon className="h-4 w-4" /> Approve
                        </SubmitButton>
                        <SubmitButton formAction={decideVerification.bind(null, 'rejected')} confirm="Reject this verification check?" className="btn btn-danger-quiet btn-sm flex-1">
                          <XIcon className="h-4 w-4" /> Reject
                        </SubmitButton>
                      </div>
                    </form>
                  ) : (
                    <p className="text-xs text-muted">Only verifiers and admins can decide checks.</p>
                  )
                ) : (
                  <div className="lg:text-right">
                    <Pill value={v.status} />
                  </div>
                )}
              </li>
            ))}
          </ul>
        ) : (
          <Empty icon={<ShieldCheckIcon className="h-6 w-6" />}>{status === 'pending' ? 'Nothing waiting. New checks arrive from imports, profile claims and the expiry job.' : `No ${status} checks.`}</Empty>
        )}
      </Card>
    </>
  );
}
