"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { buttonClass } from "@/components/ui";
import ImageUploader from "@/components/image-uploader";

export interface VariantRow {
  id?: string;
  label: string;
  priceKes: string; // blank = product price
  stock: string;
}

export interface ProductFormValues {
  name: string;
  description: string;
  imageUrl: string;
  // Extra photos (up to 7 more) shown as a gallery on the shop.
  extraImages: string[];
  priceKes: string;
  // Optional "was" price for a sale (shown struck through).
  compareAtKes: string;
  eventId: string;
  active: boolean;
  variants: VariantRow[];
}

// One-click starting points for the usual event merch. Only the name and the
// size/colour options are filled in -- prices and stock are the organizer's.
const SIZES = ["S", "M", "L", "XL", "XXL"];
const TEMPLATES: { label: string; name: string; options: string[] }[] = [
  { label: "T-shirt", name: "T-shirt", options: SIZES },
  { label: "Hoodie", name: "Hoodie", options: SIZES },
  { label: "Cap", name: "Cap", options: ["One size"] },
  { label: "Cup", name: "Cup", options: ["Standard"] },
  { label: "Leso", name: "Leso", options: ["One size"] },
];

export default function ProductForm({
  productId,
  initial,
  events,
}: {
  productId: string | null;
  initial: ProductFormValues;
  events: { id: string; title: string }[];
}) {
  const router = useRouter();
  const [form, setForm] = useState(initial);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  function applyTemplate(t: (typeof TEMPLATES)[number]) {
    setForm((f) => ({
      ...f,
      name: f.name.trim() ? f.name : t.name,
      variants: t.options.map((label) => ({ label, priceKes: "", stock: "0" })),
    }));
  }

  const setVariant = (i: number, patch: Partial<VariantRow>) =>
    setForm((f) => ({ ...f, variants: f.variants.map((v, idx) => (idx === i ? { ...v, ...patch } : v)) }));

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    const price = Number(form.priceKes);
    if (Number.isNaN(price) || price < 0) return setError("Enter a valid price");
    const compareAt = form.compareAtKes.trim() === "" ? null : Number(form.compareAtKes);
    if (compareAt !== null && (Number.isNaN(compareAt) || compareAt <= price)) {
      return setError("The “was” price must be higher than the price (or leave it blank)");
    }
    const variants = form.variants.map((v) => ({
      id: v.id,
      label: v.label.trim(),
      priceCents: v.priceKes.trim() === "" ? null : Math.round(Number(v.priceKes) * 100),
      stock: Math.floor(Number(v.stock) || 0),
    }));
    if (variants.some((v) => !v.label)) return setError("Every option needs a name, e.g. “M / Black”");
    if (variants.some((v) => v.priceCents !== null && (Number.isNaN(v.priceCents) || v.priceCents < 0))) {
      return setError("Option prices must be valid amounts");
    }
    if (variants.some((v) => v.stock < 0)) return setError("Stock can't be negative");

    setLoading(true);
    const res = await fetch(productId ? `/api/dashboard/merch/products/${productId}` : "/api/dashboard/merch/products", {
      method: productId ? "PUT" : "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name: form.name,
        description: form.description || null,
        imageUrl: form.imageUrl || form.extraImages.find(Boolean) || null,
        imageUrls: form.extraImages.filter((u) => u && u !== form.imageUrl),
        priceCents: Math.round(price * 100),
        compareAtCents: compareAt === null ? null : Math.round(compareAt * 100),
        eventId: form.eventId || null,
        active: form.active,
        variants,
      }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      setError(data.error ?? "Could not save product");
      setLoading(false);
      return;
    }
    router.push("/dashboard/merch");
    router.refresh();
  }

  async function remove() {
    if (!productId || !confirm("Delete this product? Past orders keep their receipt lines.")) return;
    setLoading(true);
    const res = await fetch(`/api/dashboard/merch/products/${productId}`, { method: "DELETE" });
    if (!res.ok) {
      setError("Could not delete product");
      setLoading(false);
      return;
    }
    router.push("/dashboard/merch");
    router.refresh();
  }

  return (
    <form onSubmit={submit} className="space-y-4">
      {!productId && (
        <div>
          <p className="mb-1 text-sm font-medium text-be-text">Start from a template</p>
          <div className="flex flex-wrap gap-2">
            {TEMPLATES.map((t) => (
              <button key={t.label} type="button" onClick={() => applyTemplate(t)} className={buttonClass("secondary")}>
                {t.label}
              </button>
            ))}
          </div>
          <p className="mt-1 text-xs text-be-muted">Fills in the name and sizes — you set the price and stock.</p>
        </div>
      )}

      <Field label="Product name">
        <input
          required
          value={form.name}
          onChange={(e) => setForm({ ...form, name: e.target.value })}
          placeholder="e.g. Vulai Festival Tee"
          className="input"
        />
      </Field>

      <Field label="Description" hint="Optional">
        <textarea
          rows={3}
          value={form.description}
          onChange={(e) => setForm({ ...form, description: e.target.value })}
          className="input"
        />
      </Field>

      <ImageUploader label="Main photo" folder="merch" value={form.imageUrl} onChange={(u) => setForm({ ...form, imageUrl: u })} />

      <div className="space-y-2">
        <p className="text-sm font-medium text-be-text">
          More photos <span className="font-normal text-be-muted">— optional, up to 7 (back, close-ups, model shots)</span>
        </p>
        {form.extraImages.map((u, i) => (
          <div key={i} className="flex items-start gap-2">
            <div className="flex-1">
              <ImageUploader
                label={`Photo ${i + 2}`}
                folder="merch"
                value={u}
                onChange={(url) =>
                  setForm((f) => ({ ...f, extraImages: f.extraImages.map((x, j) => (j === i ? url : x)) }))
                }
              />
            </div>
            <button
              type="button"
              onClick={() => setForm((f) => ({ ...f, extraImages: f.extraImages.filter((_, j) => j !== i) }))}
              className={buttonClass("ghost")}
            >
              Remove
            </button>
          </div>
        ))}
        {form.extraImages.length < 7 && (
          <button
            type="button"
            onClick={() => setForm((f) => ({ ...f, extraImages: [...f.extraImages, ""] }))}
            className={buttonClass("secondary")}
          >
            + Add another photo
          </button>
        )}
      </div>

      <div className="grid grid-cols-2 gap-3">
        <Field label="Price (KES)">
          <input
            required
            type="number"
            min="0"
            step="1"
            value={form.priceKes}
            onChange={(e) => setForm({ ...form, priceKes: e.target.value })}
            className="input"
          />
        </Field>
        <Field label="Was (KES)" hint="Optional — shows a sale">
          <input
            type="number"
            min="0"
            step="1"
            value={form.compareAtKes}
            onChange={(e) => setForm({ ...form, compareAtKes: e.target.value })}
            placeholder="e.g. 1500"
            className="input"
          />
        </Field>
      </div>

      <div className="grid grid-cols-1 gap-3">
        <Field label="Promotes event" hint="Optional">
          <select value={form.eventId} onChange={(e) => setForm({ ...form, eventId: e.target.value })} className="input">
            <option value="">None</option>
            {events.map((ev) => (
              <option key={ev.id} value={ev.id}>
                {ev.title}
              </option>
            ))}
          </select>
        </Field>
      </div>

      <fieldset className="space-y-3 rounded-lg border border-be-border p-4">
        <legend className="px-1 text-sm font-medium text-be-text">Options &amp; stock</legend>
        <p className="text-xs text-be-muted">
          One row per size/colour you stock (e.g. “M / Black”). Leave the price blank to use the product price.
        </p>
        {form.variants.map((v, i) => (
          <div key={v.id ?? i} className="grid grid-cols-[1fr_6rem_5rem_auto] items-end gap-2">
            <Field label={i === 0 ? "Option" : ""}>
              <input
                value={v.label}
                onChange={(e) => setVariant(i, { label: e.target.value })}
                placeholder="Standard"
                className="input"
              />
            </Field>
            <Field label={i === 0 ? "Price" : ""}>
              <input
                type="number"
                min="0"
                step="1"
                value={v.priceKes}
                onChange={(e) => setVariant(i, { priceKes: e.target.value })}
                placeholder="—"
                className="input"
              />
            </Field>
            <Field label={i === 0 ? "Stock" : ""}>
              <input
                type="number"
                min="0"
                step="1"
                value={v.stock}
                onChange={(e) => setVariant(i, { stock: e.target.value })}
                className="input"
              />
            </Field>
            <button
              type="button"
              disabled={form.variants.length === 1}
              onClick={() => setForm({ ...form, variants: form.variants.filter((_, idx) => idx !== i) })}
              className={buttonClass("ghost", "px-2")}
              aria-label="Remove option"
            >
              ✕
            </button>
          </div>
        ))}
        <button
          type="button"
          onClick={() => setForm({ ...form, variants: [...form.variants, { label: "", priceKes: "", stock: "0" }] })}
          className={buttonClass("secondary")}
        >
          + Add option
        </button>
      </fieldset>

      <label className="flex items-center gap-2 text-sm text-be-text">
        <input type="checkbox" checked={form.active} onChange={(e) => setForm({ ...form, active: e.target.checked })} />
        Visible in the shop
      </label>

      {error && <p className="text-sm text-red-600">{error}</p>}

      <div className="flex gap-2">
        <button type="submit" disabled={loading} className={buttonClass("primary")}>
          {loading ? "Saving…" : productId ? "Save product" : "Create product"}
        </button>
        {productId && (
          <button type="button" disabled={loading} onClick={remove} className={buttonClass("danger")}>
            Delete
          </button>
        )}
      </div>
    </form>
  );
}

function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="mb-1 block min-h-5 text-sm font-medium text-be-text">
        {label} {hint && <span className="font-normal text-be-muted">— {hint}</span>}
      </label>
      {children}
    </div>
  );
}
