
import * as ActionIcons from '@/components/Icons';
import { api, me } from '@/lib/api';
import { Card, Flash, PageHeader, Pager, type SP } from '@/components/ui';
import { InboxIcon } from '@/components/Icons';
import { LeadList, type LeadRow } from '@/components/LeadList';

type D = { items: (LeadRow & { lawyerId: number })[]; total: number; page: number; pageCount: number };

const STATUSES = ['', 'delivered', 'viewed', 'accepted', 'declined', 'pending', 'failed'];

export default async function FirmLeads({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const filter = new URLSearchParams();
  if (sp.status && STATUSES.includes(sp.status)) filter.set('status', sp.status);
  if (sp.lawyerId && /^\d+$/.test(sp.lawyerId)) filter.set('lawyerId', sp.lawyerId);
  const [d, lawyers, user] = await Promise.all([
    api<D>(`/firm/leads?${filter}&page=${Number(sp.page) || 1}`),
    api<{ id: number; name: string }[]>('/firm/lawyers'),
    me(),
  ]);
  const here = `/portal/firm/leads?${filter}`;
  return (
    <>
      <PageHeader
        title="Firm enquiries"
        icon={<InboxIcon className="h-5 w-5" />}
        description="Enquiries routed to any lawyer in your firm. Client details are personal data: use them only to answer the enquiry."
        actions={
          <a href={`/portal/firm/leads/export?${filter}`} className="btn btn-quiet btn-sm">
            Export CSV
          </a>
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <form className="mb-4 flex flex-wrap items-end gap-2 text-sm">
        <label className="block">
          <span className="field-label"><ActionIcons.ActivityIcon />Status</span>
          <select name="status" defaultValue={sp.status ?? ''} className="field h-9">
            {STATUSES.map((s) => (
              <option key={s} value={s}>
                {s ? s : 'All'}
              </option>
            ))}
          </select>
        </label>
        <label className="block">
          <span className="field-label"><ActionIcons.UsersIcon />Lawyer</span>
          <select name="lawyerId" defaultValue={sp.lawyerId ?? ''} className="field h-9">
            <option value="">All lawyers</option>
            {lawyers.map((l) => (
              <option key={l.id} value={l.id}>
                {l.name}
              </option>
            ))}
          </select>
        </label>
        <button className="btn btn-quiet btn-sm"><ActionIcons.FilterIcon />Filter</button>
      </form>
      <Card>
        <LeadList items={d.items} back={here} showLawyer canRespond={user.organization?.role !== 'billing'} />
        <Pager page={d.page} pageCount={d.pageCount} total={d.total} href={(p) => `${here}&page=${p}`} />
      </Card>
    </>
  );
}
