import { api, isAdmin, me } from '@/lib/api';
import { date, n } from '@/lib/format';
import { BarChart } from '@/components/BarChart';
import { Card, Empty, Flash, Forbidden, Kpi, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { AlertIcon, GlobeIcon, RefreshIcon } from '@/components/Icons';
import { syncSearchConsole } from '../../actions';

type G = {
  configured: boolean;
  site: string | null;
  status: { lastSyncAt?: string; lastError?: string | null; rows?: number; from?: string; to?: string } | null;
  days: number;
  totals: { clicks: number; impressions: number; ctr: number | null; position: number | null };
  daily: { date: string; clicks: number; impressions: number }[];
  topPages: { page: string; clicks: number; impressions: number }[];
  sitemaps: { path: string; lastSubmitted?: string; lastDownloaded?: string; isPending?: boolean; errors?: string; warnings?: string; contents?: { type: string; submitted: string; indexed?: string }[] }[];
  sitemapError: string | null;
};

export default async function SearchConsole({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const viewer = await me();
  if (!isAdmin(viewer.role)) return <Forbidden what="Search Console" />;
  const d = await api<G>('/admin/search-console');
  return (
    <>
      <PageHeader
        title="Search Console"
        icon={<GlobeIcon className="h-5 w-5" />}
        description={d.configured ? `Google Search Console for ${d.site}. Imported daily; Google’s data lags 2–3 days.` : 'Organic search performance from Google, imported daily.'}
        actions={
          d.configured && (
            <form action={syncSearchConsole}>
              <SubmitButton className="btn btn-quiet btn-sm" pendingLabel="Importing…">
                <RefreshIcon className="h-4 w-4" /> Import now
              </SubmitButton>
            </form>
          )
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      {!d.configured && (
        <Card title="Connect Google Search Console" className="mb-6">
          <ol className="list-decimal space-y-2 p-5 pl-10 text-sm text-ink-2">
            <li>In Google Cloud, create a service account and download its JSON key. Enable the “Google Search Console API”.</li>
            <li>In Search Console → Settings → Users and permissions, add the service account’s email (read access is enough).</li>
            <li>
              Set <code>GSC_SITE_URL</code> (e.g. <code>sc-domain:justicechoice.com</code>) and <code>GSC_CREDENTIALS</code> (the JSON key, raw or base64) in the API environment, then restart the API.
            </li>
          </ol>
          <p className="border-t border-rule px-5 py-2.5 text-xs text-muted">Read-only access. Nothing is changed in your Google account.</p>
        </Card>
      )}
      {d.status?.lastError && (
        <p className="mb-6 flex items-start gap-2 rounded-lg border border-danger/30 bg-danger-soft px-4 py-3 text-sm text-danger">
          <AlertIcon className="mt-0.5 h-4 w-4" /> Last import failed: {d.status.lastError}
        </p>
      )}
      <div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-4">
        <Kpi label={`Clicks, ${d.days} days`} icon={<GlobeIcon className="h-4 w-4" />} value={n(d.totals.clicks)} />
        <Kpi label="Impressions" icon={<GlobeIcon className="h-4 w-4" />} value={n(d.totals.impressions)} />
        <Kpi label="CTR" icon={<GlobeIcon className="h-4 w-4" />} value={d.totals.ctr != null ? `${(d.totals.ctr * 100).toFixed(1)}%` : '—'} />
        <Kpi label="Avg. position" icon={<GlobeIcon className="h-4 w-4" />} value={d.totals.position ?? '—'} hint={d.status?.lastSyncAt ? `imported ${date(d.status.lastSyncAt, true)}` : 'not imported yet'} />
      </div>
      <div className="grid gap-6 xl:grid-cols-2">
        <Card title="Clicks per day">
          <div className="p-4">{d.daily.length ? <BarChart data={d.daily.map((x) => ({ x: x.date.slice(5), y: x.clicks }))} label="Clicks" /> : <Empty>No data imported yet.</Empty>}</div>
        </Card>
        <Card title="Top pages">
          {d.topPages.length ? (
            <table className="tbl">
              <thead>
                <tr>
                  <th>Page</th>
                  <th className="text-right">Clicks</th>
                  <th className="text-right">Impr.</th>
                </tr>
              </thead>
              <tbody>
                {d.topPages.map((p) => (
                  <tr key={p.page}>
                    <td className="max-w-[22rem] truncate text-xs" title={p.page}>
                      {p.page}
                    </td>
                    <td className="num text-right">{n(p.clicks)}</td>
                    <td className="num text-right">{n(p.impressions)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <Empty>No data imported yet.</Empty>
          )}
        </Card>
      </div>
      {d.configured && (
        <Card title="Sitemaps in Search Console" className="mt-6">
          {d.sitemapError ? (
            <p className="p-4 text-sm text-danger">{d.sitemapError}</p>
          ) : d.sitemaps.length ? (
            <table className="tbl">
              <thead>
                <tr>
                  <th>Sitemap</th>
                  <th>Last read</th>
                  <th>Submitted / indexed</th>
                  <th>Issues</th>
                </tr>
              </thead>
              <tbody>
                {d.sitemaps.map((s) => (
                  <tr key={s.path}>
                    <td className="text-xs">{s.path}</td>
                    <td className="text-xs">{s.isPending ? <Pill value="pending" /> : date(s.lastDownloaded, true)}</td>
                    <td className="num text-xs">{s.contents?.map((c) => `${c.submitted}${c.indexed ? ` / ${c.indexed}` : ''}`).join(', ') ?? '—'}</td>
                    <td className="text-xs">{Number(s.errors) || Number(s.warnings) ? <Pill value={`${s.errors ?? 0} errors, ${s.warnings ?? 0} warnings`} tone="warn" /> : 'None'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <Empty>No sitemaps submitted. Submit /sitemap.xml in Search Console.</Empty>
          )}
        </Card>
      )}
    </>
  );
}
