
import * as ActionIcons from '@/components/Icons';
import Link from 'next/link';
import { redirect } from 'next/navigation';
import { api, me } from '@/lib/api';
import { Card, Flash, PageHeader, type SP } from '@/components/ui';
import { InboxIcon } from '@/components/Icons';
import { LeadList, type LeadRow } from '@/components/LeadList';

type Row = { routingId: number; status: string; respondBy: string | null; deliveredAt: string | null; lead: { name: string; email: string; phone: string | null; description: string; city: string | null; practiceArea: string | null; createdAt: string } };

export default async function MyLeads({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const user = await me();
  if (!user.lawyerId) redirect('/portal');
  const page = Math.max(1, Number(sp.page) || 1);
  const rows = await api<Row[]>(`/lawyers/${user.lawyerId}/leads?page=${page}`);
  // Spread the lead first: it has its own `status`, which must not replace this routing's status
  const items: LeadRow[] = rows.map((r) => ({ ...r.lead, routingId: r.routingId, status: r.status, respondBy: r.respondBy, receivedAt: r.lead.createdAt }));
  return (
    <>
      <PageHeader title="My enquiries" icon={<InboxIcon className="h-5 w-5" />} description="Every enquiry routed to you. Responding quickly improves your client-experience score." />
      <Flash ok={sp.ok} err={sp.err} />
      <Card>
        <LeadList items={items} back={`/portal/leads?page=${page}`} canRespond />
        <div className="flex justify-between border-t border-rule px-4 py-2.5 text-sm">
          {page > 1 ? <Link href={`?page=${page - 1}`} className="btn btn-quiet btn-sm"><ActionIcons.ChevronLeftIcon />Newer</Link> : <span />}
          {rows.length === 20 && <Link href={`?page=${page + 1}`} className="btn btn-quiet btn-sm"><ActionIcons.ChevronRightIcon />Older</Link>}
        </div>
      </Card>
    </>
  );
}
