import { api, ApiError } from '@/lib/api';
import { n } from '@/lib/format';
import { BarChart } from '@/components/BarChart';
import { Card, Kpi, PageHeader } from '@/components/ui';
import { ChartIcon, EyeIcon, InboxIcon, LockIcon, SendIcon, TrendingUpIcon } from '@/components/Icons';

type A = {
  daily: { day: string; views: number; enquiries: number }[];
  totals: { views: number; enquiries: number; accepted: number; avg_response_hours: number | null; viewToEnquiry: number | null; acceptance: number | null };
  sources: { source: string; views: number }[];
  note: string;
};

export default async function Analytics() {
  let d: A | null = null;
  let locked = '';
  try {
    d = await api<A>('/me/analytics');
  } catch (e) {
    if (e instanceof ApiError && e.status === 403) locked = e.message;
    else throw e;
  }
  if (!d)
    return (
      <>
        <PageHeader title="Analytics" icon={<ChartIcon className="h-5 w-5" />} />
        <div className="card mx-auto mt-6 flex max-w-lg flex-col items-center p-10 text-center">
          <span className="grid h-14 w-14 place-items-center rounded-2xl bg-brass-soft text-brass">
            <LockIcon className="h-7 w-7" />
          </span>
          <h2 className="mt-4 font-serif text-xl font-semibold">Profile analytics is a Premium feature</h2>
          <p className="mt-2 text-sm text-muted">{locked} Your basic 30-day views stay on the Overview, and your ranking is never affected by your plan.</p>
          <a href="/portal/billing" className="btn btn-primary btn-sm mt-6">
            See plans
          </a>
        </div>
      </>
    );
  const t = d.totals;
  return (
    <>
      <PageHeader title="Analytics" icon={<ChartIcon className="h-5 w-5" />} description={`Last 90 days. ${d.note}`} />
      <div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-5">
        <Kpi label="Profile views" icon={<EyeIcon className="h-4 w-4" />} value={n(t.views)} />
        <Kpi label="Enquiries" icon={<InboxIcon className="h-4 w-4" />} value={n(t.enquiries)} />
        <Kpi label="View → enquiry" icon={<TrendingUpIcon className="h-4 w-4" />} value={t.viewToEnquiry != null ? `${t.viewToEnquiry}%` : '—'} />
        <Kpi label="Accepted" icon={<SendIcon className="h-4 w-4" />} value={t.acceptance != null ? `${t.acceptance}%` : '—'} hint={`${n(t.accepted)} enquiries`} />
        <Kpi label="Avg. response" icon={<SendIcon className="h-4 w-4" />} value={t.avg_response_hours != null ? `${t.avg_response_hours} h` : '—'} hint="to accept or decline" />
      </div>
      <div className="grid gap-6 xl:grid-cols-[1.6fr_1fr]">
        <div className="space-y-6">
          <Card title="Profile views per day" icon={<EyeIcon className="h-4 w-4" />}>
            <div className="p-4">
              <BarChart data={d.daily.map((x) => ({ x: x.day.slice(5), y: x.views }))} label="Daily profile views" />
            </div>
          </Card>
          <Card title="Enquiries per day" icon={<InboxIcon className="h-4 w-4" />}>
            <div className="p-4">
              <BarChart data={d.daily.map((x) => ({ x: x.day.slice(5), y: x.enquiries }))} label="Daily enquiries" />
            </div>
          </Card>
        </div>
        <Card title="Where visitors came from">
          {d.sources.length ? (
            <ul className="divide-y divide-rule text-sm">
              {d.sources.map((s) => (
                <li key={s.source} className="flex justify-between px-4 py-2.5">
                  <span>{s.source}</span>
                  <span className="num">{n(s.views)}</span>
                </li>
              ))}
            </ul>
          ) : (
            <p className="p-4 text-sm text-muted">No visits recorded yet.</p>
          )}
          <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">Referring site only — we never record visitors’ identities.</p>
        </Card>
      </div>
    </>
  );
}
