"use client";

import { useActionState, useState } from "react";
import { savePagesAction } from "@/app/admin/actions";
import type { ActionState } from "@/lib/form";
import type { NavItemCms, PageCopy, SiteSettings } from "@/lib/cms";

/* ------------------------------ primitives ------------------------------ */

function Field({
  label,
  name,
  defaultValue,
  textarea = false,
  rows = 2,
  hint,
}: {
  label: string;
  name: string;
  defaultValue: string;
  textarea?: boolean;
  rows?: number;
  hint?: string;
}) {
  return (
    <div>
      <label htmlFor={name} className="field-label">
        {label}
      </label>
      {textarea ? (
        <textarea
          id={name}
          name={name}
          rows={rows}
          defaultValue={defaultValue}
          className="field-textarea resize-y"
        />
      ) : (
        <input
          id={name}
          name={name}
          type="text"
          defaultValue={defaultValue}
          className="field-input"
        />
      )}
      {hint ? <p className="mt-1 text-xs text-ink-mute">{hint}</p> : null}
    </div>
  );
}

function Arrow({ up }: { up: boolean }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      className={`h-3.5 w-3.5 ${up ? "" : "rotate-180"}`}
    >
      <path d="M12 19V5" />
      <path d="m5 12 7-7 7 7" />
    </svg>
  );
}

function SwapButtons({
  onMove,
  position,
  count,
  what,
}: {
  onMove: (delta: -1 | 1) => void;
  position: number;
  count: number;
  what: string;
}) {
  return (
    <div className="flex flex-col gap-1.5">
      <button
        type="button"
        onClick={() => onMove(-1)}
        disabled={position <= 0}
        aria-label={`Move ${what} up`}
        title="Move up"
        className="flex h-8 w-8 items-center justify-center rounded-full border border-linen bg-white text-ink-soft transition-colors hover:border-teal hover:text-teal disabled:cursor-not-allowed disabled:opacity-35"
      >
        <Arrow up />
      </button>
      <button
        type="button"
        onClick={() => onMove(1)}
        disabled={position >= count - 1}
        aria-label={`Move ${what} down`}
        title="Move down"
        className="flex h-8 w-8 items-center justify-center rounded-full border border-linen bg-white text-ink-soft transition-colors hover:border-teal hover:text-teal disabled:cursor-not-allowed disabled:opacity-35"
      >
        <Arrow up={false} />
      </button>
    </div>
  );
}

function Group({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <fieldset className="rounded-2xl bg-mint p-5">
      <legend className="px-1 text-[0.72rem] font-bold uppercase tracking-[0.16em] text-ink-mute">
        {title}
      </legend>
      <div className="space-y-4">{children}</div>
    </fieldset>
  );
}

/** Collapsible card with a summary line so long forms stay scannable. */
function PageSection({
  title,
  badge,
  summary,
  defaultOpen = false,
  children,
}: {
  title: string;
  badge?: string;
  summary: string;
  defaultOpen?: boolean;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <section className="card-soft overflow-hidden">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        aria-expanded={open}
        className="flex w-full items-center gap-4 p-6 text-left transition-colors hover:bg-mint/50"
      >
        <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-teal-soft text-teal transition-transform duration-300">
          <Arrow up={open} />
        </span>
        <span className="min-w-0 flex-1">
          <span className="flex items-center gap-3">
            <span className="font-display text-xl font-semibold text-ink">
              {title}
            </span>
            {badge ? (
              <span className="rounded-full bg-mint px-2.5 py-0.5 text-[0.68rem] font-bold uppercase tracking-wide text-ink-mute">
                {badge}
              </span>
            ) : null}
          </span>
          <span className="mt-0.5 block truncate text-sm text-ink-mute">
            {summary}
          </span>
        </span>
      </button>
      {open ? <div className="space-y-5 border-t border-linen p-6">{children}</div> : null}
    </section>
  );
}

/* ------------------------------ nav editor ------------------------------ */

function NavEditor({ nav }: { nav: NavItemCms[] }) {
  const [rows, setRows] = useState<NavItemCms[]>(nav);

  const move = (i: number, delta: -1 | 1) => {
    const j = i + delta;
    if (j < 0 || j >= rows.length) return;
    const next = [...rows];
    [next[i], next[j]] = [next[j], next[i]];
    setRows(next);
  };

  return (
    <div className="space-y-3">
      {rows.map((row, i) => (
        <div key={i} className="flex items-center gap-3 rounded-2xl bg-mint p-4">
          <SwapButtons
            onMove={(delta) => move(i, delta)}
            position={i}
            count={rows.length}
            what="menu item"
          />
          <div className="min-w-0 flex-1 space-y-2">
            <div className="grid gap-2 sm:grid-cols-[1fr_1.4fr]">
              <div>
                <label htmlFor={`navLabel.${i}`} className="field-label">
                  Label
                </label>
                <input
                  id={`navLabel.${i}`}
                  name={`navLabel.${i}`}
                  defaultValue={row.label}
                  placeholder="Portfolio"
                  className="field-input"
                />
              </div>
              <div>
                <label htmlFor={`navHref.${i}`} className="field-label">
                  Link
                </label>
                <input
                  id={`navHref.${i}`}
                  name={`navHref.${i}`}
                  defaultValue={row.href}
                  placeholder="/portfolio"
                  className="field-input"
                />
              </div>
            </div>
          </div>
          <button
            type="button"
            onClick={() => setRows(rows.filter((_, j) => j !== i))}
            className="self-start rounded-full px-3 py-1.5 text-xs font-semibold text-coral-dark transition-colors hover:bg-coral-soft"
          >
            Remove
          </button>
        </div>
      ))}

      <button
        type="button"
        onClick={() => setRows([...rows, { label: "", href: "" }])}
        className="btn btn-outline"
      >
        Add menu item
      </button>
      <p className="text-xs text-ink-mute">
        Drives both the header and the footer menu. Use relative links like
        /services or full https:// URLs.
      </p>
    </div>
  );
}

/* --------------------------------- form ---------------------------------- */

export function PagesForm({
  pages,
  nav,
}: {
  pages: PageCopy;
  nav: SiteSettings["nav"];
}) {
  const [state, formAction, pending] = useActionState<ActionState, FormData>(
    savePagesAction,
    null,
  );

  return (
    <form action={formAction} className="space-y-6">
      {state?.error ? (
        <p
          role="alert"
          className="rounded-xl border border-coral/40 bg-coral-soft px-4 py-3 text-sm font-medium text-coral-dark"
        >
          {state.error}
        </p>
      ) : null}

      <PageSection
        title="Navigation menu"
        badge={`${nav.length} items`}
        summary={nav.map((n) => n.label).join(" · ")}
        defaultOpen
      >
        <NavEditor nav={nav} />
      </PageSection>

      <PageSection
        title="Home"
        summary={pages.home.featuredTitle}
      >
        <Group title="Featured projects section">
          <Field label="Eyebrow" name="homeFeaturedEyebrow" defaultValue={pages.home.featuredEyebrow} />
          <Field label="Title" name="homeFeaturedTitle" defaultValue={pages.home.featuredTitle} />
          <Field label="Lead" name="homeFeaturedLead" defaultValue={pages.home.featuredLead} textarea rows={2} />
        </Group>
        <p className="text-xs text-ink-mute">
          Hero, promo banner and closing CTA copy live in{" "}
          <a href="/admin/settings" className="font-semibold text-teal hover:underline">
            Site settings
          </a>
          . Testimonials are managed in{" "}
          <a href="/admin/testimonials" className="font-semibold text-teal hover:underline">
            Testimonials
          </a>
          .
        </p>
      </PageSection>

      <PageSection
        title="Services page"
        summary={pages.services.title}
      >
        <Field label="Meta description (SEO)" name="servicesMetaDescription" defaultValue={pages.services.metaDescription} textarea rows={2} />
        <Group title="Hero">
          <Field label="Eyebrow" name="servicesEyebrow" defaultValue={pages.services.eyebrow} />
          <Field label="Title" name="servicesTitle" defaultValue={pages.services.title} />
          <Field label="Lead" name="servicesLead" defaultValue={pages.services.lead} textarea rows={2} />
        </Group>
        <Group title="Process section">
          <Field label="Eyebrow" name="servicesProcessEyebrow" defaultValue={pages.services.processEyebrow} />
          <Field label="Title" name="servicesProcessTitle" defaultValue={pages.services.processTitle} />
          <Field label="Lead" name="servicesProcessLead" defaultValue={pages.services.processLead} textarea rows={2} />
        </Group>
      </PageSection>

      <PageSection
        title="Portfolio page"
        summary={pages.portfolio.title}
      >
        <Field label="Meta description (SEO)" name="portfolioMetaDescription" defaultValue={pages.portfolio.metaDescription} textarea rows={2} />
        <Group title="Hero">
          <Field label="Eyebrow" name="portfolioEyebrow" defaultValue={pages.portfolio.eyebrow} />
          <Field label="Title" name="portfolioTitle" defaultValue={pages.portfolio.title} />
          <Field label="Lead" name="portfolioLead" defaultValue={pages.portfolio.lead} textarea rows={2} />
        </Group>
      </PageSection>

      <PageSection
        title="About page"
        summary={pages.about.title}
      >
        <Field label="Meta description (SEO)" name="aboutMetaDescription" defaultValue={pages.about.metaDescription} textarea rows={2} />
        <Group title="Hero">
          <Field label="Eyebrow" name="aboutEyebrow" defaultValue={pages.about.eyebrow} />
          <Field label="Title" name="aboutTitle" defaultValue={pages.about.title} textarea rows={2} />
          <Field label="Intro paragraph 1" name="aboutIntro1" defaultValue={pages.about.intro1} textarea rows={4} />
          <Field label="Intro paragraph 2" name="aboutIntro2" defaultValue={pages.about.intro2} textarea rows={3} />
        </Group>
        <Group title="Values section">
          <Field label="Title" name="aboutValuesTitle" defaultValue={pages.about.valuesTitle} />
        </Group>
        <Group title="Founder section">
          <Field label="Name" name="aboutFounderName" defaultValue={pages.about.founderName} />
          <Field label="Role badge" name="aboutFounderRole" defaultValue={pages.about.founderRole} />
          <Field label="Quote heading" name="aboutFounderQuote" defaultValue={pages.about.founderQuote} />
          <Field label="Bio paragraph 1" name="aboutFounderBio1" defaultValue={pages.about.founderBio1} textarea rows={4} />
          <Field
            label="Bio paragraph 2 (ends with the highlighted client quote)"
            name="aboutFounderBio2"
            defaultValue={pages.about.founderBio2}
            textarea
            rows={3}
          />
        </Group>
        <Group title="Stats">
          <Field
            label="Stat lines (value | label)"
            name="aboutStats"
            defaultValue={pages.about.stats}
            textarea
            rows={5}
            hint="One per line, e.g. 120+ | projects completed"
          />
        </Group>
      </PageSection>

      <PageSection
        title="Pricing page"
        summary={pages.pricing.title}
      >
        <Field label="Meta description (SEO)" name="pricingMetaDescription" defaultValue={pages.pricing.metaDescription} textarea rows={2} />
        <Group title="Hero">
          <Field label="Eyebrow" name="pricingEyebrow" defaultValue={pages.pricing.eyebrow} />
          <Field label="Title" name="pricingTitle" defaultValue={pages.pricing.title} />
          <Field label="Lead" name="pricingLead" defaultValue={pages.pricing.lead} textarea rows={2} />
        </Group>
        <Group title="Notes under the tiers">
          <Field label="Notes (one per line)" name="pricingNotes" defaultValue={pages.pricing.notes} textarea rows={4} />
        </Group>
        <Group title="FAQ section">
          <Field label="Eyebrow" name="pricingFaqEyebrow" defaultValue={pages.pricing.faqEyebrow} />
          <Field label="Title" name="pricingFaqTitle" defaultValue={pages.pricing.faqTitle} />
          <Field label="Lead" name="pricingFaqLead" defaultValue={pages.pricing.faqLead} textarea rows={2} />
        </Group>
        <Group title="Closing CTA">
          <Field label="Heading" name="pricingCtaHeading" defaultValue={pages.pricing.ctaHeading} />
        </Group>
      </PageSection>

      <PageSection
        title="Contact page"
        summary={pages.contact.title}
      >
        <Field label="Meta description (SEO)" name="contactMetaDescription" defaultValue={pages.contact.metaDescription} textarea rows={2} />
        <Group title="Hero">
          <Field label="Title" name="contactTitle" defaultValue={pages.contact.title} />
          <Field label="Lead" name="contactLead" defaultValue={pages.contact.lead} textarea rows={3} />
        </Group>
        <Group title="Form intro">
          <Field label="Text under the form heading" name="contactFormIntro" defaultValue={pages.contact.formIntro} textarea rows={2} />
        </Group>
      </PageSection>

      <div className="sticky bottom-4 z-10">
        <button
          type="submit"
          disabled={pending}
          className="btn btn-teal w-full shadow-[0_20px_45px_-20px_rgba(14,59,59,0.6)] disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto"
        >
          {pending ? "Saving…" : "Save page content"}
        </button>
      </div>
    </form>
  );
}
