"use client";

import { useActionState, useState } from "react";
import { resetThemeAction, saveThemeAction } from "@/app/admin/actions";
import type { ActionState } from "@/lib/form";
import {
  PALETTE_TOKENS,
  type ThemeSettings,
  type TypographyRole,
} from "@/lib/theme";

const FONT_OPTIONS: { value: string; label: string }[] = [
  { value: "inter", label: "Inter (sans)" },
  { value: "playfair", label: "Playfair Display (serif)" },
  { value: "system-sans", label: "System sans" },
  { value: "system-serif", label: "System serif" },
  { value: "georgia", label: "Georgia" },
];

const TYPOGRAPHY_ROLES: { role: TypographyRole; label: string }[] = [
  { role: "body", label: "Body text" },
  { role: "h1", label: "Heading 1" },
  { role: "h2", label: "Heading 2" },
  { role: "h3", label: "Heading 3" },
  { role: "h4", label: "Heading 4" },
  { role: "h5", label: "Heading 5" },
  { role: "h6", label: "Heading 6" },
  { role: "nav", label: "Nav links" },
  { role: "button", label: "Buttons" },
];

/** Color picker + hex input kept in sync; the text input carries the value. */
function ColorField({
  label,
  name,
  defaultValue,
  hint,
  allowEmpty = false,
}: {
  label: string;
  name: string;
  defaultValue: string;
  hint?: string;
  allowEmpty?: boolean;
}) {
  const [value, setValue] = useState(defaultValue);
  return (
    <div>
      <label htmlFor={name} className="field-label">
        {label}
      </label>
      <div className="flex items-center gap-2">
        <input
          type="color"
          aria-label={`${label} — pick a color`}
          value={/^#[0-9a-f]{6}$/i.test(value) ? value : "#000000"}
          onChange={(e) => setValue(e.target.value)}
          className="h-10 w-12 shrink-0 cursor-pointer rounded-lg border border-ink/15 bg-white p-1"
        />
        <input
          id={name}
          name={name}
          type="text"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          placeholder={allowEmpty ? "default" : "#000000"}
          className="field-input font-mono text-xs"
        />
      </div>
      {hint ? <p className="mt-1 text-xs text-ink-mute">{hint}</p> : null}
    </div>
  );
}

export function ThemeForm({ theme }: { theme: ThemeSettings }) {
  const [state, formAction, pending] = useActionState<ActionState, FormData>(
    saveThemeAction,
    null,
  );
  const published = theme.published;

  return (
    <div 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}

      <form action={formAction} className="space-y-6">
        {/* ------------------------------ Palette ------------------------------ */}
        <section className="card-soft space-y-5 p-7">
          <div>
            <h2 className="display-3">Palette</h2>
            <p className="mt-1 text-sm text-ink-soft">
              These feed the site-wide CSS tokens — buttons, links, headings
              and backgrounds all follow. Derived shades (hover colors, soft
              tints) are recalculated automatically.
            </p>
          </div>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {PALETTE_TOKENS.map((token) => (
              <ColorField
                key={token.key}
                label={token.label}
                name={`style.colors.${token.key}`}
                defaultValue={published.colors[token.key] ?? ""}
              />
            ))}
          </div>
        </section>

        {/* ----------------------------- Typography ----------------------------- */}
        <section className="card-soft space-y-5 p-7">
          <div>
            <h2 className="display-3">Typography</h2>
            <p className="mt-1 text-sm text-ink-soft">
              Sizes accept any CSS value (px, rem, clamp()). Line height is a
              unitless number; letter spacing takes a CSS value (use 0 for
              none).
            </p>
          </div>
          <div className="grid gap-5 xl:grid-cols-2">
            {TYPOGRAPHY_ROLES.map(({ role, label }) => {
              const t = published.typography[role];
              return (
                <fieldset
                  key={role}
                  className="rounded-2xl border border-ink/10 p-4"
                >
                  <legend className="px-2 text-xs font-bold uppercase tracking-[0.14em] text-ink-soft">
                    {label}
                  </legend>
                  <div className="grid grid-cols-2 gap-3">
                    <div className="col-span-2">
                      <label
                        htmlFor={`style.typography.${role}.font`}
                        className="field-label"
                      >
                        Font
                      </label>
                      <select
                        id={`style.typography.${role}.font`}
                        name={`style.typography.${role}.font`}
                        defaultValue={t?.font ?? "inter"}
                        className="field-input"
                      >
                        {FONT_OPTIONS.map((f) => (
                          <option key={f.value} value={f.value}>
                            {f.label}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label
                        htmlFor={`style.typography.${role}.size`}
                        className="field-label"
                      >
                        Size
                      </label>
                      <input
                        id={`style.typography.${role}.size`}
                        name={`style.typography.${role}.size`}
                        type="text"
                        defaultValue={t?.size ?? ""}
                        placeholder="1rem"
                        className="field-input"
                      />
                    </div>
                    <div>
                      <label
                        htmlFor={`style.typography.${role}.weight`}
                        className="field-label"
                      >
                        Weight
                      </label>
                      <input
                        id={`style.typography.${role}.weight`}
                        name={`style.typography.${role}.weight`}
                        type="number"
                        min={100}
                        max={900}
                        step={100}
                        defaultValue={t?.weight ?? 400}
                        className="field-input"
                      />
                    </div>
                    <div>
                      <label
                        htmlFor={`style.typography.${role}.lineHeight`}
                        className="field-label"
                      >
                        Line height
                      </label>
                      <input
                        id={`style.typography.${role}.lineHeight`}
                        name={`style.typography.${role}.lineHeight`}
                        type="text"
                        defaultValue={t?.lineHeight ?? ""}
                        placeholder="1.5"
                        className="field-input"
                      />
                    </div>
                    <div>
                      <label
                        htmlFor={`style.typography.${role}.letterSpacing`}
                        className="field-label"
                      >
                        Letter spacing
                      </label>
                      <input
                        id={`style.typography.${role}.letterSpacing`}
                        name={`style.typography.${role}.letterSpacing`}
                        type="text"
                        defaultValue={t?.letterSpacing ?? "0"}
                        placeholder="0"
                        className="field-input"
                      />
                    </div>
                  </div>
                </fieldset>
              );
            })}
          </div>
        </section>

        {/* ------------------------------- Header ------------------------------- */}
        <section className="card-soft space-y-5 p-7">
          <div>
            <h2 className="display-3">Header</h2>
            <p className="mt-1 text-sm text-ink-soft">
              Leave a color empty to keep the built-in look — a transparent
              bar over the page that turns white on scroll.
            </p>
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <ColorField
              label="Background"
              name="style.header.background"
              defaultValue={published.header.background}
              hint="Empty = transparent / white-on-scroll"
              allowEmpty
            />
            <ColorField
              label="Nav link color"
              name="style.header.textColor"
              defaultValue={published.header.textColor}
              allowEmpty
            />
            <ColorField
              label="Active link color"
              name="style.header.activeColor"
              defaultValue={published.header.activeColor}
              allowEmpty
            />
            <ColorField
              label="Hover link color"
              name="style.header.hoverColor"
              defaultValue={published.header.hoverColor}
              allowEmpty
            />
            <div>
              <label htmlFor="style.header.height" className="field-label">
                Bar height
              </label>
              <input
                id="style.header.height"
                name="style.header.height"
                type="text"
                defaultValue={published.header.height}
                placeholder="4.5rem"
                className="field-input"
              />
            </div>
            <div className="flex items-end pb-1">
              <label className="flex cursor-pointer items-center gap-3 text-sm font-medium text-ink">
                <input
                  type="checkbox"
                  name="style.header.sticky"
                  defaultChecked={published.header.sticky}
                  className="h-4 w-4 accent-teal"
                />
                Sticky header
              </label>
            </div>
          </div>
        </section>

        {/* ------------------------------- Footer ------------------------------- */}
        <section className="card-soft space-y-5 p-7">
          <div>
            <h2 className="display-3">Footer</h2>
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <ColorField
              label="Background"
              name="style.footer.background"
              defaultValue={published.footer.background}
              hint="Empty = deep teal"
              allowEmpty
            />
            <ColorField
              label="Text color"
              name="style.footer.textColor"
              defaultValue={published.footer.textColor}
              allowEmpty
            />
          </div>
        </section>

        {/* ------------------------------- Actions ------------------------------ */}
        <div className="flex flex-wrap items-center gap-4">
          <button
            type="submit"
            disabled={pending}
            className="btn btn-primary disabled:cursor-not-allowed disabled:opacity-60"
          >
            {pending ? "Saving…" : "Save theme"}
          </button>
        </div>
      </form>

      <form action={resetThemeAction}>
        <button
          type="submit"
          className="btn btn-outline"
          disabled={pending}
        >
          Restore defaults
        </button>
      </form>
    </div>
  );
}
