"use client"

import { useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Plus, X } from "lucide-react"

import { itemsApi } from "@/lib/api/items"
import { categoriesApi } from "@/lib/api/categories"
import { brandsApi } from "@/lib/api/brands"
import { itemTypesApi } from "@/lib/api/item-types"
import { productConfig } from "@/lib/api/product-config"
import { uomsApi } from "@/lib/api/uoms"
import { warehousesApi } from "@/lib/api/warehouses"
import { errorMessage } from "@/lib/error-map"
import {
  contentPairErrors,
  validateVariantContent,
  validateVariantItemForm,
  validateVariantPrices,
} from "@/lib/validations/master-data"
import { cn } from "@/lib/utils"
import {
  Brand,
  Category,
  ItemType,
  MeasureUnit,
  ProductConfig,
  StockNature,
  SubCategory,
  WARRANTY_PERIOD_MONTHS_OPTIONS,
  Warranty,
  WarrantyPeriodMonths,
} from "@/types/master-data"

/** Entry units. Only ml/g are stored — the server normalises L and Kg ×1000 on write. */
const CONTENT_UNITS: MeasureUnit[] = ["Ml", "L", "G", "Kg"]

import { Badge } from "@/components/ui/badge"
import { Button, buttonVariants } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { FieldError } from "@/components/ui/field"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

function skuSegment(text: string, maxLen: number): string {
  const cleaned = text.trim().toUpperCase().replace(/[^A-Z0-9]/g, "")
  return cleaned.slice(0, maxLen) || "GEN"
}

/**
 * A value on a builder dimension. `qty`/`unit` are set only on a measurable dimension;
 * `label` is the single source of truth for the chip, the item name and the SKU segment.
 */
type DimensionValue = { label: string; qty: number | null; unit: MeasureUnit | null }

const isMeasured = (v: DimensionValue): v is DimensionValue & { qty: number; unit: MeasureUnit } =>
  v.qty !== null && v.unit !== null

/** Canonical casing, so 1.5 L renders as "1.5L" and not "1.5l". */
const UNIT_LABEL: Record<MeasureUnit, string> = { Ml: "ml", L: "L", G: "g", Kg: "kg" }

const measuredLabel = (qty: number, unit: MeasureUnit) => `${qty}${UNIT_LABEL[unit]}`

/**
 * Normalised identity of a measurement, mirroring the server's `ItemContent.Normalize`
 * (L/Kg ×1000 → ml/g). Used for BOTH the SKU segment and value dedupe, so the client's
 * notion of "same size" is the server's.
 *
 * The decimal point becomes `P` rather than being stripped: `skuSegment` deletes it, which
 * would make 2.5ml and 25ml — and 1.5L and 15L — produce identical SKUs and fail the
 * create loop partway with SKU_DUPLICATE.
 */
function measureKey(qty: number, unit: MeasureUnit): string {
  const factor = unit === "L" || unit === "Kg" ? 1000 : 1
  const base = unit === "L" || unit === "Ml" ? "ML" : "G"
  const n = Math.round(qty * factor * 10000) / 10000
  const digits = n.toFixed(4).replace(/0+$/, "").replace(/\.$/, "")
  return `${digits.replace(".", "P")}${base}`
}

function buildVariantSku(categoryLabel: string, values: DimensionValue[]): string {
  return [
    skuSegment(categoryLabel, 3),
    // Measurement segments are deliberately NOT truncated — truncation is what collides.
    ...values.map((v) => (isMeasured(v) ? measureKey(v.qty, v.unit) : skuSegment(v.label, 3))),
  ].join("-")
}

export default function NewItemPage() {
  const router = useRouter()

  const [categories, setCategories] = useState<Category[] | null>(null)
  const [brands, setBrands] = useState<Brand[] | null>(null)
  const [itemTypes, setItemTypes] = useState<ItemType[] | null>(null)
  const [config, setConfig] = useState<ProductConfig | null>(null)
  const [uoms, setUoms] = useState<{ uomId: number; name: string }[]>([])
  /** Defaults to the first UOM once loaded; null only means none exist yet. */
  const [baseUomId, setBaseUomId] = useState<number | null>(null)
  // Kept as a raw string: an empty box means "no content size", which is different from 0.
  const [contentQty, setContentQty] = useState("")
  const [contentUnit, setContentUnit] = useState<MeasureUnit | null>(null)
  const [stockNature, setStockNature] = useState<StockNature>("Stocked")
  const [loadError, setLoadError] = useState<string | null>(null)

  const [productName, setProductName] = useState("")
  const [categoryId, setCategoryId] = useState<number | null>(null)
  const [subCategories, setSubCategories] = useState<SubCategory[]>([])
  const [subCategoryId, setSubCategoryId] = useState<number | null>(null)
  const [brandId, setBrandId] = useState<number | null>(null)
  // Frontend-only: there's no warehouse field anywhere on the Item contract, so this
  // isn't sent on submit — nothing to wire it to server-side.
  const [warehouses, setWarehouses] = useState<{ warehouseId: number; code: string; name: string }[]>([])
  const [warehouseId, setWarehouseId] = useState<number | null>(null)

  const [checkedItemTypeIds, setCheckedItemTypeIds] = useState<number[]>([])
  const [valuesByCategory, setValuesByCategory] = useState<Record<number, DimensionValue[]>>({})
  const [inputByCategory, setInputByCategory] = useState<Record<number, string>>({})
  // Measurable dimensions enter a number + unit instead of free text.
  const [qtyByCategory, setQtyByCategory] = useState<Record<number, string>>({})
  const [unitByCategory, setUnitByCategory] = useState<Record<number, MeasureUnit | null>>({})
  const [valueErrors, setValueErrors] = useState<Record<number, string>>({})
  // Lets a specific generated combination be dropped from the preview table before
  // submit, without having to remove and re-add the whole value that produced it.
  const [removedVariantKeys, setRemovedVariantKeys] = useState<Set<string>>(new Set())

  // Sales pricing (FR-MD-01). "stock" ⇒ salePrice sent as null (sell at FIFO value);
  // "fixed" ⇒ every variant must carry a price. `fixValue` is the shared default that
  // pre-fills rows; a per-key entry in `pricesByKey` overrides it for that one row only.
  const [priceMode, setPriceMode] = useState<"stock" | "fixed">("stock")
  const [fixValue, setFixValue] = useState<string>("")
  const [pricesByKey, setPricesByKey] = useState<Record<string, string>>({})
  const [priceErrors, setPriceErrors] = useState<Record<string, string>>({})

  // Warranty (FR-MD-01). Applies to every generated variant — there is no per-variant override.
  const [warranty, setWarranty] = useState<Warranty>("NonWarranty")
  const [warrantyPeriodMonths, setWarrantyPeriodMonths] = useState<WarrantyPeriodMonths | null>(null)

  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitError, setSubmitError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  // A row shows its own override if set, otherwise it follows the shared fix value.
  const priceFor = (key: string) => pricesByKey[key] ?? fixValue

  useEffect(() => {
    Promise.all([
      categoriesApi.list({ pageSize: 200, status: "Active" }),
      brandsApi.list({ pageSize: 200, status: "Active" }),
      itemTypesApi.list({ pageSize: 200, status: "Active" }),
      productConfig(),
      uomsApi.list({ pageSize: 200 }),
      warehousesApi.list({ pageSize: 200 }),
    ])
      .then(([cat, br, types, cfg, uoms, wh]) => {
        setCategories(cat.items)
        setBrands(br.items)
        setItemTypes(types.items)
        setConfig(cfg)
        setUoms(uoms.items)
        setBaseUomId(uoms.items[0]?.uomId ?? null)
        setWarehouses(wh.items)
      })
      .catch((err) => setLoadError(errorMessage(err)))
  }, [])

  // Subcategories are their own resource now — fetched per category rather than filtered
  // out of a flat list by parentId (that column no longer exists).
  useEffect(() => {
    if (categoryId === null || !config?.subcategoriesEnabled) {
      setSubCategories([])
      return
    }
    categoriesApi
      .listSubCategories(categoryId, { pageSize: 200, status: "Active" })
      .then((res) => setSubCategories(res.items))
      .catch(() => setSubCategories([]))
  }, [categoryId, config?.subcategoriesEnabled])

  const brandLabel = (brands ?? []).find((b) => b.brandId === brandId)?.name ?? ""
  /**
   * The product being built ("Coca Cola"), typed rather than derived. It names every generated
   * item and supplies the SKU's leading segment.
   *
   * Category and subcategory still classify the item and are both sent to the server; they just
   * no longer name it, which is what produced labels like "Beverages - 500ml".
   */
  const productLabel = productName.trim()

  function handleCategoryChange(value: number | null) {
    setCategoryId(value)
    setSubCategoryId(null)
  }

  function toggleItemType(itemTypeId: number) {
    setCheckedItemTypeIds((prev) =>
      prev.includes(itemTypeId) ? prev.filter((id) => id !== itemTypeId) : [...prev, itemTypeId]
    )
  }

  /**
   * Add is the real validation gate for a measurement — rejecting here means a half or
   * duplicate pair never reaches state, so nothing downstream has to defend against one.
   */
  function addValue(itemTypeId: number) {
    const measurable = (itemTypes ?? []).find((t) => t.itemTypeId === itemTypeId)?.isMeasurable ?? false

    if (!measurable) {
      const label = (inputByCategory[itemTypeId] ?? "").trim()
      if (label) {
        setValuesByCategory((prev) => {
          const existing = prev[itemTypeId] ?? []
          if (existing.some((v) => v.label.toLowerCase() === label.toLowerCase())) return prev
          return { ...prev, [itemTypeId]: [...existing, { label, qty: null, unit: null }] }
        })
      }
      setInputByCategory((prev) => ({ ...prev, [itemTypeId]: "" }))
      return
    }

    const raw = (qtyByCategory[itemTypeId] ?? "").trim()
    const unit = unitByCategory[itemTypeId] ?? null
    const qty = Number(raw)

    if (!raw || Number.isNaN(qty) || qty <= 0) {
      setValueErrors((prev) => ({ ...prev, [itemTypeId]: "Enter a size greater than 0" }))
      return
    }
    if (!unit) {
      setValueErrors((prev) => ({ ...prev, [itemTypeId]: "Select a unit" }))
      return
    }

    // Dedupe on the NORMALISED size, not the label: 500 ml and 0.5 L read differently but
    // store identically, so a label-only check would create two items of the same size.
    const key = measureKey(qty, unit)
    const existing = valuesByCategory[itemTypeId] ?? []
    if (existing.some((v) => isMeasured(v) && measureKey(v.qty, v.unit) === key)) {
      setValueErrors((prev) => ({ ...prev, [itemTypeId]: "That size is already in the list" }))
      return
    }

    setValuesByCategory((prev) => ({
      ...prev,
      [itemTypeId]: [...(prev[itemTypeId] ?? []), { label: measuredLabel(qty, unit), qty, unit }],
    }))
    setQtyByCategory((prev) => ({ ...prev, [itemTypeId]: "" }))
    setValueErrors((prev) => ({ ...prev, [itemTypeId]: "" }))
  }

  function removeValue(itemTypeId: number, label: string) {
    setValuesByCategory((prev) => ({
      ...prev,
      [itemTypeId]: (prev[itemTypeId] ?? []).filter((v) => v.label !== label),
    }))
  }

  const activeCategories = useMemo(
    () =>
      (itemTypes ?? [])
        .filter((t) => checkedItemTypeIds.includes(t.itemTypeId))
        .map((t) => ({ ...t, values: valuesByCategory[t.itemTypeId] ?? [] }))
        .filter((t) => t.values.length > 0),
    [itemTypes, checkedItemTypeIds, valuesByCategory]
  )

  const allVariants = useMemo(() => {
    if (activeCategories.length === 0) return []
    let combinations: { key: string; parts: { name: string; value: DimensionValue }[] }[] = [{ key: "", parts: [] }]
    for (const cat of activeCategories) {
      const next: typeof combinations = []
      for (const combo of combinations) {
        for (const value of cat.values) {
          next.push({
            key: combo.key ? `${combo.key}::${value.label}` : value.label,
            parts: [...combo.parts, { name: cat.name, value }],
          })
        }
      }
      combinations = next
    }
    return combinations.map((c) => ({
      ...c,
      sku: buildVariantSku(productLabel, c.parts.map((p) => p.value)),
    }))
  }, [activeCategories, productLabel])

  const variants = useMemo(
    () => allVariants.filter((v) => !removedVariantKeys.has(v.key)),
    [allVariants, removedVariantKeys]
  )

  function removeVariant(key: string) {
    setRemovedVariantKeys((prev) => new Set(prev).add(key))
  }

  /**
   * True once a checked dimension supplies each variant's content size. The form-level
   * content field is then hidden and cleared, so the two can never disagree.
   */
  const measurableCheckedCount = (itemTypes ?? []).filter(
    (t) => checkedItemTypeIds.includes(t.itemTypeId) && t.isMeasurable
  ).length
  // Keyed off *checked*, not "checked and already has values": the moment a measurement
  // dimension is ticked the form-level pair is irrelevant, so it should not linger while the
  // first value is being typed.
  const hasMeasurableDimension = measurableCheckedCount > 0

  /**
   * The shared content pair is offered only when it is the ONLY way to set a content size:
   * dimensions are chosen, and none of them measures anything (a Colour-only product, whose
   * variants really do all hold the same amount).
   *
   * Deliberately hidden on the untouched page. Showing it there invites someone to fill in one
   * size before discovering that ticking Size would have captured a size per value — which
   * reads as though sizes still apply to every variant at once.
   */
  const showSharedContent = checkedItemTypeIds.length > 0 && !hasMeasurableDimension

  useEffect(() => {
    if (!hasMeasurableDimension) return
    setContentQty("")
    setContentUnit(null)
  }, [hasMeasurableDimension])

  /** A variant's own measured part, else the form-level fallback pair. */
  function contentForVariant(variant: { parts: { value: DimensionValue }[] }) {
    const measured = variant.parts.find((p) => isMeasured(p.value))
    if (measured && isMeasured(measured.value)) {
      return { qty: measured.value.qty, unit: measured.value.unit }
    }
    // Only fall back to the shared pair when that pair is the one on offer, so a value left
    // behind by an earlier selection can never be applied invisibly.
    if (!showSharedContent || !contentQty.trim() || !contentUnit) return null
    return { qty: Number(contentQty), unit: contentUnit }
  }

  function contentLabelFor(variant: { parts: { value: DimensionValue }[] }) {
    const content = contentForVariant(variant)
    return content ? measuredLabel(content.qty, content.unit) : "—"
  }

  async function handleSubmit() {
    setSubmitError(null)
    const nextErrors: Record<string, string> = {
      ...validateVariantItemForm({ productName, categoryId, hasVariants: variants.length > 0 }),
      // Validate the shared pair exactly when it is on screen. Validating it while hidden
      // would block submit with a message the user cannot see.
      ...(showSharedContent ? contentPairErrors(contentQty, contentUnit) : {}),
    }
    if (measurableCheckedCount > 1) {
      nextErrors.measurable = "Only one measurement dimension can be used at a time."
    }
    if (warranty === "Warranty" && warrantyPeriodMonths === null) {
      nextErrors.warrantyPeriodMonths = "Select a warranty period"
    }
    // Should never fire — addValue is the real gate — so it catches stale state only.
    const contentSweep = validateVariantContent(
      variants.map((v) => v.key),
      (key) => {
        const variant = variants.find((v) => v.key === key)
        const content = variant ? contentForVariant(variant) : null
        return content
          ? { qty: String(content.qty), unit: content.unit }
          : { qty: "", unit: null }
      },
    )
    const sweepMessage = Object.values(contentSweep)[0]
    if (sweepMessage) nextErrors.variantContent = sweepMessage
    setErrors(nextErrors)
    // In fixed mode, block the whole submit until every variant has a price > 0.
    const nextPriceErrors =
      priceMode === "fixed" ? validateVariantPrices(variants.map((v) => v.key), priceFor) : {}
    setPriceErrors(nextPriceErrors)
    if (Object.keys(nextErrors).length > 0 || Object.keys(nextPriceErrors).length > 0) return
    if (baseUomId === null) {
      setSubmitError("No unit of measure exists yet — create one under Products → UOM before adding items.")
      return
    }

    setSubmitting(true)
    let created = 0
    try {
      for (const variant of variants) {
        const content = contentForVariant(variant)
        await itemsApi.create({
          sku: variant.sku,
          name: `${brandLabel ? brandLabel + " " : ""}${productLabel} - ${variant.parts.map((p) => p.value.label).join("/")}`,
          // Both FKs travel: the old code sent `subCategoryId ?? categoryId` as the
          // category, which lost the parent entirely. The server rejects a mismatched
          // pair with 422.
          categoryId: categoryId as number,
          subCategoryId,
          brandId,
          baseUomId,
          stockNature,
          trackingMode: "None",
          warranty,
          warrantyPeriodMonths: warranty === "Warranty" ? warrantyPeriodMonths : null,
          salePrice: priceMode === "fixed" ? Number(priceFor(variant.key)) : null,
          // Each variant carries its OWN size when a measurement dimension supplied one;
          // otherwise the shared form-level pair, which is correct when the varying dimension
          // isn't size (colour variants of one 500 ml bottle all hold 500 ml).
          contentQty: content?.qty ?? null,
          contentUnit: content?.unit ?? null,
        })
        created += 1
      }
      toast.success("Variants created", `${created} item${created === 1 ? "" : "s"} created`)
      router.push("/dashboard/products")
    } catch (err) {
      // Each row is its own POST with no transaction, so a failure partway (e.g. a
      // duplicate SKU) leaves the earlier rows created. Say so rather than implying
      // nothing happened.
      const detail = errorMessage(err)
      setSubmitError(
        created > 0
          ? `${detail} — ${created} item${created === 1 ? "" : "s"} were already created before this failed.`
          : detail,
      )
      toast.error("Could not create all variants", detail)
    } finally {
      setSubmitting(false)
    }
  }

  const loading = !categories || !brands || !itemTypes || !config

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <div>
          <h1 className="text-2xl font-bold text-foreground">New Item</h1>
          <p className="text-base text-muted-foreground">Category, subcategory, brand, and item types (FR-MD-01).</p>
        </div>
      </div>

      {loadError && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{loadError}</div>
      )}

      {loading && !loadError && <Skeleton className="h-64 w-full" />}

      {!loading && baseUomId === null && (
        <div className="rounded-lg border border-amber-300 bg-amber-50 p-5 text-base text-amber-900">
          No unit of measure exists yet. Items need a base UOM —{" "}
          <Link href="/dashboard/products/uoms" className="font-semibold underline">
            create one first
          </Link>
          .
        </div>
      )}

      {!loading && (
        <>
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div className="flex flex-col gap-2">
              <Label className="text-base">Product name</Label>
              <Input
                value={productName}
                onChange={(e) => setProductName(e.target.value)}
                placeholder="e.g. Coca Cola"
                aria-invalid={!!errors.productName}
                className="h-12! text-base"
              />
              <FieldError errors={[errors.productName ? { message: errors.productName } : undefined]} />
              <p className="text-sm text-muted-foreground">
                Names every variant and starts its SKU
                {productLabel ? ` — "${brandLabel ? brandLabel + " " : ""}${productLabel} - 500ml", SKU ${skuSegment(productLabel, 3)}-…` : "."}
              </p>
            </div>

            <div className="flex flex-col gap-2">
              <Label className="text-base">Category</Label>
              <Select<number | null>
                value={categoryId}
                onValueChange={handleCategoryChange}
                items={(categories ?? []).map((c) => ({ label: c.name, value: c.categoryId }))}
              >
                <SelectTrigger className="h-12! w-full text-base" aria-invalid={!!errors.categoryId}>
                  <SelectValue placeholder="Select category" />
                </SelectTrigger>
                <SelectContent>
                  {(categories ?? []).map((c) => (
                    <SelectItem key={c.categoryId} value={c.categoryId} className="text-base">
                      {c.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FieldError errors={[errors.categoryId ? { message: errors.categoryId } : undefined]} />
            </div>
            {/* Config flags are honoured by hiding the field: sending a gated value would
                just earn a 422 CONFIG_DISABLED (docs/11 §2.8). */}
            {config?.subcategoriesEnabled && (
              <div className="flex flex-col gap-2">
                <Label className="text-base">Subcategory (optional)</Label>
                <Select<number | null>
                  value={subCategoryId}
                  onValueChange={setSubCategoryId}
                  disabled={subCategories.length === 0}
                  items={subCategories.map((s) => ({ label: s.name, value: s.subCategoryId }))}
                >
                  <SelectTrigger className="h-12! w-full text-base">
                    <SelectValue placeholder={subCategories.length === 0 ? "No subcategories" : "Select subcategory"} />
                  </SelectTrigger>
                  <SelectContent>
                    {subCategories.map((s) => (
                      <SelectItem key={s.subCategoryId} value={s.subCategoryId} className="text-base">
                        {s.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
            {config?.brandsEnabled && (
              <div className="flex flex-col gap-2">
                <Label className="text-base">Brand (optional)</Label>
                <Select<number | null>
                  value={brandId}
                  onValueChange={setBrandId}
                  items={(brands ?? []).map((b) => ({ label: b.name, value: b.brandId }))}
                >
                  <SelectTrigger className="h-12! w-full text-base">
                    <SelectValue placeholder="Select brand" />
                  </SelectTrigger>
                  <SelectContent>
                    {(brands ?? []).map((b) => (
                      <SelectItem key={b.brandId} value={b.brandId} className="text-base">
                        {b.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
            <div className="flex flex-col gap-2">
              <Label className="text-base">Warehouse (optional)</Label>
              <Select<number | null>
                value={warehouseId}
                onValueChange={setWarehouseId}
                items={warehouses.map((w) => ({ label: `${w.code} — ${w.name}`, value: w.warehouseId }))}
              >
                <SelectTrigger className="h-12! w-full text-base">
                  <SelectValue placeholder="Select warehouse" />
                </SelectTrigger>
                <SelectContent>
                  {warehouses.map((w) => (
                    <SelectItem key={w.warehouseId} value={w.warehouseId} className="text-base">
                      {w.code} — {w.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex flex-col gap-2">
              <Label className="text-base">Base UOM</Label>
              <Select<number | null>
                value={baseUomId}
                onValueChange={setBaseUomId}
                items={uoms.map((u) => ({ label: u.name, value: u.uomId }))}
              >
                <SelectTrigger className="h-12! w-full text-base">
                  <SelectValue placeholder="Select base UOM" />
                </SelectTrigger>
                <SelectContent>
                  {uoms.map((u) => (
                    <SelectItem key={u.uomId} value={u.uomId} className="text-base">
                      {u.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {/* Content size (FR-MD-02): how much one stocked pack holds. Optional — a screw
                or a label has none. Litres/kilograms are normalised to ml/g by the server.
                Hidden once a measurement dimension is in play, because that dimension then
                gives each variant its own size and this pair would only contradict it. */}
            {showSharedContent && (
            <div className="flex flex-col gap-2">
              <Label className="text-base">Content size</Label>
              <div className="flex gap-2">
                <Input
                  type="number"
                  min="0"
                  step="any"
                  value={contentQty}
                  onChange={(e) => setContentQty(e.target.value)}
                  placeholder="e.g. 500"
                  aria-invalid={!!errors.contentQty}
                  className="h-12! text-base"
                />
                <Select<MeasureUnit | null>
                  value={contentUnit}
                  onValueChange={setContentUnit}
                  items={CONTENT_UNITS.map((u) => ({ label: u, value: u }))}
                >
                  <SelectTrigger className="h-12! w-28 shrink-0 text-base" aria-invalid={!!errors.contentUnit}>
                    <SelectValue placeholder="Unit" />
                  </SelectTrigger>
                  <SelectContent>
                    {CONTENT_UNITS.map((u) => (
                      <SelectItem key={u} value={u} className="text-base">
                        {u.toLowerCase()}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <FieldError
                errors={[
                  errors.contentQty ? { message: errors.contentQty } : undefined,
                  errors.contentUnit ? { message: errors.contentUnit } : undefined,
                ]}
              />
              <p className="text-sm text-muted-foreground">
                Applies to every variant. Leave blank for items with no measurable content — stock is
                counted in the base UOM either way.
              </p>
            </div>
            )}
            <div className="flex flex-col gap-2">
              <Label className="text-base">Stock nature</Label>
              <Select<StockNature> value={stockNature} onValueChange={(v) => v && setStockNature(v)}>
                <SelectTrigger className="h-12! w-full text-base">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Stocked" className="text-base">Stocked</SelectItem>
                  <SelectItem value="NonStocked" className="text-base">Non-stocked</SelectItem>
                  <SelectItem value="Service" className="text-base">Service</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* Sales pricing (FR-MD-01). The toggle is frontend-only: "stock" sends
              salePrice=null (sold at FIFO value); "fixed" requires a price per variant. */}
          <div className="flex flex-col gap-4 rounded-xl border p-5">
            <div>
              <h2 className="text-lg font-semibold text-foreground">Sale price</h2>
              <p className="text-sm text-muted-foreground">
                Choose a fixed selling price, or leave it to the item&apos;s stock value.
              </p>
            </div>

            <div className="inline-flex w-fit rounded-lg border p-1">
              <button
                type="button"
                onClick={() => setPriceMode("stock")}
                className={cn(
                  "rounded-md px-4 py-2 text-base font-medium transition-colors",
                  priceMode === "stock" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-muted/50",
                )}
              >
                Use stock value
              </button>
              <button
                type="button"
                onClick={() => setPriceMode("fixed")}
                className={cn(
                  "rounded-md px-4 py-2 text-base font-medium transition-colors",
                  priceMode === "fixed" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-muted/50",
                )}
              >
                Fixed price
              </button>
            </div>

            {priceMode === "fixed" && (
              <div className="flex max-w-xs flex-col gap-2">
                <Label className="text-base">Fix value (applies to all variants)</Label>
                <Input
                  type="number"
                  min="0"
                  step="0.01"
                  inputMode="decimal"
                  value={fixValue}
                  onChange={(e) => setFixValue(e.target.value)}
                  placeholder="0.00"
                  className="h-11 text-base"
                />
                <p className="text-sm text-muted-foreground">
                  Edit any row below to give that variant a different price.
                </p>
              </div>
            )}
          </div>

          {/* Warranty (FR-MD-01). Frontend-only toggle, mirrors the Sale price bar above. */}
          <div className="flex flex-col gap-4 rounded-xl border p-5">
            <div>
              <h2 className="text-lg font-semibold text-foreground">Warranty</h2>
              <p className="text-sm text-muted-foreground">
                Mark whether every generated variant is sold under warranty.
              </p>
            </div>

            <div className="inline-flex w-fit rounded-lg border p-1">
              <button
                type="button"
                onClick={() => {
                  setWarranty("NonWarranty")
                  setWarrantyPeriodMonths(null)
                }}
                className={cn(
                  "rounded-md px-4 py-2 text-base font-medium transition-colors",
                  warranty === "NonWarranty" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-muted/50",
                )}
              >
                Non-Warranty
              </button>
              <button
                type="button"
                onClick={() => setWarranty("Warranty")}
                className={cn(
                  "rounded-md px-4 py-2 text-base font-medium transition-colors",
                  warranty === "Warranty" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-muted/50",
                )}
              >
                Warranty
              </button>
            </div>

            {warranty === "Warranty" && (
              <div className="flex flex-col gap-1.5">
                <Label>Warranty period</Label>
                <Select<WarrantyPeriodMonths>
                  value={warrantyPeriodMonths}
                  onValueChange={(v) => v && setWarrantyPeriodMonths(v)}
                >
                  <SelectTrigger className="h-11! w-48 text-base" aria-invalid={!!errors.warrantyPeriodMonths}>
                    <SelectValue placeholder="Select period" />
                  </SelectTrigger>
                  <SelectContent>
                    {WARRANTY_PERIOD_MONTHS_OPTIONS.map((months) => (
                      <SelectItem key={months} value={months} className="text-base">
                        {months} months
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FieldError errors={[errors.warrantyPeriodMonths ? { message: errors.warrantyPeriodMonths } : undefined]} />
              </div>
            )}
          </div>

          {/* itemTypesEnabled is advisory — the server cannot enforce it (items hold no
              item-type reference), so this section IS the enforcement. */}
          {config?.itemTypesEnabled && (
          <div className="flex flex-col gap-4 rounded-xl border p-5">
            <div>
              <h2 className="text-lg font-semibold text-foreground">Item types</h2>
              <p className="text-sm text-muted-foreground">
                Check the item types that apply, then add their values to generate a SKU per combination.
              </p>
              {/* Without this, the per-size content feature is invisible: nothing is flagged as a
                  measurement out of the box, so the builder silently falls back to one shared
                  content size and the user has no reason to suspect another page is involved. */}
              {(itemTypes ?? []).length > 0 && !(itemTypes ?? []).some((t) => t.isMeasurable) && (
                <p className="mt-2 text-sm text-muted-foreground">
                  Selling the same product in several sizes (500 ml, 1 L)?{" "}
                  <Link href="/dashboard/products/item-types" className="font-medium underline">
                    Mark that item type as a measurement
                  </Link>{" "}
                  and each size will capture its own number and unit, giving every variant its own content size.
                </p>
              )}
            </div>

            <div className="flex flex-wrap items-center gap-4">
              {(itemTypes ?? []).map((t) => {
                const checked = checkedItemTypeIds.includes(t.itemTypeId)
                // Only one dimension may supply the content size, or a variant would have two.
                const blocked = t.isMeasurable && !checked && measurableCheckedCount > 0
                return (
                  <label
                    key={t.itemTypeId}
                    title={blocked ? "Only one measurement dimension can be used at a time." : undefined}
                    className={cn(
                      "flex items-center gap-2.5 rounded-lg border px-3 py-2",
                      blocked ? "opacity-50" : "hover:bg-muted/50"
                    )}
                  >
                    <Checkbox
                      checked={checked}
                      disabled={blocked}
                      onCheckedChange={() => toggleItemType(t.itemTypeId)}
                    />
                    <span className="text-base font-medium">{t.name}</span>
                    {t.isMeasurable && (
                      <Badge variant="outline" className="text-xs">measurement</Badge>
                    )}
                  </label>
                )
              })}
            </div>

            <FieldError
              errors={[
                errors.variants ? { message: errors.variants } : undefined,
                errors.measurable ? { message: errors.measurable } : undefined,
              ]}
            />

            {checkedItemTypeIds.length > 0 && (
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                {(itemTypes ?? [])
                  .filter((t) => checkedItemTypeIds.includes(t.itemTypeId))
                  .map((t) => {
                    const currentInput = inputByCategory[t.itemTypeId] ?? ""

                    return (
                      <div key={t.itemTypeId} className="flex flex-col gap-2">
                        <Label className="text-base">{t.name} values</Label>
                        {t.isMeasurable ? (
                          // A measurement is entered as a number + unit; the chip label, the SKU
                          // segment and the item's stored content size all derive from this pair.
                          <div className="flex gap-2">
                            <Input
                              type="number"
                              min="0"
                              step="any"
                              value={qtyByCategory[t.itemTypeId] ?? ""}
                              onChange={(e) => setQtyByCategory((prev) => ({ ...prev, [t.itemTypeId]: e.target.value }))}
                              onKeyDown={(e) => {
                                if (e.key === "Enter") {
                                  e.preventDefault()
                                  addValue(t.itemTypeId)
                                }
                              }}
                              placeholder="e.g. 500"
                              aria-invalid={!!valueErrors[t.itemTypeId]}
                              className="h-11 text-base"
                            />
                            <Select<MeasureUnit | null>
                              value={unitByCategory[t.itemTypeId] ?? null}
                              onValueChange={(v) => setUnitByCategory((prev) => ({ ...prev, [t.itemTypeId]: v }))}
                              items={CONTENT_UNITS.map((u) => ({ label: u, value: u }))}
                            >
                              <SelectTrigger className="h-11! w-24 shrink-0 text-base">
                                <SelectValue placeholder="Unit" />
                              </SelectTrigger>
                              <SelectContent>
                                {CONTENT_UNITS.map((u) => (
                                  <SelectItem key={u} value={u} className="text-base">
                                    {UNIT_LABEL[u]}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <Button type="button" variant="outline" onClick={() => addValue(t.itemTypeId)}>
                              <Plus className="size-4" />
                              Add
                            </Button>
                          </div>
                        ) : (
                          <div className="flex gap-2">
                            <Input
                              value={currentInput}
                              onChange={(e) => setInputByCategory((prev) => ({ ...prev, [t.itemTypeId]: e.target.value }))}
                              onKeyDown={(e) => {
                                if (e.key === "Enter") {
                                  e.preventDefault()
                                  addValue(t.itemTypeId)
                                }
                              }}
                              placeholder={t.name}
                              className="h-11 text-base"
                            />
                            <Button type="button" variant="outline" onClick={() => addValue(t.itemTypeId)}>
                              <Plus className="size-4" />
                              Add {t.name}
                            </Button>
                          </div>
                        )}
                        <FieldError
                          errors={[valueErrors[t.itemTypeId] ? { message: valueErrors[t.itemTypeId] } : undefined]}
                        />
                        <div className="flex flex-wrap gap-2">
                          {(valuesByCategory[t.itemTypeId] ?? []).map((v) => (
                            <Badge key={v.label} variant="outline" className="h-7 gap-1 pr-1 text-sm">
                              {v.label}
                              <button
                                type="button"
                                onClick={() => removeValue(t.itemTypeId, v.label)}
                                className="rounded-full p-0.5 hover:bg-muted"
                                aria-label={`Remove ${v.label}`}
                              >
                                <X className="size-3" />
                              </button>
                            </Badge>
                          ))}
                        </div>
                      </div>
                    )
                  })}
              </div>
            )}

            {/* Form-level, not per-row: a variant's content is derived, so there is no cell to
                attach this to. Should never appear — addValue rejects a bad pair at entry. */}
            <FieldError errors={[errors.variantContent ? { message: errors.variantContent } : undefined]} />

            {variants.length > 0 && (
              <div className="overflow-x-auto">
                <Table className="text-base">
                  <TableHeader>
                    <TableRow>
                      {activeCategories.map((cat) => (
                        <TableHead key={cat.itemTypeId} className="h-11 px-3 text-sm">{cat.name}</TableHead>
                      ))}
                      <TableHead className="h-11 px-3 text-sm">SKU</TableHead>
                      <TableHead className="h-11 px-3 text-sm">Content</TableHead>
                      {priceMode === "fixed" && (
                        <TableHead className="h-11 px-3 text-sm">Sale price</TableHead>
                      )}
                      {/* Quantity column removed 2026-07-17: there is no `initialQty` on the
                          Item contract and no initial-receipt flow — stock arrives via a GRN.
                          The input was informational-only under the mock and would now be a
                          field that silently discards what you type. */}
                      <TableHead className="h-11 w-8 px-1" />
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {variants.map((variant) => (
                      <TableRow key={variant.key}>
                        {variant.parts.map((part, i) => (
                          <TableCell key={i} className="px-3 py-2.5">
                            {part.value.label}
                          </TableCell>
                        ))}
                        <TableCell className="py-2.5 pr-1 pl-3 font-medium">{variant.sku}</TableCell>
                        {/* Read-only: content is derived, so an editable cell here could only
                            disagree with the value that produced it. */}
                        <TableCell className="px-3 py-2.5 text-muted-foreground">
                          {contentLabelFor(variant)}
                        </TableCell>
                        {priceMode === "fixed" && (
                          <TableCell className="px-3 py-2.5">
                            <Input
                              type="number"
                              min="0"
                              step="0.01"
                              inputMode="decimal"
                              value={priceFor(variant.key)}
                              onChange={(e) => {
                                const value = e.target.value
                                setPricesByKey((prev) => ({ ...prev, [variant.key]: value }))
                                setPriceErrors((prev) => {
                                  if (!prev[variant.key]) return prev
                                  const next = { ...prev }
                                  delete next[variant.key]
                                  return next
                                })
                              }}
                              placeholder="0.00"
                              aria-invalid={!!priceErrors[variant.key]}
                              className="h-10 w-28 text-base"
                            />
                            <FieldError errors={[priceErrors[variant.key] ? { message: priceErrors[variant.key] } : undefined]} />
                          </TableCell>
                        )}
                        <TableCell className="py-2.5 pr-3 pl-0">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon-sm"
                            onClick={() => removeVariant(variant.key)}
                            aria-label={`Remove ${variant.sku}`}
                            className="text-destructive hover:bg-destructive/10"
                          >
                            <X className="size-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </div>
          )}

          {submitError && (
            <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-base text-destructive">{submitError}</div>
          )}

          <div className="flex justify-end gap-3">
            <Link href="/dashboard/products" className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>
              Cancel
            </Link>
            <Button size="lg" type="button" onClick={handleSubmit} disabled={submitting}>
              {submitting ? "Creating…" : "Create Variants"}
            </Button>
          </div>
        </>
      )}
    </div>
  )
}
