import { date } from '@/lib/format';
import { respondLead } from '@/app/actions';
import { Empty, Pill } from './ui';
import { SubmitButton } from './Actions';
import { CheckIcon, InboxIcon, MailIcon, PhoneIcon, XIcon } from './Icons';

export type LeadRow = {
  routingId: number;
  status: string;
  receivedAt: string;
  name: string;
  email: string;
  phone: string | null;
  description: string;
  city: string | null;
  practiceArea: string | null;
  lawyer?: string;
  /** Deadline to accept or decline (open enquiries only) */
  respondBy?: string | null;
};

/** Still answerable — includes webhook routings that are retrying or failed (the dashboard always works) */
const OPEN = ['pending', 'delivered', 'viewed', 'failed'];

/** Enquiry inbox rows with accept/decline, shared by the lawyer and firm views */
export function LeadList({ items, back, showLawyer, canRespond }: { items: LeadRow[]; back: string; showLawyer?: boolean; canRespond: boolean }) {
  if (!items.length) return <Empty icon={<InboxIcon className="h-6 w-6" />}>No enquiries match.</Empty>;
  return (
    <ul className="divide-y divide-rule">
      {items.map((x) => (
        <li key={x.routingId} className={`p-4 text-sm ${OPEN.includes(x.status) ? 'bg-brass-soft/30' : ''}`}>
          <div className="flex flex-wrap items-center gap-2">
            <span className="font-semibold">{x.name}</span>
            <Pill value={x.status} />
            {showLawyer && x.lawyer && <span className="text-xs text-muted">for {x.lawyer}</span>}
            <span className="text-xs text-muted">
              {x.practiceArea ?? 'Direct enquiry'}
              {x.city ? ` · ${x.city}` : ''} · {date(x.receivedAt, true)}
            </span>
            {x.respondBy && OPEN.includes(x.status) && (
              <span className={`text-xs font-semibold ${new Date(x.respondBy).getTime() - Date.now() < 6 * 3_600_000 ? 'text-danger' : 'text-brass'}`}>Reply by {date(x.respondBy, true)} UTC</span>
            )}
          </div>
          <p className="mt-2 whitespace-pre-line leading-relaxed text-ink-2">{x.description}</p>
          <p className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted">
            <a href={`mailto:${x.email}`} className="inline-flex items-center gap-1 hover:text-ledger">
              <MailIcon className="h-3.5 w-3.5" /> {x.email}
            </a>
            {x.phone && (
              <a href={`tel:${x.phone.replace(/[^\d+]/g, '')}`} className="num inline-flex items-center gap-1 hover:text-ledger">
                <PhoneIcon className="h-3.5 w-3.5" /> {x.phone}
              </a>
            )}
          </p>
          {canRespond && OPEN.includes(x.status) && (
            <form className="mt-3 flex gap-2">
              <input type="hidden" name="routingId" value={x.routingId} />
              <input type="hidden" name="back" value={back} />
              <SubmitButton formAction={respondLead.bind(null, 'accepted')}>
                <CheckIcon className="h-4 w-4" /> Accept
              </SubmitButton>
              <SubmitButton formAction={respondLead.bind(null, 'declined')} confirm="Decline this enquiry? The client may be routed to another lawyer." className="btn btn-quiet btn-sm">
                <XIcon className="h-4 w-4" /> Decline
              </SubmitButton>
            </form>
          )}
        </li>
      ))}
    </ul>
  );
}
