
import * as ActionIcons from '@/components/Icons';
import Link from 'next/link';
import { api, isReviewer, me } from '@/lib/api';
import { date, PUBLIC_SITE } from '@/lib/format';
import { Card, Flash, Forbidden, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { AlertIcon, ArrowLeftIcon, CheckIcon, ExternalLinkIcon, FileTextIcon, MailIcon, ShieldCheckIcon, UserIcon, XIcon } from '@/components/Icons';
import { claimDecision } from '../../../actions';

type Detail = {
  claim: {
    id: number;
    status: string;
    claimantName: string;
    claimantEmail: string;
    claimantPhone: string | null;
    licenseNumber: string | null;
    message: string | null;
    emailMatch: boolean;
    licenseMatch: boolean;
    emailVerifiedAt: string | null;
    decisionNote: string | null;
    decidedAt: string | null;
    reviewer: string | null;
    createdAt: string;
  };
  lawyer: { id: number; slug: string; firstName: string; lastName: string; email: string | null; phone: string | null; websiteUrl: string | null; verificationStatus: string } | null;
  firm: { id: number; name: string; websiteUrl: string | null; email: string | null } | null;
  licenses: { jurisdiction: string; number: string | null; status: string; verification: string }[];
  documents: { id: number; name: string; mimeType: string; size: number; createdAt: string }[];
  otherClaims: { id: number; email: string; status: string; createdAt: string }[];
  managedBy: { id: number; email: string } | null;
  existingUser: { id: number; role: string; lawyerId: number | null; isActive: boolean } | null;
};

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex justify-between gap-4 px-4 py-2.5 text-sm">
      <dt className="text-muted">{label}</dt>
      <dd className="min-w-0 text-right font-medium">{children}</dd>
    </div>
  );
}

export default async function ClaimDetail({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: SP }) {
  const [{ id }, sp, viewer] = await Promise.all([params, searchParams, me()]);
  if (!isReviewer(viewer.role)) return <Forbidden what="profile claims" />;
  const d = await api<Detail>(`/admin/claims/${encodeURIComponent(id)}`);
  const c = d.claim;
  const open = ['email_verified', 'under_review', 'documents_required'].includes(c.status);
  const lawyerName = d.lawyer ? `${d.lawyer.firstName} ${d.lawyer.lastName}` : 'Unknown lawyer';
  return (
    <>
      <Link href="/claims" className="mb-3 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
        <ArrowLeftIcon className="h-4 w-4" /> All claims
      </Link>
      <PageHeader
        title={`Claim for ${lawyerName}`}
        icon={<UserIcon className="h-5 w-5" />}
        description={
          <span className="flex flex-wrap items-center gap-2">
            <Pill value={c.status} /> submitted {date(c.createdAt, true)}
            {c.decidedAt && (
              <span>
                · decided {date(c.decidedAt, true)} {c.reviewer && `by ${c.reviewer}`}
              </span>
            )}
          </span>
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      {d.managedBy && (
        <p className="mb-6 flex items-center gap-2 rounded-lg border border-danger/30 bg-danger-soft px-4 py-3 text-sm text-danger">
          <AlertIcon className="h-4 w-4" /> This profile is already managed by {d.managedBy.email}. Approving is blocked until that account is unlinked.
        </p>
      )}

      <div className="grid gap-6 xl:grid-cols-2">
        <div className="space-y-6">
          <Card title="Claimant" icon={<MailIcon className="h-4 w-4" />}>
            <dl className="divide-y divide-rule">
              <Row label="Name">{c.claimantName}</Row>
              <Row label="Email">
                {c.claimantEmail} {c.emailVerifiedAt ? <Pill value="confirmed" tone="good" /> : <Pill value="not confirmed" tone="warn" />}
              </Row>
              <Row label="Phone">{c.claimantPhone ?? '—'}</Row>
              <Row label="Licence number given">{c.licenseNumber ?? '—'}</Row>
              <Row label="Existing account">{d.existingUser ? `#${d.existingUser.id} (${d.existingUser.role}${d.existingUser.lawyerId ? `, manages lawyer #${d.existingUser.lawyerId}` : ''})` : 'None — a new account will be created'}</Row>
            </dl>
            {c.message && <p className="border-t border-rule px-4 py-3 text-sm leading-relaxed text-ink-2">“{c.message}”</p>}
          </Card>

          <Card title="Automatic checks" icon={<ShieldCheckIcon className="h-4 w-4" />}>
            <ul className="divide-y divide-rule text-sm">
              <li className="flex items-center gap-2 px-4 py-2.5">
                {c.emailMatch ? <CheckIcon className="h-4 w-4 text-ledger" /> : <XIcon className="h-4 w-4 text-muted" />} Email matches the profile or its website/firm domain
              </li>
              <li className="flex items-center gap-2 px-4 py-2.5">
                {c.licenseMatch ? <CheckIcon className="h-4 w-4 text-ledger" /> : <XIcon className="h-4 w-4 text-muted" />} Licence number matches one on the profile
              </li>
              <li className="flex items-center gap-2 px-4 py-2.5">
                {d.documents.length ? <CheckIcon className="h-4 w-4 text-ledger" /> : <XIcon className="h-4 w-4 text-muted" />} {d.documents.length} document{d.documents.length === 1 ? '' : 's'} uploaded
              </li>
            </ul>
          </Card>

          <Card title="Documents" icon={<FileTextIcon className="h-4 w-4" />}>
            {d.documents.length ? (
              <ul className="divide-y divide-rule text-sm">
                {d.documents.map((f) => (
                  <li key={f.id} className="flex items-center justify-between gap-3 px-4 py-2.5">
                    <span className="min-w-0 truncate">
                      {f.name} <span className="text-xs text-muted">· {Math.ceil(f.size / 1024)} KB · {date(f.createdAt, true)}</span>
                    </span>
                    <a href={`/files/${f.id}`} className="btn btn-quiet btn-xs">
                      Download
                    </a>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="p-4 text-sm text-muted">No documents uploaded. Use “Ask for documents” if the automatic checks aren’t enough.</p>
            )}
            <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">Documents are private: they download only for owners, admins and verifiers, and are never published.</p>
          </Card>
        </div>

        <div className="space-y-6">
          {d.lawyer && (
            <Card
              title="Profile on file"
              icon={<UserIcon className="h-4 w-4" />}
              actions={
                <a href={`${PUBLIC_SITE}/lawyers/${d.lawyer.slug}/`} target="_blank" rel="noopener" className="btn btn-quiet btn-xs">
                  <ExternalLinkIcon className="h-3.5 w-3.5" /> Public page
                </a>
              }
            >
              <dl className="divide-y divide-rule">
                <Row label="Email on profile">{d.lawyer.email ?? '—'}</Row>
                <Row label="Phone on profile">{d.lawyer.phone ?? '—'}</Row>
                <Row label="Website">{d.lawyer.websiteUrl ?? '—'}</Row>
                <Row label="Firm">{d.firm ? `${d.firm.name}${d.firm.websiteUrl ? ` (${d.firm.websiteUrl})` : ''}` : '—'}</Row>
                <Row label="Verification">
                  <Pill value={d.lawyer.verificationStatus} />
                </Row>
              </dl>
              <div className="border-t border-rule px-4 py-3 text-sm">
                <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted">Licences</p>
                {d.licenses.length ? (
                  <ul className="space-y-1">
                    {d.licenses.map((l, i) => (
                      <li key={i} className="flex flex-wrap items-center gap-2">
                        {l.jurisdiction} · <code className="text-xs">{l.number ?? 'no number'}</code> <Pill value={l.status} /> <Pill value={l.verification} />
                      </li>
                    ))}
                  </ul>
                ) : (
                  <p className="text-muted">No licences on file.</p>
                )}
              </div>
            </Card>
          )}

          {open ? (
            <Card title="Decision" icon={<CheckIcon className="h-4 w-4" />}>
              <form className="space-y-3 p-5 text-sm">
                <input type="hidden" name="id" value={c.id} />
                <label className="block">
                  <span className="field-label"><ActionIcons.FileTextIcon />Note (sent to the claimant when rejecting or asking for documents)</span>
                  <textarea name="note" rows={3} maxLength={2000} className="field" placeholder="e.g. Please upload your bar card or licence certificate" />
                </label>
                <div className="flex flex-wrap gap-2">
                  <SubmitButton formAction={claimDecision.bind(null, 'approve')} disabled={!!d.managedBy} confirm={`Approve and give ${c.claimantEmail} control of this profile?`}>
                    <CheckIcon className="h-4 w-4" /> Approve
                  </SubmitButton>
                  <SubmitButton formAction={claimDecision.bind(null, 'request-documents')} className="btn btn-quiet btn-sm">
                    <FileTextIcon className="h-4 w-4" /> Ask for documents
                  </SubmitButton>
                  <SubmitButton formAction={claimDecision.bind(null, 'reject')} className="btn btn-danger-quiet btn-sm" confirm="Reject this claim? The note is emailed to the claimant.">
                    <XIcon className="h-4 w-4" /> Reject
                  </SubmitButton>
                </div>
                <p className="text-xs text-muted">Approving creates (or links) a professional account, gives the lawyer a solo organization if they have none, closes competing claims and emails an activation link.</p>
              </form>
            </Card>
          ) : (
            c.decisionNote && (
              <Card title="Decision note">
                <p className="p-4 text-sm text-ink-2">{c.decisionNote}</p>
              </Card>
            )
          )}

          {d.otherClaims.length > 0 && (
            <Card title="Other claims for this profile">
              <ul className="divide-y divide-rule text-sm">
                {d.otherClaims.map((o) => (
                  <li key={o.id} className="flex items-center justify-between gap-3 px-4 py-2.5">
                    <Link href={`/claims/${o.id}`} className="hover:text-ledger hover:underline">
                      {o.email}
                    </Link>
                    <span className="flex items-center gap-2 text-xs text-muted">
                      <Pill value={o.status} /> {date(o.createdAt)}
                    </span>
                  </li>
                ))}
              </ul>
            </Card>
          )}
        </div>
      </div>
    </>
  );
}
