"use client"

import { useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { ArrowLeft, 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 { validateVariantItemForm, validateVariantPrices } from "@/lib/validations/master-data"
import { cn } from "@/lib/utils"
import { Brand, Category, ItemType, ProductConfig, StockNature, SubCategory } from "@/types/master-data"

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"
}

function buildVariantSku(categoryLabel: string, values: string[]): string {
  return [skuSegment(categoryLabel, 3), ...values.map((v) => skuSegment(v, 3))].join("-")
}

/** The item builder only ever offers these two dimensions, regardless of what else exists
 * in the Item Types master list. */
const BUILDER_ITEM_TYPES = ["color", "size"]
function isBuilderItemType(name: string): boolean {
  return BUILDER_ITEM_TYPES.includes(name.trim().toLowerCase())
}

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)
  const [stockNature, setStockNature] = useState<StockNature>("Stocked")
  const [loadError, setLoadError] = useState<string | null>(null)

  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, string[]>>({})
  const [inputByCategory, setInputByCategory] = 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>>({})

  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 categoryLabel = (categories ?? []).find((c) => c.categoryId === categoryId)?.name ?? ""
  const subCategoryLabel = subCategories.find((s) => s.subCategoryId === subCategoryId)?.name ?? ""
  /** SKU/name read best off the most specific level, but BOTH ids are sent to the server. */
  const effectiveLabel = subCategoryLabel || categoryLabel
  const brandLabel = (brands ?? []).find((b) => b.brandId === brandId)?.name ?? ""

  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]
    )
  }

  function addValue(itemTypeId: number) {
    const value = (inputByCategory[itemTypeId] ?? "").trim()
    if (value) {
      setValuesByCategory((prev) => {
        const existing = prev[itemTypeId] ?? []
        if (existing.some((v) => v.toLowerCase() === value.toLowerCase())) return prev
        return { ...prev, [itemTypeId]: [...existing, value] }
      })
    }
    setInputByCategory((prev) => ({ ...prev, [itemTypeId]: "" }))
  }

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

  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: string }[] }[] = [{ 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}` : value,
            parts: [...combo.parts, { name: cat.name, value }],
          })
        }
      }
      combinations = next
    }
    return combinations.map((c) => ({
      ...c,
      sku: buildVariantSku(effectiveLabel, c.parts.map((p) => p.value)),
    }))
  }, [activeCategories, effectiveLabel])

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

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

  async function handleSubmit() {
    setSubmitError(null)
    const nextErrors = validateVariantItemForm({ categoryId, hasVariants: variants.length > 0 })
    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) {
        await itemsApi.create({
          sku: variant.sku,
          name: `${brandLabel ? brandLabel + " " : ""}${effectiveLabel} - ${variant.parts.map((p) => p.value).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",
          salePrice: priceMode === "fixed" ? Number(priceFor(variant.key)) : 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">
        <Link href="/dashboard/products" className={cn(buttonVariants({ variant: "ghost", size: "icon-lg" }))}>
          <ArrowLeft className="size-5" />
        </Link>
        <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">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>
            <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>

          {/* 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>
            </div>

            <div className="flex flex-wrap items-center gap-4">
              {(itemTypes ?? [])
                .filter((t) => isBuilderItemType(t.name))
                .map((t) => (
                  <label key={t.itemTypeId} className="flex items-center gap-2.5 rounded-lg border px-3 py-2 hover:bg-muted/50">
                    <Checkbox
                      checked={checkedItemTypeIds.includes(t.itemTypeId)}
                      onCheckedChange={() => toggleItemType(t.itemTypeId)}
                    />
                    <span className="text-base font-medium">{t.name}</span>
                  </label>
                ))}
            </div>

            <FieldError errors={[errors.variants ? { message: errors.variants } : 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>
                        <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>
                        <div className="flex flex-wrap gap-2">
                          {(valuesByCategory[t.itemTypeId] ?? []).map((v) => (
                            <Badge key={v} variant="outline" className="h-7 gap-1 pr-1 text-sm">
                              {v}
                              <button
                                type="button"
                                onClick={() => removeValue(t.itemTypeId, v)}
                                className="rounded-full p-0.5 hover:bg-muted"
                                aria-label={`Remove ${v}`}
                              >
                                <X className="size-3" />
                              </button>
                            </Badge>
                          ))}
                        </div>
                      </div>
                    )
                  })}
              </div>
            )}

            {variants.length > 0 && (
              <div className="overflow-x-auto">
                <Table className="text-base">
                  <TableHeader className="bg-indigo-50">
                    <TableRow className="hover:bg-indigo-50">
                      {activeCategories.map((cat) => (
                        <TableHead key={cat.itemTypeId} className="h-11 px-3 text-sm text-indigo-700">{cat.name}</TableHead>
                      ))}
                      <TableHead className="h-11 px-3 text-sm text-indigo-700">SKU</TableHead>
                      {priceMode === "fixed" && (
                        <TableHead className="h-11 px-3 text-sm text-indigo-700">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}
                          </TableCell>
                        ))}
                        <TableCell className="py-2.5 pr-1 pl-3 font-medium">{variant.sku}</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>
  )
}
