
import * as ActionIcons from '@/components/Icons';

import Link from 'next/link';
import { api } from '@/lib/api';
import { date, PUBLIC_SITE } from '@/lib/format';
import { Card, Flash, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { ArrowLeftIcon, HistoryIcon, InboxIcon, LockIcon, MailIcon, PhoneIcon, RefreshIcon, SaveIcon, SendIcon } from '@/components/Icons';
import { rerouteLead, updateLead } from '../../../actions';

type D = {
  lead: { id: number; publicId: string; name: string; email: string; phone: string | null; description: string; status: string; outcome: string | null; consentGiven: boolean; consentText: string; consentAt: string; spamScore: string; sourcePath: string | null; createdAt: string; city: { name: string } | null; practiceArea: { name: string } | null };
  routings: { id: number; lawyer: string; slug: string; channel: string; status: string; matchScore: string; attempts: number; lastError: string | null; deliveredAt: string | null; respondedAt: string | null; reminderSentAt: string | null; closedReason: string | null }[];
  history: { id: number; action: string; createdAt: string; userId?: number | null }[];
};

export default async function LeadDetail({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: SP }) {
  const { id } = await params;
  const sp = await searchParams;
  const d = await api<D>(`/admin/leads/${encodeURIComponent(id)}`);
  const l = d.lead;
  return (
    <>
      <Link href="/leads" className="mb-3 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
        <ArrowLeftIcon className="h-4 w-4" /> All leads
      </Link>
      <PageHeader
        title={`Lead ${l.publicId}`}
        icon={<InboxIcon className="h-5 w-5" />}
        description={
          <span className="flex flex-wrap items-center gap-2">
            <Pill value={l.status} />
            {date(l.createdAt, true)} · {l.practiceArea?.name ?? 'Direct enquiry'}
            {l.city ? ` in ${l.city.name}` : ''}
          </span>
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <div className="grid gap-6 xl:grid-cols-[1.2fr_1fr]">
        <Card title="Enquiry" icon={<MailIcon className="h-4 w-4" />}>
          <div className="space-y-4 p-5 text-sm">
            <div className="flex flex-wrap items-center gap-x-4 gap-y-1">
              <span className="font-semibold text-ink">{l.name}</span>
              <a href={`mailto:${l.email}`} className="inline-flex items-center gap-1 text-ink-2 hover:text-ledger">
                <MailIcon className="h-3.5 w-3.5" /> {l.email}
              </a>
              {l.phone && (
                <a href={`tel:${l.phone.replace(/[^\d+]/g, '')}`} className="num inline-flex items-center gap-1 text-ink-2 hover:text-ledger">
                  <PhoneIcon className="h-3.5 w-3.5" /> {l.phone}
                </a>
              )}
            </div>
            <p className="whitespace-pre-wrap rounded-lg bg-sunken p-3.5 leading-relaxed">{l.description}</p>
            <p className="text-xs text-muted">
              From <span className="num">{l.sourcePath ?? 'unknown page'}</span> · spam score <span className="num font-semibold">{Number(l.spamScore).toFixed(2)}</span>
            </p>
            <div className="rounded-lg border border-rule p-3.5 text-xs">
              <p className="flex items-center gap-1.5 font-semibold text-ink">
                <LockIcon className="h-3.5 w-3.5" /> Consent record
              </p>
              <p className="mt-1.5 leading-relaxed text-ink-2">“{l.consentText}”</p>
              <p className="mt-1.5 text-muted">Given {date(l.consentAt, true)}</p>
            </div>
            <form action={updateLead} className="grid gap-3 border-t border-rule pt-4 sm:grid-cols-[10rem_1fr_auto] sm:items-end">
              <input type="hidden" name="id" value={l.id} />
              <label className="block">
                <span className="field-label"><ActionIcons.ActivityIcon />Status</span>
                <select name="status" defaultValue={l.status} className="field">
                  {['new', 'routed', 'accepted', 'declined', 'contacted', 'retained', 'closed', 'expired', 'spam'].map((s) => (
                    <option key={s} value={s}>
                      {s}
                    </option>
                  ))}
                </select>
              </label>
              <label className="block">
                <span className="field-label"><ActionIcons.ActivityIcon />Outcome</span>
                <input name="outcome" maxLength={300} defaultValue={l.outcome ?? ''} className="field" placeholder="e.g. retained, no response" />
              </label>
              <SubmitButton pendingLabel="Saving…">
                <SaveIcon className="h-4 w-4" /> Save
              </SubmitButton>
            </form>
          </div>
        </Card>
        <div className="space-y-6">
          <Card
            title="Routing"
            icon={<SendIcon className="h-4 w-4" />}
            actions={
              <form action={rerouteLead}>
                <input type="hidden" name="id" value={l.id} />
                <SubmitButton className="btn btn-quiet btn-xs" confirm="Offer this enquiry to the next best-matching lawyers (never ones already contacted, and within the client’s consent)?">
                  <RefreshIcon className="h-3.5 w-3.5" /> Offer to more lawyers
                </SubmitButton>
              </form>
            }
          >
            <div className="overflow-x-auto">
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Lawyer</th>
                    <th>Channel</th>
                    <th>Status</th>
                    <th className="text-right">Match</th>
                    <th>Responded</th>
                  </tr>
                </thead>
                <tbody>
                  {d.routings.map((r) => (
                    <tr key={r.id}>
                      <td>
                        <a href={`${PUBLIC_SITE}/lawyers/${r.slug}/`} target="_blank" rel="noopener" className="font-medium hover:text-ledger hover:underline">
                          {r.lawyer}
                        </a>
                        {r.lastError && <span className="block text-xs text-danger">{r.lastError}</span>}
                        {r.attempts > 1 && <span className="block text-[11px] text-muted">{r.attempts} attempts</span>}
                      </td>
                      <td className="capitalize">{r.channel}</td>
                      <td>
                        <Pill value={r.status} />
                        {r.closedReason && <span className="block text-[11px] text-muted">{r.closedReason.replace(/_/g, ' ')}</span>}
                        {r.reminderSentAt && <span className="block text-[11px] text-muted">reminded {date(r.reminderSentAt, true)}</span>}
                      </td>
                      <td className="num text-right">{Number(r.matchScore).toFixed(1)}</td>
                      <td className="whitespace-nowrap text-xs">{date(r.respondedAt, true)}</td>
                    </tr>
                  ))}
                  {!d.routings.length && (
                    <tr>
                      <td colSpan={5} className="py-6 text-center text-muted">
                        Not routed to anyone yet.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </Card>
          <Card title="History" icon={<HistoryIcon className="h-4 w-4" />}>
            {d.history.length ? (
              <ol className="relative space-y-4 p-4 pl-8 text-sm before:absolute before:bottom-5 before:left-[1.1rem] before:top-5 before:w-px before:bg-rule">
                {d.history.map((h) => (
                  <li key={h.id} className="relative">
                    <span className="absolute -left-[1.15rem] top-1.5 h-2.5 w-2.5 rounded-full border-2 border-surface bg-ledger" />
                    <p className="font-medium">{h.action}</p>
                    <p className="text-xs text-muted">{date(h.createdAt, true)}</p>
                  </li>
                ))}
              </ol>
            ) : (
              <p className="p-4 text-sm text-muted">No recorded changes yet.</p>
            )}
          </Card>
        </div>
      </div>
    </>
  );
}
