import { EnquiryRecipients, type EnquiryRecipient } from '@/components/EnquiryRecipients';
import { UsersIcon, ArrowRightIcon } from '@/components/Icons';

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, InboxIcon, XIcon } from '@/components/Icons';

type L = { id: number; publicId: string; name: string; email: string; status: string; spamScore: string; city: string | null; practiceArea: string | null; createdAt: string; routed: number; accepted: number; description: string; recipients: EnquiryRecipient[] };

export default async function Leads({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const qs = new URLSearchParams(Object.entries(sp).filter(([k, v]) => v && ['status', 'q', 'page', 'lawyerId'].includes(k)) as [string, string][]);
  const d = await api<{ items: L[]; total: number; page: number; pageCount: number; selectedLawyer: { id: number; name: string } | null }>(`/admin/leads?${qs}`);
  const filtered = Boolean(sp.q || sp.status || sp.lawyerId);
  return (
    <>
      <PageHeader
        title={d.selectedLawyer ? `Enquiries for ${d.selectedLawyer.name}` : 'Enquiries'}
        icon={<InboxIcon className="h-5 w-5" />}
        actions={<Link href="/leads/lawyers" className="btn btn-quiet btn-sm"><UsersIcon />By lawyer</Link>}
        description={
          <>
            Every enquiry with its consent record, routing history and outcome. <span className="num font-semibold text-ink">{n(d.total)}</span> {filtered ? 'match.' : 'in total.'}
          </>
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <Toolbar>
        {sp.lawyerId && <input type="hidden" name="lawyerId" value={sp.lawyerId} />}
        <SearchField name="q" defaultValue={sp.q} placeholder="Client name, email, reference or lawyer" />
        <select name="status" defaultValue={sp.status ?? ''} className="field w-auto min-w-36" aria-label="Status">
          <option value="">Any status</option>
          {['new', 'routed', 'accepted', 'declined', 'contacted', 'retained', 'closed', 'expired', 'spam'].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="/leads" 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>Received</th>
                  <th>From</th>
                  <th>Need</th>
                  <th>Relevant lawyer / delivery</th>
                  <th>Status</th>
                  <th className="text-right">Routed</th>
                  <th className="text-right">Accepted</th>
                  <th className="text-right">Spam</th>
                </tr>
              </thead>
              <tbody>
                {d.items.map((l) => {
                  const spam = Number(l.spamScore);
                  return (
                    <tr key={l.id}>
                      <td className="whitespace-nowrap">
                        <Link href={`/leads/${l.id}`} className="font-semibold hover:text-ledger hover:underline">
                          {date(l.createdAt, true)}
                        </Link>
                        <span className="num block text-[11px] text-muted">{l.publicId}</span>
                      </td>
                      <td>
                        <span className="font-medium">{l.name}</span>
                        <span className="block text-xs text-muted">{l.email}</span>
                      </td>
                      <td>
                        <Link href={`/leads/${l.id}`} className="font-medium hover:text-ledger">{l.practiceArea ?? 'Direct enquiry'}</Link><p className="mt-1 max-w-xs line-clamp-2 text-xs text-muted">{l.description}</p> {l.city && <span className="text-muted">· {l.city}</span>}
                      </td>
                      <td><EnquiryRecipients recipients={l.recipients} /></td>
                      <td>
                        <Pill value={l.status} />
                      </td>
                      <td className="num text-right">{l.routed}</td>
                      <td className="num text-right">{l.accepted}</td>
                      <td className="text-right">
                        <span className={`num rounded px-1.5 py-0.5 text-xs font-semibold ${spam >= 0.5 ? 'bg-danger-soft text-danger' : spam > 0 ? 'bg-brass-soft text-brass' : 'text-muted'}`}>{spam.toFixed(2)}</span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<InboxIcon className="h-6 w-6" />}>No enquiries match these filters.</Empty>
        )}
        <Pager page={d.page} pageCount={d.pageCount} total={d.total} href={(p) => `/leads?${new URLSearchParams({ ...Object.fromEntries(qs), page: String(p) })}`} />
      </Card>
    </>
  );
}
