import Link from "next/link";
import { headers } from "next/headers";
import { notFound } from "next/navigation";
import { DesignForm, InstagramForm, RedirectsPanel, RelatedPagesPanel, RobotsForm, SeoForm, SiteSettingsTabs } from "@/components/features/site-admin";
import { COUNTRIES } from "@/lib/i18n/countries";
import { Badge, Card, EmptyState, PageHeader } from "@/components/ui";
import { canAnywhere, type DashboardKind } from "@/lib/authz/context";
import { requireDashboard } from "@/lib/authz/guard";
import { AuthError } from "@/lib/authz/errors";
import { getActiveSiteId, listAccessibleSites } from "@/lib/data/sites";
import { cn } from "@/lib/utils";
import { redirectUri } from "@/lib/services/instagram";
import { buildRobotsTxt } from "@/lib/public/robots";
import { getRelatedPagesData, getSiteAdminData } from "@/lib/services/site-admin";

const first = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v);

export async function SeoScreen({ kind, searchParams }: { kind: Extract<DashboardKind, "admin">; searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const ctx = await requireDashboard(kind);
  if (!canAnywhere(ctx, "settings.manage") && !canAnywhere(ctx, "seo.manage")) notFound();
  const siteId = await getActiveSiteId(await listAccessibleSites(ctx));
  if (!siteId) return (<><PageHeader title="SEO & settings" /><Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown)." /></Card></>);
  let d;
  try { d = await getSiteAdminData(siteId); } catch (e) { if (e instanceof AuthError) notFound(); throw e; }
  const tabs: Array<[string, string]> = [];
  if (d.perms.seo || d.perms.settings) tabs.push(["seo", "SEO"]);
  if (d.perms.settings) tabs.push(["site", "Site settings"], ["design", "Design & appearance"], ["instagram", "Instagram"]);
  if (d.perms.seo) tabs.push(["redirects", "Redirects"], ["related", "Related pages"], ["robots", "Site robots.txt"]);
  tabs.push(["domains", "Domains & crawling"]);
  const sp = await searchParams;
  const tab = tabs.find(([k]) => k === first(sp.tab))?.[0] ?? tabs[0]![0];
  const base = `/dashboard/${kind}/seo`;
  const primary = d.domains.find((x) => x.isPrimary) ?? d.domains[0];
  const hdrs = await headers();
  const origin = `${hdrs.get("x-forwarded-proto") ?? "http"}://${hdrs.get("host") ?? "localhost:3000"}`;
  const related = tab === "related" ? await getRelatedPagesData(siteId) : null;
  const timezones = typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : [d.timezone];

  return (
    <>
      <PageHeader title="SEO & settings" description={d.site.name} />
      <nav aria-label="Settings sections" className="mb-4 flex gap-1 border-b border-border">
        {tabs.map(([k, label]) => (
          <Link key={k} href={`${base}?tab=${k}`} aria-current={tab === k ? "page" : undefined} className={cn("-mb-px border-b-2 px-3 py-2 text-sm", tab === k ? "border-primary font-medium" : "border-transparent text-muted-foreground hover:text-foreground")}>{label}</Link>
        ))}
      </nav>
      {tab === "seo" ? <SeoForm siteId={siteId} settings={d.settings} countries={COUNTRIES.map((c) => ({ code: c.code, name: c.name }))} /> : null}
      {tab === "site" ? <SiteSettingsTabs siteId={siteId} settings={d.settings} timezone={d.timezone} timezones={timezones} pages={d.pages} libraries={d.libraries} recaptchaSecretSet={d.recaptchaSecretSet} isSuperAdmin={d.isSuperAdmin} thirdPartyCount={d.thirdPartyCount} primaryHost={primary?.hostname ?? null} /> : null}
      {tab === "design" ? <DesignForm siteId={siteId} design={d.theme.design} textColour={d.theme.text} primaryColour={d.theme.primary} backgroundColour={d.theme.background} /> : null}
      {tab === "redirects" ? <RedirectsPanel siteId={siteId} rows={d.redirects} /> : null}
      {tab === "instagram" ? <InstagramForm siteId={siteId} instagram={d.settings.instagram} secretSet={d.instagramSecretSet} connected={d.instagramConnected} redirectUri={redirectUri(origin)} notice={first(sp.ig)} /> : null}
      {tab === "related" && related ? <RelatedPagesPanel siteId={siteId} data={related} /> : null}
      {tab === "robots" ? <RobotsForm siteId={siteId} robotsFile={d.settings.seo.robotsFile} indexing={d.settings.allowIndexing} generated={buildRobotsTxt({ allowIndexing: true, robotsFile: "", robotsExtra: d.settings.seo.robotsExtra, sitemapUrl: `https://${primary?.hostname ?? "your-domain.example"}/sitemap.xml` })} /> : null}
      {tab === "domains" ? (
        <div className="space-y-4">
          <Card>
            <table className="w-full text-left text-sm">
              <thead className="border-b border-border text-xs text-muted-foreground"><tr><th className="px-4 py-2 font-medium">Domain</th><th className="px-4 py-2 font-medium">Role</th><th className="px-4 py-2 font-medium">Verified</th></tr></thead>
              <tbody className="divide-y divide-border">
                {d.domains.map((x) => (
                  <tr key={x.id}><td className="px-4 py-2 font-mono text-xs">{x.hostname}</td><td className="px-4 py-2">{x.isPrimary ? <Badge>Primary</Badge> : "Alias"}</td><td className="px-4 py-2">{x.verifiedAt ? x.verifiedAt.toISOString().slice(0, 10) : "Not verified"}</td></tr>
                ))}
              </tbody>
            </table>
            <p className="border-t border-border px-4 py-3 text-xs text-muted-foreground">Domains are attached by a platform administrator. Ask for a change through a maintenance request.</p>
          </Card>
          {primary ? (
            <Card className="space-y-2 p-4 text-sm">
              <h2 className="text-sm font-semibold">Crawling</h2>
              <p>{d.settings.allowIndexing ? "Search engines may index this website." : "Indexing is turned off: pages are served with noindex and crawling is disallowed."}</p>
              <p className="text-muted-foreground">Sitemap: <span className="font-mono text-xs">https://{primary.hostname}/sitemap.xml</span> · Robots: <span className="font-mono text-xs">https://{primary.hostname}/robots.txt</span></p>
            </Card>
          ) : null}
        </div>
      ) : null}
    </>
  );
}
