import { EnquiryRecipients, type EnquiryRecipient } from '@/components/EnquiryRecipients';
import Link from 'next/link';
import { api, isAdmin, me } from '@/lib/api';
import { date, money, n, pct } from '@/lib/format';
import { BarChart } from '@/components/BarChart';
import { Card, Kpi, PageHeader, Pill } from '@/components/ui';
import {
  ActivityIcon,
  ArrowRightIcon,
  BadgeCheckIcon,
  ChartIcon,
  DashboardIcon,
  DollarIcon,
  EyeIcon,
  FileTextIcon,
  FlagIcon,
  GaugeIcon,
  GlobeIcon,
  InboxIcon,
  MergeIcon,
  SearchIcon,
  SendIcon,
  ShieldCheckIcon,
  StarIcon,
  TrendingUpIcon,
} from '@/components/Icons';

type Overview = {
  kpis: Record<string, number | null>;
  queues: Record<string, number>;
  leads30d: number;
  spam30d: number;
  firms: number;
  leadsByDay: { day: string; leads: number }[];
  revenueByCity: { city: string; revenue: number }[];
  pagesByType: { page_type: string; total: number; eligible: number }[];
  lastRankingRun: { id: number; status: string; finishedAt: string | null; rankingsCount: number; version: string } | null;
  searchConsole: { connected: boolean; note: string };
};

export default async function Dashboard() {
  const [o, user] = await Promise.all([api<Overview>('/admin/overview'), me()]);
  // Lead PII and commerce are admin-only in the API; don't link other staff to a 403
  const admin = isAdmin(user.role);
  const enquiries = admin ? await api<{ items: { id: number; publicId: string; name: string; email: string; description: string; status: string; createdAt: string; recipients: EnquiryRecipient[] }[]; total: number }>('/admin/leads?pageSize=8') : null;
  const k = o.kpis;
  const maxRevenue = Math.max(1, ...o.revenueByCity.map((r) => r.revenue));
  const queues: [string, number, string, typeof ShieldCheckIcon][] = [
    ['Verification checks waiting', o.queues.verification ?? 0, '/verification', ShieldCheckIcon],
    ['Profile claims to review', o.queues.claims ?? 0, '/claims', ShieldCheckIcon],
    ['Credentials to verify', o.queues.changeRequests ?? 0, '/change-requests', ShieldCheckIcon],
    ['Possible duplicates', o.queues.duplicates ?? 0, '/duplicates', MergeIcon],
    ['Reviews awaiting moderation', o.queues.reviews ?? 0, '/reviews', StarIcon],
    ['Open corrections and disputes', o.queues.corrections ?? 0, '/corrections', FlagIcon],
    ['Draft profiles', o.queues.drafts ?? 0, '/lawyers?status=draft', FileTextIcon],
  ];
  const totalLeads = o.leadsByDay.reduce((s, d) => s + d.leads, 0);
  return (
    <>
      <PageHeader title="Dashboard" icon={<DashboardIcon className="h-5 w-5" />} description="Justice Choice platform KPIs for justicechoice.com, over the last 30 days unless stated." />

      <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-6">
        <Kpi label="Verified lawyers" icon={<BadgeCheckIcon className="h-4 w-4" />} value={n(k.verifiedLawyers)} hint={`${pct(k.verifiedShare)} of ${n(k.publishedLawyers)} published`} href="/lawyers?verification=verified" />
        <Kpi label="Profile completeness" icon={<GaugeIcon className="h-4 w-4" />} value={pct(k.profileCompleteness)} hint="average across published" href="/data-quality" />
        <Kpi label="Indexable pages" icon={<GlobeIcon className="h-4 w-4" />} value={n(k.eligiblePages)} hint={`of ${n(k.totalPages)} evaluated`} href="/seo" />
        <Kpi label="Enquiries" icon={<InboxIcon className="h-4 w-4" />} value={n(o.leads30d)} hint={`${n(o.spam30d)} flagged as spam`} href={admin ? '/leads' : undefined} />
        <Kpi label="Lead acceptance" icon={<SendIcon className="h-4 w-4" />} value={pct(k.leadAcceptanceRate)} hint={`response rate ${pct(k.leadResponseRate)}`} />
        <Kpi label="Revenue" icon={<DollarIcon className="h-4 w-4" />} value={money(k.revenue30d)} hint={`paid conversion ${pct(k.paidConversion)}`} href={admin ? '/commerce' : undefined} />
        <Kpi label="Search → profile" icon={<SearchIcon className="h-4 w-4" />} value={pct(k.searchToProfile)} hint="profile views per search" />
        <Kpi label="Profile → lead" icon={<TrendingUpIcon className="h-4 w-4" />} value={pct(k.profileToLead)} hint="leads per profile view" />
        <Kpi label="Data freshness" icon={<ActivityIcon className="h-4 w-4" />} value={pct(k.dataFreshness)} hint="verified within 12 months" />
        <Kpi label="Correction rate" icon={<FlagIcon className="h-4 w-4" />} value={k.correctionRate != null ? `${k.correctionRate}‰` : '—'} hint="reports per 1,000 profiles, 90 days" href="/corrections" />
        <Kpi label="Organic impressions" tone="muted" icon={<EyeIcon className="h-4 w-4" />} value="—" hint="Search Console not connected" />
        <Kpi label="Organic clicks" tone="muted" icon={<EyeIcon className="h-4 w-4" />} value="—" hint="Search Console not connected" />
      </div>

      {enquiries && <Card className="mt-6" title="Recent enquiries and relevant lawyers" icon={<InboxIcon />} actions={<div className="flex flex-wrap gap-2"><Link href="/leads/lawyers" className="btn btn-quiet btn-xs">By lawyer<ArrowRightIcon /></Link><Link href="/leads" className="btn btn-quiet btn-xs">All enquiries ({n(enquiries.total)})<ArrowRightIcon /></Link></div>}>
        {enquiries.items.length ? <div className="overflow-x-auto"><table className="tbl"><thead><tr><th>Received / reference</th><th>Client</th><th>Enquiry</th><th>Relevant lawyer / delivery</th><th>Status</th></tr></thead><tbody>{enquiries.items.map(e => <tr key={e.id}><td><Link href={`/leads/${e.id}`} className="font-medium hover:text-ledger">{date(e.createdAt,true)}</Link><span className="block text-xs text-muted">{e.publicId}</span></td><td>{e.name}<span className="block text-xs text-muted">{e.email}</span></td><td><Link href={`/leads/${e.id}`} className="line-clamp-2 max-w-xs text-sm hover:text-ledger">{e.description}</Link></td><td><EnquiryRecipients recipients={e.recipients} /></td><td><Pill value={e.status} /></td></tr>)}</tbody></table></div> : <p className="p-6 text-sm text-muted">No enquiries yet. Incoming enquiries and their relevant lawyers will appear here.</p>}
      </Card>}

      <div className="mt-6 grid gap-6 xl:grid-cols-[1.6fr_1fr]">
        <Card title="Leads per day" icon={<InboxIcon className="h-4 w-4" />} actions={<span className="num text-xs text-muted">{n(totalLeads)} in 30 days</span>}>
          <div className="p-4">
            <BarChart data={o.leadsByDay.map((d) => ({ x: d.day.slice(5), y: d.leads }))} label="Leads per day, last 30 days" />
          </div>
        </Card>
        <Card title="Work queues" icon={<ShieldCheckIcon className="h-4 w-4" />}>
          <ul className="divide-y divide-rule text-sm">
            {queues.map(([label, v, href, Icon]) => (
              <li key={href}>
                <Link href={href} className="group flex items-center gap-3 px-4 py-3 transition-colors hover:bg-ledger-tint">
                  <span className={`grid h-8 w-8 place-items-center rounded-lg ${v > 0 ? 'bg-brass-soft text-brass' : 'bg-sunken text-muted'}`}>
                    <Icon className="h-4 w-4" />
                  </span>
                  <span className="flex-1 font-medium text-ink-2 group-hover:text-ink">{label}</span>
                  <span className={`num rounded-full px-2 py-0.5 text-xs font-bold ${v > 0 ? 'bg-brass-soft text-brass' : 'text-muted'}`}>{n(v)}</span>
                  <ArrowRightIcon className="h-3.5 w-3.5 text-muted transition-transform group-hover:translate-x-0.5 group-hover:text-ledger" />
                </Link>
              </li>
            ))}
          </ul>
        </Card>
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-3">
        <Card
          title="SEO eligibility by page type"
          icon={<GlobeIcon className="h-4 w-4" />}
          actions={
            <Link href="/seo" className="btn btn-ghost btn-xs">
              Open <ArrowRightIcon className="h-3 w-3" />
            </Link>
          }
        >
          <table className="tbl">
            <thead>
              <tr>
                <th>Type</th>
                <th className="w-28">Indexable</th>
                <th className="text-right">Total</th>
              </tr>
            </thead>
            <tbody>
              {o.pagesByType.map((p) => (
                <tr key={p.page_type}>
                  <td className="capitalize">{p.page_type.replace(/_/g, ' × ')}</td>
                  <td>
                    <div className="flex items-center gap-2">
                      <span className="h-1.5 w-12 overflow-hidden rounded-full bg-sunken">
                        <span className="block h-full rounded-full bg-[var(--g-expertise)]" style={{ width: `${p.total ? (p.eligible / p.total) * 100 : 0}%` }} />
                      </span>
                      <span className="num">{n(p.eligible)}</span>
                    </div>
                  </td>
                  <td className="num text-right text-muted">{n(p.total)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
        <Card title="Revenue by city (all time)" icon={<DollarIcon className="h-4 w-4" />}>
          {o.revenueByCity.length ? (
            <table className="tbl">
              <tbody>
                {o.revenueByCity.map((r) => (
                  <tr key={r.city}>
                    <td className="w-1/3">{r.city}</td>
                    <td>
                      <span className="block h-1.5 overflow-hidden rounded-full bg-sunken">
                        <span className="block h-full rounded-full bg-[var(--g-standing)]" style={{ width: `${(r.revenue / maxRevenue) * 100}%` }} />
                      </span>
                    </td>
                    <td className="num text-right font-semibold">{money(r.revenue)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <p className="p-4 text-sm text-muted">No payments recorded yet.</p>
          )}
        </Card>
        <Card
          title="Latest ranking run"
          icon={<ChartIcon className="h-4 w-4" />}
          actions={
            <Link href="/rankings" className="btn btn-ghost btn-xs">
              Open <ArrowRightIcon className="h-3 w-3" />
            </Link>
          }
        >
          {o.lastRankingRun ? (
            <dl className="grid grid-cols-[auto_1fr] gap-x-6 gap-y-3 p-4 text-sm">
              <dt className="text-muted">Run</dt>
              <dd className="num font-semibold">#{o.lastRankingRun.id}</dd>
              <dt className="text-muted">Status</dt>
              <dd>
                <Pill value={o.lastRankingRun.status} />
              </dd>
              <dt className="text-muted">Version</dt>
              <dd className="num">{o.lastRankingRun.version}</dd>
              <dt className="text-muted">Rankings</dt>
              <dd className="num">{n(o.lastRankingRun.rankingsCount)}</dd>
              <dt className="text-muted">Finished</dt>
              <dd>{date(o.lastRankingRun.finishedAt, true)}</dd>
            </dl>
          ) : (
            <p className="p-4 text-sm text-muted">No runs yet.</p>
          )}
        </Card>
      </div>
    </>
  );
}
