import Link from 'next/link';
import { api } from '@/lib/api';
import { date, n } from '@/lib/format';
import { Card, PageHeader } from '@/components/ui';
import { AlertIcon, DatabaseIcon, GaugeIcon, MapPinIcon } from '@/components/Icons';

type DQ = {
  missing: Record<string, number>;
  completenessBuckets: { bucket: string; n: number }[];
  suspendedButPublished: { id: number; slug: string; name: string; status: string }[];
  sources: { name: string; source_type: string; records: number; rejected: number; last_fetch: string | null }[];
  byCity: { city: string; lawyers: number; verified_pct: number; avg_quality: number | null }[];
};
const LABELS: Record<string, string> = {
  thin_bio: 'Biography under 150 characters',
  no_photo: 'No photo',
  no_website: 'No website',
  no_phone: 'No phone',
  no_email: 'No email',
  no_experience: 'Years of experience missing',
  no_firm: 'No firm linked',
  no_license: 'No licence on record',
  unverified_license: 'No verified licence',
  no_practice_area: 'No practice area',
  never_verified: 'Never verified',
  stale_verification: 'Verification older than 12 months',
  stale_profile: 'Profile not updated in 12 months',
};

export default async function DataQuality() {
  const d = await api<DQ>('/admin/data-quality');
  const total = Math.max(1, d.missing.total ?? 0);
  // Worst gaps first, so the table reads as a to-do list
  const rows = Object.entries(LABELS)
    .map(([k, label]) => ({ k, label, v: d.missing[k] ?? 0 }))
    .sort((a, b) => b.v - a.v);
  return (
    <>
      <PageHeader
        title="Data quality"
        icon={<GaugeIcon className="h-5 w-5" />}
        description={`Gaps across ${n(d.missing.total)} published profiles. Missing data lowers scores; it is never filled in with guesses.`}
      />
      <div className="grid gap-6 xl:grid-cols-2">
        <Card title="Missing or stale fields" icon={<AlertIcon className="h-4 w-4" />}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Gap</th>
                <th className="text-right">Profiles</th>
                <th className="w-44">Share</th>
              </tr>
            </thead>
            <tbody>
              {rows.map(({ k, label, v }) => {
                const share = (v / total) * 100;
                return (
                  <tr key={k}>
                    <td>{label}</td>
                    <td className="num text-right font-semibold">{n(v)}</td>
                    <td>
                      <div className="flex items-center gap-2">
                        <span className="h-1.5 flex-1 overflow-hidden rounded-full bg-sunken">
                          <span className="block h-full rounded-full" style={{ width: `${share}%`, background: share >= 50 ? 'var(--danger)' : share >= 20 ? 'var(--g-standing)' : 'var(--g-expertise)' }} />
                        </span>
                        <span className="num w-9 text-right text-xs text-muted">{share.toFixed(0)}%</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
        <div className="space-y-6">
          <Card title="Quality by city" icon={<MapPinIcon className="h-4 w-4" />}>
            <table className="tbl">
              <thead>
                <tr>
                  <th>City</th>
                  <th className="text-right">Lawyers</th>
                  <th className="text-right">Verified</th>
                  <th className="text-right">Avg profile quality</th>
                </tr>
              </thead>
              <tbody>
                {d.byCity.map((c) => (
                  <tr key={c.city}>
                    <td className="font-medium">{c.city}</td>
                    <td className="num text-right">{n(c.lawyers)}</td>
                    <td className="num text-right">{c.verified_pct}%</td>
                    <td className="num text-right">{c.avg_quality ?? '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
          <Card title="Suspended licences on published profiles" icon={<AlertIcon className="h-4 w-4" />}>
            {d.suspendedButPublished.length ? (
              <table className="tbl">
                <tbody>
                  {d.suspendedButPublished.map((s) => (
                    <tr key={s.id}>
                      <td>
                        <Link href={`/lawyers/${s.id}`} className="font-medium text-ledger hover:underline">
                          {s.name}
                        </Link>
                      </td>
                      <td className="capitalize text-danger">{s.status}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <p className="p-4 text-sm text-muted">None — good.</p>
            )}
            <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">These lawyers are excluded from rankings automatically; review whether the profile should stay public.</p>
          </Card>
          <Card title="Source health" icon={<DatabaseIcon className="h-4 w-4" />}>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Source</th>
                  <th className="text-right">Records</th>
                  <th className="text-right">Rejected</th>
                  <th>Last fetch</th>
                </tr>
              </thead>
              <tbody>
                {d.sources.map((s) => (
                  <tr key={s.name}>
                    <td>{s.name}</td>
                    <td className="num text-right">{n(s.records)}</td>
                    <td className={`num text-right ${s.rejected ? 'font-semibold text-danger' : 'text-muted'}`}>{n(s.rejected)}</td>
                    <td className="whitespace-nowrap text-xs text-muted">{date(s.last_fetch)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        </div>
      </div>
    </>
  );
}
