
import Link from 'next/link';
import { api, canEdit, me } from '@/lib/api';
import { date, n, PUBLIC_SITE } from '@/lib/format';
import { Card, Empty, Flash, PageHeader, Pager, Pill, SearchField, Toolbar, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { ExternalLinkIcon, FilterIcon, GlobeIcon, RefreshIcon, XIcon } from '@/components/Icons';
import { evaluateSeo } from '../../actions';

type Page = { id: number; pageType: string; path: string; canonicalPath: string; title: string; isEligible: boolean; robots: string; score: string; reasons: string[] | null; inSitemap: boolean; sitemapSegment: string | null; lastEvaluatedAt: string };

export default async function Seo({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const qs = new URLSearchParams(Object.entries(sp).filter(([k, v]) => v && ['type', 'eligible', 'q', 'page', 'sort'].includes(k)) as [string, string][]);
  const [d, user] = await Promise.all([
    api<{ items: Page[]; total: number; page: number; pageCount: number; summary: { page_type: string; total: number; eligible: number; near: number }[] }>(`/admin/seo/pages?${qs}`),
    me(),
  ]);
  const filtered = Boolean(sp.q || sp.type || sp.eligible || sp.sort);
  return (
    <>
      <PageHeader
        title="SEO eligibility & indexation"
        icon={<GlobeIcon className="h-5 w-5" />}
        description="A page is indexed only when it has enough relevant and verified professionals, local information, ranking data and unique content, and no other page covers the same intent. Everything else renders with noindex and stays out of the sitemaps."
        actions={
          canEdit(user.role) && (
            <form action={evaluateSeo}>
              <SubmitButton pendingLabel="Evaluating…">
                <RefreshIcon className="h-4 w-4" /> Re-evaluate all pages
              </SubmitButton>
            </form>
          )
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-4 xl:grid-cols-7">
        {d.summary.map((s) => {
          const share = s.total ? Math.round((s.eligible / s.total) * 100) : 0;
          const on = sp.type === s.page_type;
          return (
            <Link key={s.page_type} href={on ? '/seo' : `/seo?type=${s.page_type}`} aria-current={on ? 'true' : undefined} className={`card card-hover p-3.5 ${on ? 'border-ledger ring-1 ring-ledger' : ''}`}>
              <p className="truncate text-xs font-medium capitalize text-muted">{s.page_type.replace(/_/g, ' × ')}</p>
              <p className="num mt-0.5 font-serif text-xl font-semibold">
                {n(s.eligible)} <span className="text-sm font-normal text-muted">/ {n(s.total)}</span>
              </p>
              <span className="mt-2 block h-1 overflow-hidden rounded-full bg-sunken">
                <span className="block h-full rounded-full bg-[var(--g-expertise)]" style={{ width: `${share}%` }} />
              </span>
              <p className="mt-1.5 text-[11px] text-muted">{s.near} close to the bar</p>
            </Link>
          );
        })}
      </div>
      <Toolbar>
        <SearchField name="q" defaultValue={sp.q} placeholder="Path contains…" />
        <select name="type" defaultValue={sp.type ?? ''} className="field w-auto min-w-40" aria-label="Page type">
          <option value="">All types</option>
          {d.summary.map((s) => (
            <option key={s.page_type} value={s.page_type}>
              {s.page_type.replace(/_/g, ' × ')}
            </option>
          ))}
        </select>
        <select name="eligible" defaultValue={sp.eligible ?? ''} className="field w-auto min-w-32" aria-label="Indexation">
          <option value="">Any</option>
          <option value="true">Indexable</option>
          <option value="false">Noindex</option>
        </select>
        <select name="sort" defaultValue={sp.sort ?? ''} className="field w-auto min-w-44" aria-label="Sort">
          <option value="">Sort by path</option>
          <option value="score">Sort by eligibility score</option>
        </select>
        <button className="btn btn-quiet">
          <FilterIcon className="h-4 w-4" /> Filter
        </button>
        {filtered && (
          <Link href="/seo" className="btn btn-ghost">
            <XIcon className="h-4 w-4" /> Clear
          </Link>
        )}
      </Toolbar>
      <Card>
        {d.items.length ? (
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Page</th>
                  <th>Type</th>
                  <th>Robots</th>
                  <th className="text-right">Score</th>
                  <th>Why</th>
                  <th>Sitemap</th>
                  <th>Evaluated</th>
                </tr>
              </thead>
              <tbody>
                {d.items.map((p) => {
                  const score = Number(p.score);
                  return (
                    <tr key={p.id}>
                      <td className="max-w-80">
                        <div className="flex items-center gap-1.5">
                          <Link href={`/seo/page?path=${encodeURIComponent(p.path)}`} className="num block truncate font-semibold hover:text-ledger hover:underline" title={p.path}>
                            {p.path}
                          </Link>
                          <a href={`${PUBLIC_SITE}${p.path}`} target="_blank" rel="noopener" aria-label="Open the public page" className="shrink-0 text-muted hover:text-ledger">
                            <ExternalLinkIcon className="h-3.5 w-3.5" />
                          </a>
                        </div>
                        {p.canonicalPath !== p.path && <p className="num truncate text-xs text-warn">canonical → {p.canonicalPath}</p>}
                      </td>
                      <td className="whitespace-nowrap capitalize">{p.pageType.replace(/_/g, ' ')}</td>
                      <td>
                        <Pill value={p.isEligible ? 'index' : 'noindex'} tone={p.isEligible ? 'good' : 'warn'} />
                      </td>
                      <td className="text-right">
                        <span className={`num inline-block min-w-9 rounded-md px-1.5 py-0.5 text-center text-xs font-bold ${score >= 70 ? 'bg-ledger-soft text-ledger' : score >= 40 ? 'bg-brass-soft text-brass' : 'bg-sunken text-muted'}`}>{score.toFixed(0)}</span>
                      </td>
                      <td className="max-w-96 text-xs text-ink-2">{(p.reasons ?? []).slice(0, p.isEligible ? 1 : 3).join('; ')}</td>
                      <td className="text-xs">{p.inSitemap ? <span className="num">{p.sitemapSegment}</span> : <span className="text-muted">—</span>}</td>
                      <td className="whitespace-nowrap text-xs text-muted">{date(p.lastEvaluatedAt)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<GlobeIcon className="h-6 w-6" />}>No pages match these filters.</Empty>
        )}
        <Pager page={d.page} pageCount={d.pageCount} total={d.total} href={(pg) => `/seo?${new URLSearchParams({ ...Object.fromEntries(qs), page: String(pg) })}`} />
      </Card>
    </>
  );
}
