
import * as ActionIcons from '@/components/Icons';
import Link from 'next/link';
import { api, canEdit, me } from '@/lib/api';
import { date, PUBLIC_SITE } from '@/lib/format';
import { Card, Flash, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { ArrowLeftIcon, CodeIcon, ExternalLinkIcon, FileTextIcon, GlobeIcon, SaveIcon } from '@/components/Icons';
import { savePageConfig } from '../../../actions';

type Cfg = {
  path: string;
  config: { indexDirective: string; h1Override: string | null; intro: string | null; localResources: { name: string; url?: string; note?: string }[] | null; faqs: { q: string; a: string }[] | null; notes: string | null; updatedAt: string } | null;
  page: { isEligible: boolean; robots: string; eligibilityScore: string; reasons: string[] | null; metrics: Record<string, unknown> | null; lastEvaluatedAt: string; title: string } | null;
};

export default async function PageConfig({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const path = sp.path?.startsWith('/') ? sp.path : '/';
  const [d, user] = await Promise.all([api<Cfg>(`/admin/seo/page-config?path=${encodeURIComponent(path)}`), me()]);
  const c = d.config;
  const editable = canEdit(user.role);
  return (
    <>
      <Link href="/seo" className="mb-3 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
        <ArrowLeftIcon className="h-4 w-4" /> All pages
      </Link>
      <PageHeader
        title="Page content & index control"
        icon={<FileTextIcon className="h-5 w-5" />}
        description={<span className="num break-all">{path}</span>}
        actions={
          <a href={`${PUBLIC_SITE}${path}`} target="_blank" rel="noopener" className="btn btn-quiet btn-sm">
            <ExternalLinkIcon className="h-4 w-4" /> View page
          </a>
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <div className="grid gap-6 xl:grid-cols-[1.4fr_1fr]">
        <Card title="Editorial content" icon={<FileTextIcon className="h-4 w-4" />}>
          <form action={savePageConfig} className="space-y-4 p-5 text-sm">
            <input type="hidden" name="path" value={path} />
            <fieldset disabled={!editable} className="space-y-4">
              <label className="block">
                <span className="field-label"><ActionIcons.ActivityIcon />Indexing</span>
                <select name="indexDirective" defaultValue={c?.indexDirective ?? 'auto'} className="field max-w-sm">
                  <option value="auto">Automatic (eligibility engine decides)</option>
                  <option value="force_index">Force index (never for duplicates)</option>
                  <option value="force_noindex">Force noindex</option>
                </select>
              </label>
              <label className="block">
                <span className="field-label"><ActionIcons.FileTextIcon />Title override</span>
                <input name="h1Override" maxLength={200} defaultValue={c?.h1Override ?? ''} className="field" />
              </label>
              <label className="block">
                <span className="field-label"><ActionIcons.FileTextIcon />Local introduction</span>
                <textarea name="intro" rows={6} defaultValue={c?.intro ?? ''} className="field" placeholder="Genuinely local explanation: courts, procedures, what matters in this city." />
              </label>
              <label className="block">
                <span className="field-label">
                  Local resources <span className="font-normal text-muted">— one per line: name | url | note</span>
                </span>
                <textarea name="resources" rows={4} spellCheck={false} defaultValue={(c?.localResources ?? []).map((r) => [r.name, r.url ?? '', r.note ?? ''].join(' | ')).join('\n')} className="field font-mono text-xs" />
              </label>
              <label className="block">
                <span className="field-label">
                  FAQs <span className="font-normal text-muted">— question on one line, answer below, blank line between</span>
                </span>
                <textarea name="faqs" rows={7} defaultValue={(c?.faqs ?? []).map((f) => `${f.q}\n${f.a}`).join('\n\n')} className="field" />
              </label>
              <label className="block">
                <span className="field-label"><ActionIcons.FileTextIcon />Internal notes</span>
                <input name="notes" maxLength={1000} defaultValue={c?.notes ?? ''} className="field" />
              </label>
            </fieldset>
            <div className="flex flex-wrap items-center gap-3 border-t border-rule pt-4">
              {editable ? (
                <SubmitButton pendingLabel="Saving…">
                  <SaveIcon className="h-4 w-4" /> Save content
                </SubmitButton>
              ) : (
                <span className="text-xs text-muted">Read-only for your role.</span>
              )}
              {c && <span className="text-xs text-muted">Last saved {date(c.updatedAt, true)}</span>}
            </div>
          </form>
        </Card>
        <Card title="Eligibility decision" icon={<GlobeIcon className="h-4 w-4" />} className="self-start">
          {d.page ? (
            <div className="space-y-4 p-4 text-sm">
              <div className="flex flex-wrap items-center gap-3">
                <Pill value={d.page.isEligible ? 'index' : 'noindex'} tone={d.page.isEligible ? 'good' : 'warn'} />
                <span className="num font-serif text-2xl font-semibold">{Number(d.page.eligibilityScore).toFixed(0)}</span>
                <span className="text-xs text-muted">/ 100 · evaluated {date(d.page.lastEvaluatedAt, true)}</span>
              </div>
              <p className="font-medium">{d.page.title}</p>
              <ul className="space-y-1.5 text-ink-2">
                {(d.page.reasons ?? []).map((r) => (
                  <li key={r} className="flex gap-2">
                    <span className="mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-muted" />
                    {r}
                  </li>
                ))}
              </ul>
              {d.page.metrics && (
                <details className="group">
                  <summary className="inline-flex cursor-pointer items-center gap-1.5 text-xs font-medium text-muted hover:text-ink">
                    <CodeIcon className="h-3.5 w-3.5" /> Signals
                  </summary>
                  <pre className="mt-2 max-h-80 overflow-auto rounded-lg bg-sunken p-3 text-[11px]">{JSON.stringify(d.page.metrics, null, 2)}</pre>
                </details>
              )}
            </div>
          ) : (
            <p className="p-4 text-sm text-muted">This path has not been evaluated.</p>
          )}
        </Card>
      </div>
    </>
  );
}
