
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, Empty, Flash, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { ArrowLeftIcon, BadgeCheckIcon, BriefcaseIcon, ChartIcon, CodeIcon, ExternalLinkIcon, FlagIcon, HistoryIcon, SaveIcon, ShieldCheckIcon, UserIcon } from '@/components/Icons';
import { updateLawyer } from '../../../actions';

type Detail = {
  lawyer: {
    id: number;
    slug: string;
    firstName: string;
    lastName: string;
    title: string | null;
    bio: string | null;
    websiteUrl: string | null;
    phone: string | null;
    email: string | null;
    yearsExperience: number | null;
    verificationStatus: string;
    profileStatus: string;
    acceptsLeads: boolean;
    lastVerifiedAt: string | null;
    mergedIntoId: number | null;
    firm: { name: string } | null;
    practiceAreas: { isPrimary: boolean; yearsExperience: number | null; practiceArea: { name: string } }[];
    languages: { language: { name: string } }[];
    licenses: { id: number; jurisdiction: string; licenseNumber: string | null; status: string; verification: string }[];
    locations: { city: { name: string }; isPrimary: boolean }[];
  };
  verifications: { id: number; checkType: string; status: string; notes: string | null; createdAt: string; decidedAt: string | null }[];
  sourceRecords: { id: number; source: string; status: string; fetchedAt: string; payload: unknown }[];
  corrections: { id: number; field: string | null; message: string; status: string; createdAt: string }[];
  auditTrail: { id: number; action: string; createdAt: string; userId: number | null }[];
};

const FIELDS = [
  ['firstName', 'First name', 'text', true],
  ['lastName', 'Last name', 'text', true],
  ['title', 'Title', 'text', false],
  ['yearsExperience', 'Years in practice', 'number', false],
  ['email', 'Email', 'email', false],
  ['phone', 'Phone', 'tel', false],
  ['websiteUrl', 'Website', 'url', false],
] as const;

export default async function LawyerDetail({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: SP }) {
  const { id } = await params;
  const sp = await searchParams;
  const d = await api<Detail>(`/admin/lawyers/${encodeURIComponent(id)}`);
  const l = d.lawyer;
  const facts: [string, string][] = [
    ['Firm', l.firm?.name ?? '—'],
    ['Offices', l.locations.map((x) => x.city.name + (x.isPrimary ? ' (main)' : '')).join(', ') || '—'],
    ['Areas', l.practiceAreas.map((p) => `${p.practiceArea.name}${p.isPrimary ? ' ★' : ''}${p.yearsExperience ? ` (${p.yearsExperience}y)` : ''}`).join(', ') || '—'],
    ['Languages', l.languages.map((x) => x.language.name).join(', ') || '—'],
  ];
  return (
    <>
      <Link href="/lawyers" className="mb-3 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
        <ArrowLeftIcon className="h-4 w-4" /> All lawyers
      </Link>
      <PageHeader
        title={`${l.firstName} ${l.lastName}`}
        icon={<UserIcon className="h-5 w-5" />}
        description={
          <span className="flex flex-wrap items-center gap-2">
            <Pill value={l.profileStatus} /> <Pill value={l.verificationStatus} />
            <span>Last verified {date(l.lastVerifiedAt)}</span>
            <span className="num">· #{l.id}</span>
            {l.mergedIntoId && (
              <Link href={`/lawyers/${l.mergedIntoId}`} className="font-medium text-warn underline">
                merged into #{l.mergedIntoId}
              </Link>
            )}
          </span>
        }
        actions={
          <>
            <a href={`${PUBLIC_SITE}/lawyers/${l.slug}/`} target="_blank" rel="noopener" className="btn btn-quiet btn-sm">
              <ExternalLinkIcon className="h-4 w-4" /> Public profile
            </a>
            <Link href={`/rankings?audit=${encodeURIComponent(l.slug)}`} className="btn btn-quiet btn-sm">
              <ChartIcon className="h-4 w-4" /> Ranking audit
            </Link>
          </>
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <div className="grid gap-6 xl:grid-cols-[1.4fr_1fr]">
        <Card title="Profile" icon={<UserIcon className="h-4 w-4" />}>
          <form action={updateLawyer} className="grid gap-4 p-5 sm:grid-cols-2">
            <input type="hidden" name="id" value={l.id} />
            {FIELDS.map(([name, label, type, required]) => (
              <label key={name} className="block">
                <span className="field-label">
                  {label}
                  {required && <span className="text-danger"> *</span>}
                </span>
                <input
                  name={name}
                  defaultValue={l[name] ?? ''}
                  type={type}
                  required={required}
                  {...(type === 'number' ? { min: 0, max: 70, inputMode: 'numeric' as const } : {})}
                  {...(type === 'url' ? { placeholder: 'https://' } : {})}
                  className="field"
                />
              </label>
            ))}
            <label className="block">
              <span className="field-label"><ActionIcons.ActivityIcon />Profile status</span>
              <select name="profileStatus" defaultValue={l.profileStatus} className="field">
                {['draft', 'published', 'suspended', 'archived'].map((s) => (
                  <option key={s} value={s}>
                    {s}
                  </option>
                ))}
              </select>
            </label>
            <label className="block sm:col-span-2">
              <span className="field-label"><ActionIcons.FileTextIcon />Biography</span>
              <textarea name="bio" rows={6} maxLength={5000} defaultValue={l.bio ?? ''} className="field" />
            </label>
            <label className="flex items-center gap-2.5 text-sm font-medium sm:col-span-2">
              <input type="checkbox" name="acceptsLeads" defaultChecked={l.acceptsLeads} /> Accepts enquiries
            </label>
            <div className="flex flex-wrap items-center gap-3 border-t border-rule pt-4 sm:col-span-2">
              <SubmitButton pendingLabel="Saving…">
                <SaveIcon className="h-4 w-4" /> Save changes
              </SubmitButton>
              <span className="text-xs text-muted">Every change is written to the audit log.</span>
            </div>
          </form>
        </Card>
        <div className="space-y-6">
          <Card title="Practice" icon={<BriefcaseIcon className="h-4 w-4" />}>
            <dl className="grid grid-cols-[6rem_1fr] gap-x-4 gap-y-2.5 p-4 text-sm">
              {facts.map(([k, v]) => (
                <div key={k} className="contents">
                  <dt className="text-muted">{k}</dt>
                  <dd className="text-ink">{v}</dd>
                </div>
              ))}
            </dl>
          </Card>
          <Card title="Licences" icon={<BadgeCheckIcon className="h-4 w-4" />}>
            {l.licenses.length ? (
              <table className="tbl">
                <tbody>
                  {l.licenses.map((x) => (
                    <tr key={x.id}>
                      <td className="font-medium">{x.jurisdiction}</td>
                      <td className="num">{x.licenseNumber ?? '—'}</td>
                      <td>
                        <Pill value={x.status} tone={x.status === 'active' ? 'good' : 'bad'} />
                      </td>
                      <td>
                        <Pill value={x.verification} />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <p className="p-4 text-sm text-muted">No licence on record — this profile cannot be ranked.</p>
            )}
          </Card>
          <Card title="Verification history" icon={<ShieldCheckIcon className="h-4 w-4" />}>
            {d.verifications.length ? (
              <table className="tbl">
                <tbody>
                  {d.verifications.map((v) => (
                    <tr key={v.id}>
                      <td>{v.checkType.replace(/_/g, ' ')}</td>
                      <td>
                        <Pill value={v.status} />
                      </td>
                      <td className="whitespace-nowrap text-muted">{date(v.decidedAt ?? v.createdAt)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <p className="p-4 text-sm text-muted">No checks recorded.</p>
            )}
          </Card>
        </div>
      </div>
      <div className="mt-6 grid gap-6 xl:grid-cols-2">
        <Card title="Raw source records (provenance)" icon={<CodeIcon className="h-4 w-4" />}>
          {d.sourceRecords.length ? (
            <ul className="divide-y divide-rule text-xs">
              {d.sourceRecords.map((r) => (
                <li key={r.id}>
                  <details className="group">
                    <summary className="flex cursor-pointer items-center gap-2 px-4 py-3 text-sm transition-colors hover:bg-paper">
                      <span className="flex-1 font-medium">{r.source}</span>
                      <Pill value={r.status} />
                      <span className="text-xs text-muted">{date(r.fetchedAt)}</span>
                    </summary>
                    <pre className="mx-4 mb-3 max-h-72 overflow-auto rounded-lg bg-sunken p-3 text-[11px] leading-relaxed">{JSON.stringify(r.payload, null, 2)}</pre>
                  </details>
                </li>
              ))}
            </ul>
          ) : (
            <Empty>No raw records linked to this profile.</Empty>
          )}
        </Card>
        <Card title="Audit trail" icon={<HistoryIcon className="h-4 w-4" />}>
          {d.auditTrail.length ? (
            <table className="tbl">
              <tbody>
                {d.auditTrail.map((a) => (
                  <tr key={a.id}>
                    <td className="font-medium">{a.action}</td>
                    <td className="text-muted">{a.userId ? `user #${a.userId}` : 'system'}</td>
                    <td className="whitespace-nowrap text-muted">{date(a.createdAt, true)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <p className="p-4 text-sm text-muted">No changes recorded yet.</p>
          )}
          {d.corrections.length > 0 && (
            <div className="border-t border-rule p-4 text-sm">
              <p className="mb-2 flex items-center gap-2 font-semibold">
                <FlagIcon className="h-4 w-4 text-muted" /> Reports about this profile
              </p>
              <ul className="space-y-2">
                {d.corrections.map((c) => (
                  <li key={c.id} className="flex items-start gap-2">
                    <Pill value={c.status} />
                    <span className="text-ink-2">{c.message}</span>
                  </li>
                ))}
              </ul>
              <Link href="/corrections" className="mt-3 inline-block text-xs font-semibold text-ledger hover:underline">
                Open corrections queue
              </Link>
            </div>
          )}
        </Card>
      </div>
    </>
  );
}
