"use client";

import { useEffect, useId, useState, type ReactNode } from "react";
import {
  ANIMATION_TYPES, BG_PATTERNS, BG_TYPES, BORDER_SIDES, BORDER_STYLES, GRADIENT_DIRECTIONS,
  sectionAnimationSchema, sectionBackgroundSchema, sectionBorderSchema,
  type Section, type SectionAnimation, type SectionBackground, type SectionBorder,
} from "@/lib/blocks/layout";
import { PALETTE_KEYS } from "@/lib/site-settings";
import { sitePaletteAction } from "@/lib/actions/pages";
import { EdField, Switch, edInput } from "./ed-ui";
import { MediaPicker } from "./media-picker";

const COLOUR_NAMES: Record<string, string> = { one: "Colour One", two: "Colour Two", three: "Colour Three", four: "Colour Four", five: "Colour Five", six: "Colour Six", seven: "Colour Seven", eight: "Colour Eight", muted: "Muted" };
const TYPE_LABELS: Record<SectionBackground["type"], string> = { colour: "Colour", gradient: "Gradient", image: "Image", video: "Video", pattern: "Pattern" };
const PATTERN_LABELS: Record<SectionBackground["pattern"], string> = { dots: "Dots", grid: "Grid", stripes: "Stripes", diagonal: "Diagonal lines", checks: "Checks" };
const DIRECTION_LABELS: Record<string, string> = { "to bottom": "Top to bottom", "to top": "Bottom to top", "to right": "Left to right", "to left": "Right to left", "to bottom right": "Diagonal ↘", "to bottom left": "Diagonal ↙" };
const SIDE_LABELS: Record<SectionBorder["sides"], string> = { all: "All sides", top: "Top only", bottom: "Bottom only", topBottom: "Top and bottom" };
const ANIM_LABELS: Record<SectionAnimation["type"], string> = { fade: "Fade in", slideUp: "Slide up", slideLeft: "Slide in from right", slideRight: "Slide in from left", zoom: "Zoom in" };

function Heading({ children }: { children: ReactNode }) {
  return <h3 className="border-b border-[var(--ed-line)] pb-2 text-sm font-bold text-[var(--ed-ink)]">{children}</h3>;
}

function ColourSelect({ id, label, value, palette, disabled, onChange }: { id: string; label: string; value: string; palette: Record<string, string> | null; disabled: boolean; onChange: (v: SectionBackground["colour"]) => void }) {
  return (
    <EdField id={id} label={label}>
      <div className="relative">
        <span className="pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 rounded-sm ring-1 ring-black/20" style={{ background: palette?.[value] ?? "transparent" }} aria-hidden />
        <select id={id} className={`${edInput} pl-9`} disabled={disabled} value={value} onChange={(e) => onChange(e.target.value as SectionBackground["colour"])}>
          {PALETTE_KEYS.map((k) => <option key={k} value={k}>{COLOUR_NAMES[k]}</option>)}
        </select>
      </div>
    </EdField>
  );
}

function Num({ id, label, value, min, max, step = 1, suffix, disabled, onChange }: { id: string; label: string; value: number; min: number; max: number; step?: number; suffix: string; disabled: boolean; onChange: (v: number) => void }) {
  return (
    <EdField id={id} label={`${label} (${suffix})`}>
      <input id={id} type="number" className={edInput} disabled={disabled} min={min} max={max} step={step} value={value} onChange={(e) => { const n = Number(e.target.value); if (Number.isFinite(n)) onChange(Math.min(max, Math.max(min, Math.round(n)))); }} />
    </EdField>
  );
}

/** Background, Borders and Animations for a section (Section Options → Settings). */
export function SectionStyleFields({ section, siteId, disabled, errors, onPatch }: { section: Section; siteId: string; disabled: boolean; errors: Record<string, string>; onPatch: (p: Partial<Section>) => void }) {
  const idp = useId();
  const [palette, setPalette] = useState<Record<string, string> | null>(null);
  useEffect(() => {
    let live = true;
    void sitePaletteAction(siteId).then((r) => { if (live && r.ok && r.data) setPalette(r.data); });
    return () => { live = false; };
  }, [siteId]);

  const bg = section.background;
  const setBg = (p: Partial<SectionBackground>) => bg && onPatch({ background: { ...bg, ...p } });
  const bd = section.border;
  const setBd = (p: Partial<SectionBorder>) => bd && onPatch({ border: { ...bd, ...p } });
  const an = section.animation;
  const setAn = (p: Partial<SectionAnimation>) => an && onPatch({ animation: { ...an, ...p } });
  const usesColour = bg && (bg.type === "colour" || bg.type === "gradient" || bg.type === "pattern");

  return (
    <div className="space-y-6 pt-2">
      <section className="space-y-4" aria-label="Background">
        <Heading>Background</Heading>
        <Switch label="Section background" checked={Boolean(bg)} disabled={disabled} onChange={(v) => onPatch({ background: v ? sectionBackgroundSchema.parse({ colour: "four" }) : null })} />
        {bg ? (
          <div className="space-y-4">
            <EdField id={`${idp}-bgtype`} label="Type">
              <select id={`${idp}-bgtype`} className={edInput} disabled={disabled} value={bg.type} onChange={(e) => setBg({ type: e.target.value as SectionBackground["type"] })}>
                {BG_TYPES.map((t) => <option key={t} value={t}>{TYPE_LABELS[t]}</option>)}
              </select>
            </EdField>
            {usesColour || bg.type === "image" || bg.type === "video" ? (
              <ColourSelect id={`${idp}-c1`} label={bg.type === "gradient" ? "From colour" : bg.type === "pattern" ? "Base colour" : bg.type === "colour" ? "Colour" : "Fallback colour"} value={bg.colour} palette={palette} disabled={disabled} onChange={(v) => setBg({ colour: v })} />
            ) : null}
            {bg.type === "gradient" ? (
              <>
                <ColourSelect id={`${idp}-c2`} label="To colour" value={bg.colour2} palette={palette} disabled={disabled} onChange={(v) => setBg({ colour2: v })} />
                <EdField id={`${idp}-dir`} label="Direction">
                  <select id={`${idp}-dir`} className={edInput} disabled={disabled} value={bg.direction} onChange={(e) => setBg({ direction: e.target.value as SectionBackground["direction"] })}>
                    {GRADIENT_DIRECTIONS.map((d) => <option key={d} value={d}>{DIRECTION_LABELS[d]}</option>)}
                  </select>
                </EdField>
              </>
            ) : null}
            {bg.type === "pattern" ? (
              <>
                <EdField id={`${idp}-pat`} label="Pattern">
                  <select id={`${idp}-pat`} className={edInput} disabled={disabled} value={bg.pattern} onChange={(e) => setBg({ pattern: e.target.value as SectionBackground["pattern"] })}>
                    {BG_PATTERNS.map((p) => <option key={p} value={p}>{PATTERN_LABELS[p]}</option>)}
                  </select>
                </EdField>
                <ColourSelect id={`${idp}-c2`} label="Pattern colour" value={bg.colour2} palette={palette} disabled={disabled} onChange={(v) => setBg({ colour2: v })} />
              </>
            ) : null}
            {bg.type === "image" ? (
              <>
                <div className="space-y-1">
                  <span className="block text-xs font-bold text-[var(--ed-ink)]">Image</span>
                  <MediaPicker siteId={siteId} label="background image" value={bg.imageId} onChange={(v) => setBg({ imageId: v })} disabled={disabled} />
                </div>
                <label className="flex items-center gap-2 text-sm text-[var(--ed-ink)]"><input type="checkbox" disabled={disabled} checked={bg.fixed} onChange={(e) => setBg({ fixed: e.target.checked })} />Keep the image still while scrolling</label>
              </>
            ) : null}
            {bg.type === "video" ? (
              <EdField id={`${idp}-vid`} label="Video link (.mp4 or .webm)" hint="A direct https link. The video plays muted and on a loop." error={errors["background.videoUrl"]}>
                <input id={`${idp}-vid`} className={edInput} disabled={disabled} inputMode="url" placeholder="https://example.com/background.mp4" value={bg.videoUrl} onChange={(e) => setBg({ videoUrl: e.target.value })} />
              </EdField>
            ) : null}
            {bg.type === "image" || bg.type === "video" ? (
              <Num id={`${idp}-ov`} label="Dark overlay" suffix="%, 0–90" min={0} max={90} step={5} value={bg.overlay} disabled={disabled} onChange={(v) => setBg({ overlay: v })} />
            ) : null}
          </div>
        ) : null}
      </section>

      <section className="space-y-4" aria-label="Borders">
        <Heading>Borders</Heading>
        <Switch label="Section border" checked={Boolean(bd)} disabled={disabled} onChange={(v) => onPatch({ border: v ? sectionBorderSchema.parse({}) : null })} />
        {bd ? (
          <div className="space-y-4">
            <EdField id={`${idp}-bds`} label="Sides">
              <select id={`${idp}-bds`} className={edInput} disabled={disabled} value={bd.sides} onChange={(e) => setBd({ sides: e.target.value as SectionBorder["sides"] })}>
                {BORDER_SIDES.map((s) => <option key={s} value={s}>{SIDE_LABELS[s]}</option>)}
              </select>
            </EdField>
            <EdField id={`${idp}-bdst`} label="Line style">
              <select id={`${idp}-bdst`} className={edInput} disabled={disabled} value={bd.style} onChange={(e) => setBd({ style: e.target.value as SectionBorder["style"] })}>
                {BORDER_STYLES.map((s) => <option key={s} value={s}>{s[0]?.toUpperCase()}{s.slice(1)}</option>)}
              </select>
            </EdField>
            <ColourSelect id={`${idp}-bdc`} label="Colour" value={bd.colour} palette={palette} disabled={disabled} onChange={(v) => setBd({ colour: v })} />
            <Num id={`${idp}-bdw`} label="Thickness" suffix="px, 1–8" min={1} max={8} value={bd.width} disabled={disabled} onChange={(v) => setBd({ width: v })} />
            <Num id={`${idp}-bdr`} label="Rounded corners" suffix="px, 0–40" min={0} max={40} value={bd.radius} disabled={disabled} onChange={(v) => setBd({ radius: v })} />
          </div>
        ) : null}
      </section>

      <section className="space-y-4" aria-label="Animations">
        <Heading>Animations</Heading>
        <Switch label="Section animation" checked={Boolean(an)} disabled={disabled} onChange={(v) => onPatch({ animation: v ? sectionAnimationSchema.parse({}) : null })} />
        {an ? (
          <div className="space-y-4">
            <EdField id={`${idp}-an`} label="Effect" hint="Plays once when the section scrolls into view. Visitors who prefer reduced motion see no animation.">
              <select id={`${idp}-an`} className={edInput} disabled={disabled} value={an.type} onChange={(e) => setAn({ type: e.target.value as SectionAnimation["type"] })}>
                {ANIMATION_TYPES.map((t) => <option key={t} value={t}>{ANIM_LABELS[t]}</option>)}
              </select>
            </EdField>
            <Num id={`${idp}-and`} label="Speed" suffix="ms, 200–2000" min={200} max={2000} step={100} value={an.duration} disabled={disabled} onChange={(v) => setAn({ duration: v })} />
            <Num id={`${idp}-anl`} label="Delay" suffix="ms, 0–2000" min={0} max={2000} step={100} value={an.delay} disabled={disabled} onChange={(v) => setAn({ delay: v })} />
          </div>
        ) : null}
      </section>
    </div>
  );
}
