
import Link from 'next/link';
import { api } from '@/lib/api';
import { date, n } from '@/lib/format';
import { Card, Empty, Flash, PageHeader, Pager, Pill, SearchField, Toolbar, type SP } from '@/components/ui';
import { FilterIcon, PlusIcon, UsersIcon, XIcon } from '@/components/Icons';

type Row = { id: number; slug: string; name: string; city: string | null; firm: string | null; verificationStatus: string; profileStatus: string; yearsExperience: number | null; lastVerifiedAt: string | null; updatedAt: string };

export default async function Lawyers({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const qs = new URLSearchParams(Object.entries(sp).filter(([k, v]) => v && ['q', 'status', 'verification', 'page'].includes(k)) as [string, string][]);
  const d = await api<{ items: Row[]; total: number; page: number; pageCount: number }>(`/admin/lawyers?${qs}`);
  const filtered = Boolean(sp.q || sp.status || sp.verification);
  return (
    <>
      <PageHeader
        title="Lawyers"
        icon={<UsersIcon className="h-5 w-5" />}
        description={
          <>
            <span className="num font-semibold text-ink">{n(d.total)}</span> {filtered ? 'profiles match these filters.' : 'profiles in the directory.'}
          </>
        }
        actions={
          <Link href="/lawyers/new" className="btn btn-primary btn-sm">
            <PlusIcon className="h-4 w-4" /> Add a lawyer
          </Link>
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <Toolbar>
        <SearchField name="q" defaultValue={sp.q} placeholder="Name, slug or email" />
        <select name="status" defaultValue={sp.status ?? ''} className="field w-auto min-w-36" aria-label="Profile status">
          <option value="">Any status</option>
          {['published', 'draft', 'suspended', 'merged', 'archived'].map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
        <select name="verification" defaultValue={sp.verification ?? ''} className="field w-auto min-w-40" aria-label="Verification">
          <option value="">Any verification</option>
          {['verified', 'pending', 'unverified', 'expired', 'rejected'].map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
        <button className="btn btn-quiet">
          <FilterIcon className="h-4 w-4" /> Filter
        </button>
        {filtered && (
          <Link href="/lawyers" className="btn btn-ghost">
            <XIcon className="h-4 w-4" /> Clear
          </Link>
        )}
      </Toolbar>
      <Card>
        {d.items.length ? (
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>City</th>
                  <th>Firm</th>
                  <th>Verification</th>
                  <th>Status</th>
                  <th className="text-right">Years</th>
                  <th>Last verified</th>
                  <th>Updated</th>
                </tr>
              </thead>
              <tbody>
                {d.items.map((l) => (
                  <tr key={l.id}>
                    <td>
                      <Link href={`/lawyers/${l.id}`} className="font-semibold text-ink hover:text-ledger hover:underline">
                        {l.name}
                      </Link>
                      <span className="num block text-[11px] text-muted">#{l.id}</span>
                    </td>
                    <td>{l.city ?? '—'}</td>
                    <td className="max-w-48 truncate" title={l.firm ?? undefined}>
                      {l.firm ?? '—'}
                    </td>
                    <td>
                      <Pill value={l.verificationStatus} />
                    </td>
                    <td>
                      <Pill value={l.profileStatus} />
                    </td>
                    <td className="num text-right">{l.yearsExperience ?? '—'}</td>
                    <td className="whitespace-nowrap">{date(l.lastVerifiedAt)}</td>
                    <td className="whitespace-nowrap text-muted">{date(l.updatedAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<UsersIcon className="h-6 w-6" />}>No lawyers match these filters.</Empty>
        )}
        <Pager page={d.page} pageCount={d.pageCount} total={d.total} href={(p) => `/lawyers?${new URLSearchParams({ ...Object.fromEntries(qs), page: String(p) })}`} />
      </Card>
    </>
  );
}
