"use client";

import { useEffect, useMemo, useState, type FormEvent } from "react";
import {
  AnimatePresence,
  LayoutGroup,
  motion,
  useReducedMotion,
} from "framer-motion";
import {
  ChevronLeft,
  ChevronRight,
  Copy,
  Pencil,
  Plus,
  Search,
  Trash2,
  X,
} from "lucide-react";
import type { Product, ProductVariant } from "@/data/types";
import { MediaUploader } from "@/components/admin/MediaUploader";
import { Button } from "@/components/ui/Button";
import { formatPrice } from "@/lib/format";
import { useToast } from "@/context/toast-context";
import {
  adminProductsBlock,
  adminProductsShell,
  easeSoft,
} from "@/lib/motion";

const PAGE_SIZE = 15;

const CATEGORY_SLUGS = [
  "outerwear",
  "tops",
  "bottoms",
  "shirts",
  "sweaters",
  "dresses",
  "innerwear",
  "loungewear",
  "accessories",
  "kids",
  "baby",
] as const;

const CATEGORY_LABELS: Record<string, string> = {
  all: "All",
  outerwear: "Outerwear",
  tops: "T-Shirts & Sweats",
  bottoms: "Bottoms",
  shirts: "Shirts & Blouses",
  sweaters: "Sweaters",
  dresses: "Dresses & Skirts",
  innerwear: "Innerwear",
  loungewear: "Loungewear",
  accessories: "Accessories",
  kids: "Kids",
  baby: "Baby",
};

type FormState = {
  name: string;
  price: string;
  compareAt: string;
  categorySlug: string;
  gender: "men" | "women" | "unisex";
  stock: string;
  seller: string;
  shortDescription: string;
  longDescription: string;
  fit: string;
  materials: string;
  care: string;
  details: string;
  tags: string;
  colorOptions: string;
  packOptions: string;
  images: string[];
  imageUrlDraft: string;
  sold: string;
  flashLimit: string;
  rating: string;
  featured: boolean;
  flashSale: boolean;
  bestSeller: boolean;
  newArrival: boolean;
  recentlyOrdered: boolean;
  verified: boolean;
};

const emptyForm = (): FormState => ({
  name: "",
  price: "49",
  compareAt: "",
  categorySlug: "tops",
  gender: "unisex",
  stock: "25",
  seller: "BhoFit",
  shortDescription: "",
  longDescription: "",
  fit: "See product details for sizing and compatibility.",
  materials: "Premium materials",
  care: "Wipe clean; follow care label",
  details: "Quality build, Everyday use",
  tags: "marketplace",
  colorOptions: "Black, Silver, White",
  packOptions: "",
  images: [],
  imageUrlDraft: "",
  sold: "",
  flashLimit: "",
  rating: "4.5",
  featured: false,
  flashSale: false,
  bestSeller: false,
  newArrival: true,
  recentlyOrdered: false,
  verified: true,
});

function variantOptions(variants: ProductVariant[] | undefined, id: string) {
  return variants?.find((v) => v.id === id)?.options.join(", ") ?? "";
}

function productToForm(product: Product): FormState {
  return {
    name: product.name,
    price: String(product.price),
    compareAt: product.compareAt != null ? String(product.compareAt) : "",
    categorySlug: product.categorySlug,
    gender: product.gender,
    stock: String(product.stock),
    seller: product.seller || "BhoFit",
    shortDescription: product.shortDescription,
    longDescription: product.longDescription,
    fit: product.fit,
    materials: product.materials.join(", "),
    care: product.care.join(", "),
    details: product.details.join(", "),
    tags: product.tags.join(", "),
    colorOptions:
      variantOptions(product.variants, "color") || "Black, Silver, White",
    packOptions: variantOptions(product.variants, "pack"),
    images: product.images ?? [],
    imageUrlDraft: "",
    sold: product.sold != null ? String(product.sold) : "",
    flashLimit: product.flashLimit != null ? String(product.flashLimit) : "",
    rating: String(product.rating ?? 4.5),
    featured: Boolean(product.featured),
    flashSale: Boolean(product.flashSale),
    bestSeller: Boolean(product.bestSeller),
    newArrival: Boolean(product.newArrival),
    recentlyOrdered: Boolean(product.recentlyOrdered),
    verified: Boolean(product.verified),
  };
}

function splitList(value: string) {
  return value
    .split(/[,\n]/)
    .map((s) => s.trim())
    .filter(Boolean);
}

function formPayload(form: FormState) {
  const colors = splitList(form.colorOptions);
  const packs = splitList(form.packOptions);
  const variants: ProductVariant[] = [];
  if (colors.length) {
    variants.push({ id: "color", label: "Color", options: colors });
  }
  if (packs.length) {
    variants.push({ id: "pack", label: "Pack", options: packs });
  }
  if (!variants.length) {
    variants.push({
      id: "color",
      label: "Color",
      options: ["Standard"],
    });
  }

  return {
    name: form.name,
    price: Number(form.price),
    compareAt: form.compareAt ? Number(form.compareAt) : null,
    categorySlug: form.categorySlug,
    gender: form.gender,
    stock: Number(form.stock),
    seller: form.seller.trim() || "BhoFit",
    shortDescription: form.shortDescription,
    longDescription: form.longDescription,
    fit: form.fit,
    materials: splitList(form.materials),
    care: splitList(form.care),
    details: splitList(form.details),
    tags: splitList(form.tags),
    images: form.images,
    variants,
    sold: form.sold ? Number(form.sold) : null,
    flashLimit: form.flashLimit ? Number(form.flashLimit) : null,
    rating: Number(form.rating) || 4.5,
    featured: form.featured,
    flashSale: form.flashSale,
    bestSeller: form.bestSeller,
    newArrival: form.newArrival,
    recentlyOrdered: form.recentlyOrdered,
    verified: form.verified,
  };
}

export default function AdminProductsPage() {
  const [list, setList] = useState<Product[]>([]);
  const [form, setForm] = useState<FormState>(emptyForm);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [query, setQuery] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("all");
  const [page, setPage] = useState(1);
  const [tab, setTab] = useState<
    "basics" | "media" | "variants" | "inventory" | "flags"
  >("basics");
  const { toast } = useToast();
  const reduceMotion = useReducedMotion();
  const load = async () => {
    const res = await fetch("/api/admin/products", { credentials: "include" });
    const data = (await res.json()) as { products?: Product[] };
    setList(data.products ?? []);
  };

  useEffect(() => {
    void load();
  }, []);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return list.filter((p) => {
      if (categoryFilter !== "all" && p.categorySlug !== categoryFilter) {
        return false;
      }
      if (!q) return true;
      return (
        p.name.toLowerCase().includes(q) ||
        p.categorySlug.includes(q) ||
        p.id.includes(q) ||
        p.seller.toLowerCase().includes(q)
      );
    });
  }, [list, query, categoryFilter]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const currentPage = Math.min(page, totalPages);
  const paged = filtered.slice(
    (currentPage - 1) * PAGE_SIZE,
    currentPage * PAGE_SIZE,
  );
  const listKey = `${categoryFilter}:${currentPage}:${query.trim().toLowerCase()}`;

  useEffect(() => {
    setPage(1);
  }, [query, categoryFilter]);

  const openCreate = () => {
    setEditingId(null);
    setForm(emptyForm());
    setTab("basics");
    setOpen(true);
  };

  const openEdit = (product: Product) => {
    setEditingId(product.id);
    setForm(productToForm(product));
    setTab("basics");
    setOpen(true);
  };

  const openDuplicate = (product: Product) => {
    const copy = productToForm(product);
    copy.name = `${product.name} (Copy)`;
    copy.newArrival = true;
    setEditingId(null);
    setForm(copy);
    setTab("basics");
    setOpen(true);
  };

  const addImageUrl = () => {
    const url = form.imageUrlDraft.trim();
    if (!url) return;
    if (!/^https?:\/\//i.test(url) && !url.startsWith("/")) {
      toast("Enter a full URL or /uploads/… path", "error");
      return;
    }
    if (form.images.includes(url)) {
      toast("Image already added", "error");
      return;
    }
    setForm((f) => ({
      ...f,
      images: [...f.images, url],
      imageUrlDraft: "",
    }));
  };

  const onSubmit = async (event: FormEvent) => {
    event.preventDefault();
    if (!form.name.trim()) {
      toast("Product name is required", "error");
      setTab("basics");
      return;
    }
    if (!form.images.length) {
      toast("Add at least one product photo", "error");
      setTab("media");
      return;
    }
    setSaving(true);
    try {
      const payload = formPayload(form);
      const res = await fetch(
        editingId ? `/api/admin/products/${editingId}` : "/api/admin/products",
        {
          method: editingId ? "PATCH" : "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify(payload),
        },
      );
      const data = (await res.json()) as { error?: string };
      if (!res.ok) {
        toast(data.error ?? "Could not save product", "error");
        return;
      }
      toast(editingId ? "Product updated" : "Product created");
      setOpen(false);
      await load();
    } finally {
      setSaving(false);
    }
  };

  const onDelete = async (id: string) => {
    if (!window.confirm("Delete this product?")) return;
    const res = await fetch(`/api/admin/products/${id}`, {
      method: "DELETE",
      credentials: "include",
    });
    if (!res.ok) {
      toast("Could not delete product", "error");
      return;
    }
    toast("Product deleted");
    await load();
  };

  return (
    <motion.div
      className="space-y-6"
      variants={reduceMotion ? undefined : adminProductsShell}
      initial={reduceMotion ? false : "hidden"}
      animate="show"
    >
      <motion.div
        variants={reduceMotion ? undefined : adminProductsBlock}
        className="flex flex-wrap items-end justify-between gap-4"
      >
        <div>
          <h1 className="text-2xl font-semibold tracking-tight text-foreground">
            Products
          </h1>
          <p className="mt-1 text-sm text-muted">
            <motion.span
              key={listKey}
              initial={
                reduceMotion
                  ? false
                  : { opacity: 0.35, y: 4, filter: "blur(2px)" }
              }
              animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
              transition={{ duration: 0.45, ease: easeSoft }}
              className="inline-block"
            >
              {filtered.length} products · showing {PAGE_SIZE} per page
              {categoryFilter !== "all"
                ? ` · ${CATEGORY_LABELS[categoryFilter] ?? categoryFilter}`
                : ""}
            </motion.span>
          </p>
        </div>
        <motion.div
          whileHover={reduceMotion ? undefined : { y: -3, scale: 1.02 }}
          whileTap={reduceMotion ? undefined : { scale: 0.98 }}
          transition={{ type: "spring", stiffness: 400, damping: 28 }}
        >
          <Button onClick={openCreate} className="h-11 gap-2 rounded-xl">
            <Plus className="h-4 w-4" />
            Add product
          </Button>
        </motion.div>
      </motion.div>

      <motion.div
        variants={reduceMotion ? undefined : adminProductsBlock}
        className="relative"
      >
        <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
        <input
          value={query}
          onChange={(event) => setQuery(event.target.value)}
          placeholder="Search name, seller, id…"
          className="h-11 w-full rounded-xl border border-border bg-background pl-10 pr-4 text-sm text-foreground outline-none transition-all duration-300 focus:border-emerald-500/50 focus:shadow-[0_0_0_3px_rgba(16,185,129,0.12)]"
        />
      </motion.div>

      <motion.div variants={reduceMotion ? undefined : adminProductsBlock}>
        <LayoutGroup id="admin-product-categories">
          <div className="-mx-1 flex gap-2 overflow-x-auto overflow-y-hidden px-1 pb-1">
            {(["all", ...CATEGORY_SLUGS] as const).map((slug) => {
              const active = categoryFilter === slug;
              return (
                <motion.button
                  key={slug}
                  type="button"
                  onClick={() => setCategoryFilter(slug)}
                  whileHover={reduceMotion ? undefined : { y: -2 }}
                  whileTap={reduceMotion ? undefined : { scale: 0.96 }}
                  transition={{ type: "spring", stiffness: 420, damping: 30 }}
                  className={`relative shrink-0 rounded-full px-3.5 py-2 text-xs font-medium transition-colors sm:text-sm ${
                    active
                      ? "text-emerald-800 dark:text-emerald-200"
                      : "text-muted hover:text-foreground"
                  }`}
                >
                  {active ? (
                    <motion.span
                      layoutId="admin-category-pill"
                      className="absolute inset-0 rounded-full border border-emerald-500/30 bg-emerald-500/15 shadow-sm"
                      transition={{
                        type: "spring",
                        stiffness: 320,
                        damping: 28,
                        mass: 0.7,
                      }}
                    />
                  ) : null}
                  <span className="relative z-10">
                    {CATEGORY_LABELS[slug] ?? slug}
                  </span>
                </motion.button>
              );
            })}
          </div>
        </LayoutGroup>
      </motion.div>

      <motion.div
        variants={reduceMotion ? undefined : adminProductsBlock}
        className="rounded-2xl border border-border bg-card shadow-sm"
      >
        {/* overflow-y-hidden prevents a second vertical scrollbar */}
        <div className="overflow-x-auto overflow-y-hidden">
          <table className="min-w-full text-left text-sm">
            <thead className="bg-surface text-xs uppercase tracking-wider text-muted">
              <tr>
                <th className="px-4 py-3 font-medium">Product</th>
                <th className="px-4 py-3 font-medium">Category</th>
                <th className="px-4 py-3 font-medium">Price</th>
                <th className="px-4 py-3 font-medium">Stock</th>
                <th className="px-4 py-3 font-medium text-right">Actions</th>
              </tr>
            </thead>
            <tbody key={listKey}>
              {paged.map((product, index) => (
                <motion.tr
                  key={product.id}
                  initial={
                    reduceMotion
                      ? false
                      : {
                          opacity: 0,
                          y: 22,
                          filter: "blur(3px)",
                        }
                  }
                  animate={{
                    opacity: 1,
                    y: 0,
                    filter: "blur(0px)",
                  }}
                  whileInView={{
                    opacity: 1,
                    y: 0,
                    filter: "blur(0px)",
                  }}
                  viewport={{
                    once: false,
                    amount: 0.15,
                    margin: "80px 0px 80px 0px",
                  }}
                  transition={{
                    duration: 0.58,
                    delay: reduceMotion
                      ? 0
                      : Math.min(index * 0.05, 0.4),
                    ease: easeSoft,
                  }}
                  className="border-t border-border transition-colors duration-300 hover:bg-surface/80"
                >
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      <motion.span
                        whileHover={
                          reduceMotion ? undefined : { scale: 1.06, y: -1 }
                        }
                        transition={{
                          type: "spring",
                          stiffness: 380,
                          damping: 24,
                        }}
                        className="relative h-12 w-12 shrink-0 overflow-hidden rounded-lg bg-surface"
                      >
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          src={product.images[0] || "/uploads/.gitkeep"}
                          alt=""
                          className="h-full w-full object-cover"
                          onError={(event) => {
                            (event.target as HTMLImageElement).src =
                              "https://images.unsplash.com/photo-1441986300917-64674bd600d8?auto=format&fit=crop&w=200&q=60";
                          }}
                        />
                      </motion.span>
                      <div>
                        <p className="font-medium text-foreground">
                          {product.name}
                        </p>
                        <p className="text-xs text-muted">{product.id}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-muted">{product.category}</td>
                  <td className="px-4 py-3 tabular-nums text-foreground">
                    {formatPrice(product.price)}
                  </td>
                  <td className="px-4 py-3 tabular-nums text-muted">
                    {product.stock}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex justify-end gap-2">
                      <motion.button
                        type="button"
                        whileHover={reduceMotion ? undefined : { y: -2 }}
                        whileTap={reduceMotion ? undefined : { scale: 0.96 }}
                        transition={{
                          type: "spring",
                          stiffness: 420,
                          damping: 28,
                        }}
                        onClick={() => openEdit(product)}
                        className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border px-3 text-xs text-foreground transition-colors hover:bg-surface"
                      >
                        <Pencil className="h-3.5 w-3.5" />
                        Edit
                      </motion.button>
                      <motion.button
                        type="button"
                        whileHover={reduceMotion ? undefined : { y: -2 }}
                        whileTap={reduceMotion ? undefined : { scale: 0.96 }}
                        transition={{
                          type: "spring",
                          stiffness: 420,
                          damping: 28,
                        }}
                        onClick={() => openDuplicate(product)}
                        className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border px-3 text-xs text-foreground transition-colors hover:bg-surface"
                        title="Duplicate"
                      >
                        <Copy className="h-3.5 w-3.5" />
                      </motion.button>
                      <motion.button
                        type="button"
                        whileHover={reduceMotion ? undefined : { y: -2 }}
                        whileTap={reduceMotion ? undefined : { scale: 0.96 }}
                        transition={{
                          type: "spring",
                          stiffness: 420,
                          damping: 28,
                        }}
                        onClick={() => void onDelete(product.id)}
                        className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border px-3 text-xs text-red-600 transition-colors hover:bg-red-500/10 dark:text-red-300"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </motion.button>
                    </div>
                  </td>
                </motion.tr>
              ))}
            </tbody>
          </table>
        </div>

        {filtered.length === 0 ? (
          <motion.p
            key={`empty-${listKey}`}
            initial={
              reduceMotion
                ? false
                : { opacity: 0, y: 10, filter: "blur(2px)" }
            }
            animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
            transition={{ duration: 0.5, ease: easeSoft }}
            className="px-4 py-10 text-center text-sm text-muted"
          >
            No products found
            {categoryFilter !== "all"
              ? ` in ${CATEGORY_LABELS[categoryFilter] ?? categoryFilter}`
              : ""}
            .
          </motion.p>
        ) : (
          <div className="flex flex-wrap items-center justify-between gap-3 border-t border-border px-4 py-3">
            <motion.p
              key={listKey}
              initial={reduceMotion ? false : { opacity: 0.35, y: 4 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.35, ease: easeSoft }}
              className="text-xs text-muted"
            >
              Page {currentPage} of {totalPages} ·{" "}
              {(currentPage - 1) * PAGE_SIZE + 1}–
              {Math.min(currentPage * PAGE_SIZE, filtered.length)} of{" "}
              {filtered.length}
            </motion.p>
            <div className="flex items-center gap-2">
              <motion.button
                type="button"
                disabled={currentPage <= 1}
                whileHover={reduceMotion ? undefined : { y: -1 }}
                whileTap={reduceMotion ? undefined : { scale: 0.96 }}
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                className="inline-flex h-9 items-center gap-1 rounded-lg border border-border px-3 text-xs text-foreground transition-colors hover:bg-surface disabled:opacity-40"
              >
                <ChevronLeft className="h-3.5 w-3.5" />
                Prev
              </motion.button>
              <motion.button
                type="button"
                disabled={currentPage >= totalPages}
                whileHover={reduceMotion ? undefined : { y: -1 }}
                whileTap={reduceMotion ? undefined : { scale: 0.96 }}
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                className="inline-flex h-9 items-center gap-1 rounded-lg border border-border px-3 text-xs text-foreground transition-colors hover:bg-surface disabled:opacity-40"
              >
                Next
                <ChevronRight className="h-3.5 w-3.5" />
              </motion.button>
            </div>
          </div>
        )}
      </motion.div>

      <AnimatePresence>
        {open ? (
          <motion.div
            key="product-editor"
            initial={reduceMotion ? false : { opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={reduceMotion ? undefined : { opacity: 0 }}
            transition={{ duration: 0.3, ease: easeSoft }}
            className="fixed inset-0 z-50 flex items-end justify-center bg-black/70 p-0 sm:items-center sm:p-6"
          >
            <motion.form
              onSubmit={onSubmit}
              initial={
                reduceMotion
                  ? false
                  : { opacity: 0, y: 24, scale: 0.985, filter: "blur(3px)" }
              }
              animate={{ opacity: 1, y: 0, scale: 1, filter: "blur(0px)" }}
              exit={
                reduceMotion
                  ? undefined
                  : { opacity: 0, y: 14, scale: 0.985, filter: "blur(2px)" }
              }
              transition={{ duration: 0.45, ease: easeSoft }}
              className="flex max-h-[94vh] w-full max-w-4xl flex-col overflow-hidden rounded-t-3xl border border-border bg-card text-foreground shadow-2xl sm:rounded-3xl"
            >
            <div className="flex items-center justify-between border-b border-border px-5 py-4">
              <div>
                <h2 className="text-lg font-semibold text-foreground">
                  {editingId ? "Edit product" : "New product"}
                </h2>
                <p className="text-xs text-muted">
                  Full catalog editor — photos, variants, inventory, merchandising.
                </p>
              </div>
              <button
                type="button"
                onClick={() => setOpen(false)}
                className="rounded-xl border border-border p-2 text-foreground hover:bg-surface"
              >
                <X className="h-4 w-4" />
              </button>
            </div>

            <div className="flex gap-1 overflow-x-auto border-b border-border px-3 pt-3 sm:px-5">
              {(
                [
                  ["basics", "Basics"],
                  ["media", "Photos"],
                  ["variants", "Variants"],
                  ["inventory", "Inventory"],
                  ["flags", "Merchandising"],
                ] as const
              ).map(([id, label]) => (
                <button
                  key={id}
                  type="button"
                  onClick={() => setTab(id)}
                  className={`relative shrink-0 rounded-t-xl px-3 py-2 text-sm transition-colors ${
                    tab === id
                      ? "text-emerald-700 dark:text-emerald-300"
                      : "text-muted hover:text-foreground"
                  }`}
                >
                  {tab === id ? (
                    <motion.span
                      layoutId="product-editor-tab"
                      className="absolute inset-0 rounded-t-xl bg-surface"
                      transition={{
                        type: "spring",
                        stiffness: 400,
                        damping: 34,
                      }}
                    />
                  ) : null}
                  <span className="relative z-10">{label}</span>
                </button>
              ))}
            </div>

            <div className="grid flex-1 gap-6 overflow-y-auto px-5 py-5 lg:grid-cols-[1fr_220px]">
              <div className="min-h-0">
                <AnimatePresence mode="wait" initial={false}>
                  <motion.div
                    key={tab}
                    initial={
                      reduceMotion
                        ? false
                        : { opacity: 0, y: 10, filter: "blur(3px)" }
                    }
                    animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
                    exit={
                      reduceMotion
                        ? undefined
                        : { opacity: 0, y: -8, filter: "blur(2px)" }
                    }
                    transition={{ duration: 0.32, ease: easeSoft }}
                    className="space-y-4"
                  >
                {tab === "basics" ? (
                  <>
                    <Field
                      label="Name"
                      value={form.name}
                      onChange={(value) => setForm((f) => ({ ...f, name: value }))}
                      required
                    />
                    <div className="grid gap-4 sm:grid-cols-2">
                      <label className="block space-y-1.5 text-sm">
                        <span className="text-muted">Category</span>
                        <select
                          value={form.categorySlug}
                          onChange={(event) =>
                            setForm((f) => ({
                              ...f,
                              categorySlug: event.target.value,
                            }))
                          }
                          className="h-11 w-full rounded-xl border border-border bg-background px-3 text-sm text-foreground"
                        >
                          {CATEGORY_SLUGS.map((slug) => (
                            <option key={slug} value={slug}>
                              {slug}
                            </option>
                          ))}
                        </select>
                      </label>
                      <Field
                        label="Seller"
                        value={form.seller}
                        onChange={(value) =>
                          setForm((f) => ({ ...f, seller: value }))
                        }
                      />
                    </div>
                    <Field
                      label="Short description"
                      value={form.shortDescription}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, shortDescription: value }))
                      }
                      textarea
                    />
                    <Field
                      label="Long description"
                      value={form.longDescription}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, longDescription: value }))
                      }
                      textarea
                    />
                    <div className="grid gap-4 sm:grid-cols-2">
                      <Field
                        label="Materials (comma separated)"
                        value={form.materials}
                        onChange={(value) =>
                          setForm((f) => ({ ...f, materials: value }))
                        }
                      />
                      <Field
                        label="Care (comma separated)"
                        value={form.care}
                        onChange={(value) =>
                          setForm((f) => ({ ...f, care: value }))
                        }
                      />
                    </div>
                    <Field
                      label="Details / bullets (comma separated)"
                      value={form.details}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, details: value }))
                      }
                    />
                    <Field
                      label="Fit / compatibility notes"
                      value={form.fit}
                      onChange={(value) => setForm((f) => ({ ...f, fit: value }))}
                    />
                    <Field
                      label="Tags (comma separated)"
                      value={form.tags}
                      onChange={(value) => setForm((f) => ({ ...f, tags: value }))}
                    />
                  </>
                ) : null}

                {tab === "media" ? (
                  <div className="space-y-4">
                    <MediaUploader
                      images={form.images}
                      onChange={(images) => setForm((f) => ({ ...f, images }))}
                      folder="products"
                      max={10}
                    />
                    <div className="rounded-2xl border border-border bg-surface p-4">
                      <p className="mb-2 text-sm font-medium text-foreground">
                        Or paste an image URL
                      </p>
                      <div className="flex gap-2">
                        <input
                          value={form.imageUrlDraft}
                          onChange={(event) =>
                            setForm((f) => ({
                              ...f,
                              imageUrlDraft: event.target.value,
                            }))
                          }
                          placeholder="https://… or /uploads/…"
                          className="h-11 flex-1 rounded-xl border border-border bg-background px-3 text-sm text-foreground"
                        />
                        <button
                          type="button"
                          onClick={addImageUrl}
                          className="h-11 rounded-xl border border-border px-4 text-sm text-foreground hover:bg-surface"
                        >
                          Add
                        </button>
                      </div>
                    </div>
                  </div>
                ) : null}

                {tab === "variants" ? (
                  <div className="space-y-4">
                    <Field
                      label="Color options (comma separated)"
                      value={form.colorOptions}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, colorOptions: value }))
                      }
                      placeholder="Black, Silver, Graphite"
                    />
                    <Field
                      label="Pack / size options (optional)"
                      value={form.packOptions}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, packOptions: value }))
                      }
                      placeholder="Travel, Full size"
                    />
                    <label className="block space-y-1.5 text-sm">
                      <span className="text-muted">Audience</span>
                      <select
                        value={form.gender}
                        onChange={(event) =>
                          setForm((f) => ({
                            ...f,
                            gender: event.target.value as FormState["gender"],
                          }))
                        }
                        className="h-11 w-full rounded-xl border border-border bg-background px-3 text-sm text-foreground"
                      >
                        <option value="unisex">Unisex / all</option>
                        <option value="men">Men</option>
                        <option value="women">Women</option>
                      </select>
                    </label>
                    <p className="text-xs text-muted">
                      No clothing S/M/L required — use pack options only when
                      needed (e.g. Travel / Full size).
                    </p>
                  </div>
                ) : null}

                {tab === "inventory" ? (
                  <div className="grid gap-4 sm:grid-cols-2">
                    <Field
                      label="Price"
                      type="number"
                      value={form.price}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, price: value }))
                      }
                      required
                    />
                    <Field
                      label="Compare at"
                      type="number"
                      value={form.compareAt}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, compareAt: value }))
                      }
                    />
                    <Field
                      label="Stock"
                      type="number"
                      value={form.stock}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, stock: value }))
                      }
                      required
                    />
                    <Field
                      label="Rating (0–5)"
                      type="number"
                      value={form.rating}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, rating: value }))
                      }
                    />
                    <Field
                      label="Units sold"
                      type="number"
                      value={form.sold}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, sold: value }))
                      }
                    />
                    <Field
                      label="Flash sale limit"
                      type="number"
                      value={form.flashLimit}
                      onChange={(value) =>
                        setForm((f) => ({ ...f, flashLimit: value }))
                      }
                    />
                  </div>
                ) : null}

                {tab === "flags" ? (
                  <div className="grid gap-3 sm:grid-cols-2">
                    {(
                      [
                        ["featured", "Featured"],
                        ["flashSale", "Flash sale"],
                        ["bestSeller", "Best seller"],
                        ["newArrival", "New arrival"],
                        ["recentlyOrdered", "Recently ordered"],
                        ["verified", "Verified seller"],
                      ] as const
                    ).map(([key, label]) => (
                      <label
                        key={key}
                        className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3 text-sm text-foreground"
                      >
                        <input
                          type="checkbox"
                          checked={form[key]}
                          onChange={(event) =>
                            setForm((f) => ({
                              ...f,
                              [key]: event.target.checked,
                            }))
                          }
                          className="accent-emerald-500"
                        />
                        {label}
                      </label>
                    ))}
                  </div>
                ) : null}
                  </motion.div>
                </AnimatePresence>
              </div>

              <aside className="space-y-3 rounded-2xl border border-border bg-surface p-4">
                <p className="text-xs font-semibold uppercase tracking-wider text-muted">
                  Live preview
                </p>
                <div className="overflow-hidden rounded-xl bg-surface">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={
                      form.images[0] ||
                      "https://images.unsplash.com/photo-1441986300917-64674bd600d8?auto=format&fit=crop&w=400&q=60"
                    }
                    alt=""
                    className="aspect-square w-full object-cover"
                    onError={(event) => {
                      (event.target as HTMLImageElement).src =
                        "https://images.unsplash.com/photo-1441986300917-64674bd600d8?auto=format&fit=crop&w=400&q=60";
                    }}
                  />
                </div>
                <p className="text-sm font-medium text-foreground">
                  {form.name || "Untitled product"}
                </p>
                <p className="text-emerald-700 dark:text-emerald-300">
                  {formatPrice(Number(form.price) || 0)}
                </p>
                <p className="text-xs text-muted">
                  {form.categorySlug} · stock {form.stock || 0}
                </p>
                <p className="text-xs text-muted">
                  {form.images.length} photo
                  {form.images.length === 1 ? "" : "s"}
                </p>
              </aside>
            </div>

            <div className="flex items-center justify-end gap-3 border-t border-border px-5 py-4">
              <button
                type="button"
                onClick={() => setOpen(false)}
                className="h-11 rounded-xl border border-border px-4 text-sm text-foreground hover:bg-surface"
              >
                Cancel
              </button>
              <Button type="submit" disabled={saving} className="h-11 rounded-xl">
                {saving
                  ? "Saving…"
                  : editingId
                    ? "Update product"
                    : "Create product"}
              </Button>
            </div>
            </motion.form>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </motion.div>
  );
}

function Field({
  label,
  value,
  onChange,
  type = "text",
  required,
  textarea,
  placeholder,
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  type?: string;
  required?: boolean;
  textarea?: boolean;
  placeholder?: string;
}) {
  const className =
    "w-full rounded-xl border border-border bg-background px-3 text-sm text-foreground outline-none focus:border-emerald-500/50";
  return (
    <label className="block space-y-1.5 text-sm">
      <span className="text-muted">{label}</span>
      {textarea ? (
        <textarea
          value={value}
          required={required}
          placeholder={placeholder}
          onChange={(event) => onChange(event.target.value)}
          rows={4}
          className={`${className} py-3`}
        />
      ) : (
        <input
          type={type}
          value={value}
          required={required}
          placeholder={placeholder}
          onChange={(event) => onChange(event.target.value)}
          className={`${className} h-11`}
          step={type === "number" ? "any" : undefined}
        />
      )}
    </label>
  );
}
