import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, ExternalLink } from "lucide-react";
import { Button } from "@/components/Button";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
  ImageUpload,
  RepeaterField,
  type RepeaterFieldDef,
  ConfirmButton,
} from "@/components/admin";
import { getProductPage } from "@/lib/product-pages/queries";
import { ICON_NAMES } from "@/lib/product-pages/icons";
import { updateProductPage, resetProductPageToDefaults } from "../actions";

export const dynamic = "force-dynamic";

const iconOptions = ICON_NAMES.map((n) => ({ value: n, label: n }));

const featureFields: RepeaterFieldDef[] = [
  { key: "title", label: "Title", type: "text", span: 2, maxLength: 200 },
  { key: "iconName", label: "Icon", type: "select", options: iconOptions, span: 1 },
  { key: "body", label: "Body", type: "textarea", rows: 3, span: 3, maxLength: 1200 },
];

const audienceFields: RepeaterFieldDef[] = [
  { key: "title", label: "Title", type: "text", span: 3, maxLength: 200 },
  { key: "body", label: "Body", type: "textarea", rows: 3, span: 3, maxLength: 1000 },
];

const faqFields: RepeaterFieldDef[] = [
  { key: "question", label: "Question", type: "text", span: 3, maxLength: 400 },
  { key: "answer", label: "Answer", type: "textarea", rows: 4, span: 3, maxLength: 2000 },
];

const accessTileFields: RepeaterFieldDef[] = [
  { key: "label", label: "Label", type: "text", span: 1, maxLength: 80 },
  { key: "href", label: "Link", type: "text", span: 2, maxLength: 300 },
  { key: "description", label: "Description", type: "text", span: 2, maxLength: 200 },
  { key: "iconName", label: "Icon", type: "select", options: iconOptions, span: 1 },
];

const customSectionTypeOptions = [
  { value: "text", label: "Text block" },
  { value: "image", label: "Image + text (two-column)" },
  { value: "video", label: "Video (YouTube / Vimeo / MP4)" },
  { value: "quote", label: "Pull quote" },
];

const videoProviderOptions = [
  { value: "youtube", label: "YouTube" },
  { value: "vimeo", label: "Vimeo" },
  { value: "mp4", label: "MP4 / HLS" },
  { value: "none", label: "(none)" },
];

const customSectionFields: RepeaterFieldDef[] = [
  { key: "type", label: "Section type", type: "select", options: customSectionTypeOptions, span: 1 },
  { key: "heading", label: "Heading", type: "text", span: 2, maxLength: 300 },
  { key: "body", label: "Body (markdown)", type: "textarea", rows: 5, span: 3, maxLength: 8000 },
  { key: "imagePath", label: "Image URL (image type only)", type: "text", span: 2, maxLength: 500 },
  { key: "imageAlt", label: "Image alt", type: "text", span: 1, maxLength: 500 },
  { key: "videoProvider", label: "Video provider (video type only)", type: "select", options: videoProviderOptions, span: 1 },
  { key: "videoUrl", label: "Video URL", type: "text", span: 2, maxLength: 600 },
  { key: "ctaLabel", label: "CTA label (optional)", type: "text", span: 1, maxLength: 80 },
  { key: "ctaHref", label: "CTA link", type: "text", span: 2, maxLength: 300 },
];

export default async function AdminProductPageEditor({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const page = await getProductPage(slug);
  if (!page) notFound();

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/product-pages"
          className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-blue)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
          All product pages
        </Link>
      </div>

      <AdminHeading
        eyebrow={`Product page · ${page.slug}`}
        title={page.heroTitle || page.slug}
        lede="Every change here republishes the matching /products/<slug> landing page."
        actions={
          <Link
            href={`/products/${page.slug}`}
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-1 rounded-md border border-[var(--color-line)] px-3 py-1.5 text-[13px] font-semibold text-[var(--color-slate)] transition-colors hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
          >
            <ExternalLink className="h-3.5 w-3.5" aria-hidden />
            View live page
          </Link>
        }
      />

      <form action={updateProductPage} className="flex flex-col gap-6">
        <input type="hidden" name="slug" value={page.slug} />

        <FormSection title="Hero" description="Top-of-page band with the headline, tagline, description, image, and primary CTAs.">
          <div className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Eyebrow badge"
              name="heroEyebrow"
              defaultValue={page.heroEyebrow}
              maxLength={120}
              placeholder="e.g. OrthoPrep · Live"
            />
            <InputField
              label="Tagline"
              name="heroTagline"
              defaultValue={page.heroTagline}
              maxLength={300}
              placeholder="e.g. 1,575 SBAs · 22 parts"
            />
            <InputField
              label="Headline"
              name="heroTitle"
              defaultValue={page.heroTitle}
              maxLength={200}
              required
              wrapClassName="md:col-span-2"
            />
            <TextareaField
              label="Description"
              name="heroDescription"
              defaultValue={page.heroDescription}
              rows={4}
              maxLength={2000}
              wrapClassName="md:col-span-2"
            />
            <div className="md:col-span-2">
              <ImageUpload
                name="heroImagePath"
                altName="heroImageAlt"
                folder="product-pages"
                label="Hero image"
                defaultValue={page.heroImagePath}
                defaultAlt={page.heroImageAlt}
              />
            </div>
            <InputField
              label="Primary CTA label"
              name="heroPrimaryCtaLabel"
              defaultValue={page.heroPrimaryCtaLabel}
              maxLength={80}
            />
            <InputField
              label="Primary CTA link"
              name="heroPrimaryCtaHref"
              defaultValue={page.heroPrimaryCtaHref}
              maxLength={300}
              placeholder="/join or external URL"
            />
            <InputField
              label="Secondary CTA label"
              name="heroSecondaryCtaLabel"
              defaultValue={page.heroSecondaryCtaLabel}
              maxLength={80}
            />
            <InputField
              label="Secondary CTA link"
              name="heroSecondaryCtaHref"
              defaultValue={page.heroSecondaryCtaHref}
              maxLength={300}
            />
          </div>
        </FormSection>

        <FormSection title="Access rail" description="The sticky strip above the hero. Members see quick-access tiles; guests see a sign-in prompt.">
          <div className="grid gap-4">
            <TextareaField
              label="Guest tagline"
              name="accessRailTagline"
              defaultValue={page.accessRailTagline}
              rows={2}
              maxLength={500}
              hint="Shown in the guest strip — one line explaining what members unlock."
            />
            <label className="flex items-center gap-2.5 text-[13px]">
              <input
                type="checkbox"
                name="accessRailMembersOnly"
                defaultChecked={page.accessRailMembersOnly}
                className="h-4 w-4 rounded border-[var(--color-line)] text-[var(--color-blue)]"
              />
              <span className="font-semibold text-[var(--color-ink)]">
                Members-only product (hides tiles from guests)
              </span>
            </label>
            <RepeaterField
              name="accessTiles"
              label="Quick-access tiles"
              hint="Shown to signed-in members above the hero. 2–4 items works best."
              fields={accessTileFields}
              defaultValue={page.accessTiles as unknown as Array<Record<string, string>>}
              addLabel="Add tile"
              emptyRow={{ label: "", href: "", description: "", iconName: "CheckCircle2" }}
              max={6}
            />
          </div>
        </FormSection>

        <FormSection title="Main section" description="The first content block after the hero — section heading, supporting copy, and the wide showcase image.">
          <div className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Section eyebrow"
              name="sectionEyebrow"
              defaultValue={page.sectionEyebrow}
              maxLength={200}
            />
            <InputField
              label="Section heading"
              name="sectionHeading"
              defaultValue={page.sectionHeading}
              maxLength={500}
              wrapClassName="md:col-span-1"
            />
            <TextareaField
              label="Section body"
              name="sectionBody"
              defaultValue={page.sectionBody}
              rows={4}
              maxLength={3000}
              wrapClassName="md:col-span-2"
            />
            <div className="md:col-span-2">
              <ImageUpload
                name="showcaseImagePath"
                altName="showcaseImageAlt"
                folder="product-pages"
                label="Showcase image (16:9)"
                defaultValue={page.showcaseImagePath}
                defaultAlt={page.showcaseImageAlt}
              />
            </div>
            <InputField
              label="Showcase eyebrow"
              name="showcaseEyebrow"
              defaultValue={page.showcaseEyebrow}
              maxLength={200}
            />
            <InputField
              label="Showcase caption"
              name="showcaseCaption"
              defaultValue={page.showcaseCaption}
              maxLength={500}
            />
          </div>
        </FormSection>

        <FormSection title="Feature tiles" description="The three-column grid of features under the showcase image. 3–9 items.">
          <RepeaterField
            name="features"
            label="Features"
            fields={featureFields}
            defaultValue={page.features as unknown as Array<Record<string, string>>}
            addLabel="Add feature"
            emptyRow={{ title: "", body: "", iconName: "CheckCircle2" }}
            max={12}
          />
        </FormSection>

        <FormSection title="Audience cards" description='The "Who it\u2019s for" section. 2\u20134 cards.'>
          <div className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Audience heading"
              name="audienceHeading"
              defaultValue={page.audienceHeading}
              maxLength={500}
              wrapClassName="md:col-span-2"
            />
            <TextareaField
              label="Audience supporting copy"
              name="audienceBody"
              defaultValue={page.audienceBody}
              rows={3}
              maxLength={2000}
              wrapClassName="md:col-span-2"
            />
            <div className="md:col-span-2">
              <RepeaterField
                name="audiences"
                label="Audience cards"
                fields={audienceFields}
                defaultValue={page.audiences as unknown as Array<Record<string, string>>}
                addLabel="Add audience"
                emptyRow={{ title: "", body: "" }}
                max={6}
              />
            </div>
          </div>
        </FormSection>

        <FormSection title="FAQs" description="Accordion of frequently asked questions. Leave empty to hide the section.">
          <RepeaterField
            name="faqs"
            label="Questions & answers"
            fields={faqFields}
            defaultValue={page.faqs as unknown as Array<Record<string, string>>}
            addLabel="Add FAQ"
            emptyRow={{ question: "", answer: "" }}
            max={20}
          />
        </FormSection>

        <FormSection
          title="Custom content blocks"
          description="Free-form sections rendered between the main block and the audience strip. Add as many as you like — text, image, video, or pull quote."
        >
          <RepeaterField
            name="customSections"
            label="Sections"
            hint="Each block has its own heading, body (markdown), and optional image/video/CTA. Re-order with the up/down arrows."
            fields={customSectionFields}
            defaultValue={
              ((page.customSections ?? []) as unknown) as Array<Record<string, string>>
            }
            addLabel="Add content block"
            emptyRow={{
              type: "text",
              heading: "",
              body: "",
              imagePath: "",
              imageAlt: "",
              videoUrl: "",
              videoProvider: "youtube",
              ctaLabel: "",
              ctaHref: "",
            }}
            max={12}
          />
        </FormSection>

        <FormSection title="Final CTA" description="The blue band at the bottom of the page.">
          <div className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Title"
              name="ctaTitle"
              defaultValue={page.ctaTitle}
              maxLength={300}
              wrapClassName="md:col-span-2"
            />
            <TextareaField
              label="Body"
              name="ctaBody"
              defaultValue={page.ctaBody}
              rows={3}
              maxLength={1500}
              wrapClassName="md:col-span-2"
            />
            <InputField
              label="Primary CTA label"
              name="ctaPrimaryLabel"
              defaultValue={page.ctaPrimaryLabel}
              maxLength={80}
            />
            <InputField
              label="Primary CTA link"
              name="ctaPrimaryHref"
              defaultValue={page.ctaPrimaryHref}
              maxLength={300}
            />
            <InputField
              label="Secondary CTA label"
              name="ctaSecondaryLabel"
              defaultValue={page.ctaSecondaryLabel}
              maxLength={80}
            />
            <InputField
              label="Secondary CTA link"
              name="ctaSecondaryHref"
              defaultValue={page.ctaSecondaryHref}
              maxLength={300}
            />
          </div>
        </FormSection>

        <div className="sticky bottom-4 z-10 flex items-center justify-between rounded-xl border border-[var(--color-line)] bg-white p-4 shadow-md">
          <p className="text-[13px] text-[var(--color-slate)]">
            Changes publish immediately to{" "}
            <code className="font-mono text-[var(--color-ink)]">/products/{page.slug}</code>.
          </p>
          <Button type="submit" variant="primary" className="!px-5 !py-2.5 !text-[13px]">
            Save product page
          </Button>
        </div>
      </form>

      <FormSection
        title="Danger zone"
        description="Restore this product page to the source-code defaults. Your custom edits will be overwritten."
        tone="danger"
        className="mt-6"
      >
        <form action={resetProductPageToDefaults}>
          <input type="hidden" name="slug" value={page.slug} />
          <ConfirmButton
            label="Reset to defaults"
            confirmLabel="Click again to overwrite edits"
            tone="danger"
          />
        </form>
      </FormSection>
    </>
  );
}
