"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 { variantCategoriesApi } from "@/lib/api/variants"
import { errorMessage } from "@/lib/error-map"
import { validateVariantCategoryName, validateVariantItemForm } from "@/lib/validations/master-data"
import { cn } from "@/lib/utils"
import { Category, VariantCategory } 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("-")
}

function isColorCategory(categoryName: string): boolean {
  return categoryName.trim().toLowerCase() === "color"
}

function encodeColorValue(name: string, hex: string): string {
  return `${name}|${hex}`
}

function decodeColorValue(value: string): { name: string; hex: string } {
  const separatorIndex = value.indexOf("|")
  if (separatorIndex === -1) return { name: value, hex: "#d4d4d8" }
  return { name: value.slice(0, separatorIndex), hex: value.slice(separatorIndex + 1) }
}

function partLabel(part: { name: string; value: string }): string {
  return isColorCategory(part.name) ? decodeColorValue(part.value).name : part.value
}

// No Base UOM field on this form — every variant created here uses the base "EA" unit (uomId 1 in the seed data).
const DEFAULT_BASE_UOM_ID = 1

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

  const [categories, setCategories] = useState<Category[] | null>(null)
  const [brands, setBrands] = useState<{ brandId: number; name: string }[] | null>(null)
  const [variantCategories, setVariantCategories] = useState<VariantCategory[] | null>(null)
  const [loadError, setLoadError] = useState<string | null>(null)

  const [categoryId, setCategoryId] = useState<number | null>(null)
  const [subCategoryId, setSubCategoryId] = useState<number | null>(null)
  const [brandId, setBrandId] = useState<number | null>(null)

  const [checkedVariantCategoryIds, setCheckedVariantCategoryIds] = useState<number[]>([])
  const [valuesByCategory, setValuesByCategory] = useState<Record<number, string[]>>({})
  const [inputByCategory, setInputByCategory] = useState<Record<number, string>>({})
  const [colorNameByCategory, setColorNameByCategory] = useState<Record<number, string>>({})
  const [quantities, setQuantities] = useState<Record<string, string>>({})

  const [addingCategory, setAddingCategory] = useState(false)
  const [newCategoryName, setNewCategoryName] = useState("")
  const [newCategoryError, setNewCategoryError] = useState<string | null>(null)
  const [addingCategorySubmitting, setAddingCategorySubmitting] = useState(false)

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

  useEffect(() => {
    Promise.all([categoriesApi.list({ pageSize: 200 }), brandsApi.list({ pageSize: 200 }), variantCategoriesApi.list()])
      .then(([cat, br, vc]) => {
        setCategories(cat.items)
        setBrands(br.items)
        setVariantCategories(vc.items)
      })
      .catch((err) => setLoadError(errorMessage(err)))
  }, [])

  const topCategories = useMemo(() => (categories ?? []).filter((c) => c.parentId === null), [categories])
  const subCategoryOptions = useMemo(
    () => (categories ?? []).filter((c) => c.parentId === categoryId),
    [categories, categoryId]
  )
  const effectiveCategoryId = subCategoryId ?? categoryId
  const effectiveCategoryLabel =
    (categories ?? []).find((c) => c.categoryId === effectiveCategoryId)?.name ?? ""
  const brandLabel = (brands ?? []).find((b) => b.brandId === brandId)?.name ?? ""

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

  function toggleVariantCategory(variantCategoryId: number) {
    setCheckedVariantCategoryIds((prev) =>
      prev.includes(variantCategoryId) ? prev.filter((id) => id !== variantCategoryId) : [...prev, variantCategoryId]
    )
    setQuantities({})
  }

  async function handleAddVariantCategory() {
    const nextErrors = validateVariantCategoryName(newCategoryName)
    if (nextErrors.name) {
      setNewCategoryError(nextErrors.name)
      return
    }
    setAddingCategorySubmitting(true)
    try {
      const category = await variantCategoriesApi.create({ name: newCategoryName })
      setVariantCategories((prev) => [...(prev ?? []), category])
      setCheckedVariantCategoryIds((prev) => [...prev, category.variantCategoryId])
      setNewCategoryName("")
      setNewCategoryError(null)
      setAddingCategory(false)
      toast.success("Variant category created", category.name)
    } catch (err) {
      setNewCategoryError(errorMessage(err))
    } finally {
      setAddingCategorySubmitting(false)
    }
  }

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

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

  const activeCategories = useMemo(
    () =>
      (variantCategories ?? [])
        .filter((vc) => checkedVariantCategoryIds.includes(vc.variantCategoryId))
        .map((vc) => ({ ...vc, values: valuesByCategory[vc.variantCategoryId] ?? [] }))
        .filter((vc) => vc.values.length > 0),
    [variantCategories, checkedVariantCategoryIds, valuesByCategory]
  )

  const variants = 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(effectiveCategoryLabel, c.parts.map(partLabel)),
    }))
  }, [activeCategories, effectiveCategoryLabel])

  async function handleSubmit() {
    setSubmitError(null)
    const nextErrors = validateVariantItemForm({ categoryId: effectiveCategoryId, hasVariants: variants.length > 0 })
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setSubmitting(true)
    try {
      let created = 0
      for (const variant of variants) {
        const qty = Number(quantities[variant.key] || 0)
        await itemsApi.create({
          sku: variant.sku,
          name: `${brandLabel ? brandLabel + " " : ""}${effectiveCategoryLabel} - ${variant.parts.map(partLabel).join("/")}`,
          categoryId: effectiveCategoryId as number,
          brandId,
          baseUomId: DEFAULT_BASE_UOM_ID,
          itemType: "Stocked",
          trackingMode: "None",
          initialQty: Number.isFinite(qty) ? qty : 0,
        })
        created += 1
      }
      toast.success("Variants created", `${created} item${created === 1 ? "" : "s"} created`)
      router.push("/dashboard/products")
    } catch (err) {
      setSubmitError(errorMessage(err))
      toast.error("Could not create variants", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  const loading = !categories || !brands || !variantCategories

  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 variant categories (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 && (
        <>
          <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}>
                <SelectTrigger className="h-12! w-full text-base" aria-invalid={!!errors.categoryId}>
                  <SelectValue placeholder="Select category" />
                </SelectTrigger>
                <SelectContent>
                  {topCategories.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>
            <div className="flex flex-col gap-2">
              <Label className="text-base">Subcategory (optional)</Label>
              <Select<number | null> value={subCategoryId} onValueChange={setSubCategoryId} disabled={subCategoryOptions.length === 0}>
                <SelectTrigger className="h-12! w-full text-base">
                  <SelectValue placeholder={subCategoryOptions.length === 0 ? "No subcategories" : "Select subcategory"} />
                </SelectTrigger>
                <SelectContent>
                  {subCategoryOptions.map((c) => (
                    <SelectItem key={c.categoryId} value={c.categoryId} className="text-base">
                      {c.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex flex-col gap-2">
              <Label className="text-base">Brand (optional)</Label>
              <Select<number | null> value={brandId} onValueChange={setBrandId}>
                <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>

          <div className="flex flex-col gap-4 rounded-xl border p-5">
            <div>
              <h2 className="text-lg font-semibold text-foreground">Variants</h2>
              <p className="text-sm text-muted-foreground">
                Check the variant categories that apply, then add their values to generate a SKU per combination.
              </p>
            </div>

            <div className="flex flex-wrap items-center gap-4">
              {(variantCategories ?? []).map((vc) => (
                <label key={vc.variantCategoryId} className="flex items-center gap-2.5 rounded-lg border px-3 py-2 hover:bg-muted/50">
                  <Checkbox
                    checked={checkedVariantCategoryIds.includes(vc.variantCategoryId)}
                    onCheckedChange={() => toggleVariantCategory(vc.variantCategoryId)}
                  />
                  <span className="text-base font-medium">{vc.name}</span>
                </label>
              ))}
              {!addingCategory && (
                <Button
                  type="button"
                  variant="outline"
                  size="icon-sm"
                  aria-label="Add another variant category"
                  onClick={() => setAddingCategory(true)}
                >
                  <Plus className="size-4" />
                </Button>
              )}
            </div>

            {addingCategory && (
              <div className="flex flex-col gap-2">
                <div className="flex gap-2">
                  <Input
                    value={newCategoryName}
                    onChange={(e) => setNewCategoryName(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") {
                        e.preventDefault()
                        handleAddVariantCategory()
                      }
                    }}
                    placeholder="Material"
                    className="h-11 max-w-xs text-base"
                    aria-invalid={!!newCategoryError}
                    autoFocus
                  />
                  <Button type="button" onClick={handleAddVariantCategory} disabled={addingCategorySubmitting}>
                    <Plus className="size-4" />
                    Add
                  </Button>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    aria-label="Cancel"
                    onClick={() => {
                      setAddingCategory(false)
                      setNewCategoryName("")
                      setNewCategoryError(null)
                    }}
                  >
                    <X className="size-4" />
                  </Button>
                </div>
                <FieldError errors={[newCategoryError ? { message: newCategoryError } : undefined]} />
              </div>
            )}

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

            {checkedVariantCategoryIds.length > 0 && (
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                {(variantCategories ?? [])
                  .filter((vc) => checkedVariantCategoryIds.includes(vc.variantCategoryId))
                  .map((vc) => {
                    const isColor = isColorCategory(vc.name)
                    const currentInput = inputByCategory[vc.variantCategoryId] ?? ""
                    const currentColorName = colorNameByCategory[vc.variantCategoryId] ?? ""

                    function addColor() {
                      const name = currentColorName.trim()
                      if (!name) return
                      addValue(vc.variantCategoryId, encodeColorValue(name, currentInput || "#EF4444"))
                      setColorNameByCategory((prev) => ({ ...prev, [vc.variantCategoryId]: "" }))
                    }

                    return (
                      <div key={vc.variantCategoryId} className="flex flex-col gap-2">
                        <Label className="text-base">{vc.name} values</Label>
                        <div className="flex gap-2">
                          {isColor ? (
                            <>
                              <input
                                type="color"
                                value={currentInput || "#EF4444"}
                                onChange={(e) => setInputByCategory((prev) => ({ ...prev, [vc.variantCategoryId]: e.target.value }))}
                                className="h-11 w-11 shrink-0 cursor-pointer rounded-md border border-input p-0.5"
                                aria-label="Pick color"
                              />
                              <Input
                                value={currentColorName}
                                onChange={(e) => setColorNameByCategory((prev) => ({ ...prev, [vc.variantCategoryId]: e.target.value }))}
                                onKeyDown={(e) => {
                                  if (e.key === "Enter") {
                                    e.preventDefault()
                                    addColor()
                                  }
                                }}
                                placeholder="Color name (e.g. Red)"
                                className="h-11 text-base"
                              />
                            </>
                          ) : (
                            <Input
                              value={currentInput}
                              onChange={(e) => setInputByCategory((prev) => ({ ...prev, [vc.variantCategoryId]: e.target.value }))}
                              onKeyDown={(e) => {
                                if (e.key === "Enter") {
                                  e.preventDefault()
                                  addValue(vc.variantCategoryId)
                                }
                              }}
                              placeholder={vc.name}
                              className="h-11 text-base"
                            />
                          )}
                          <Button type="button" variant="outline" onClick={() => (isColor ? addColor() : addValue(vc.variantCategoryId))}>
                            <Plus className="size-4" />
                            Add {vc.name}
                          </Button>
                        </div>
                        <div className="flex flex-wrap gap-2">
                          {(valuesByCategory[vc.variantCategoryId] ?? []).map((v) => {
                            const decoded = isColor ? decodeColorValue(v) : null
                            return (
                              <Badge key={v} variant="outline" className="h-7 gap-1 pr-1 text-sm">
                                {decoded && (
                                  <span
                                    className="size-3.5 shrink-0 rounded-full border border-black/10"
                                    style={{ backgroundColor: decoded.hex }}
                                    aria-hidden="true"
                                  />
                                )}
                                {decoded ? decoded.name : v}
                                <button
                                  type="button"
                                  onClick={() => removeValue(vc.variantCategoryId, v)}
                                  className="rounded-full p-0.5 hover:bg-muted"
                                  aria-label={`Remove ${decoded ? decoded.name : 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.variantCategoryId} 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>
                      <TableHead className="h-11 px-3 text-sm text-indigo-700">Quantity</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {variants.map((variant) => (
                      <TableRow key={variant.key}>
                        {variant.parts.map((part, i) => {
                          const decoded = isColorCategory(part.name) ? decodeColorValue(part.value) : null
                          return (
                            <TableCell key={i} className="px-3 py-2.5">
                              <span className="inline-flex items-center gap-1.5">
                                {decoded && (
                                  <span
                                    className="size-3.5 shrink-0 rounded-full border border-black/10"
                                    style={{ backgroundColor: decoded.hex }}
                                    aria-hidden="true"
                                  />
                                )}
                                {partLabel(part)}
                              </span>
                            </TableCell>
                          )
                        })}
                        <TableCell className="px-3 py-2.5 font-medium">{variant.sku}</TableCell>
                        <TableCell className="px-3 py-2.5">
                          <Input
                            type="number"
                            min="0"
                            value={quantities[variant.key] ?? ""}
                            onChange={(e) => setQuantities((prev) => ({ ...prev, [variant.key]: e.target.value }))}
                            placeholder="0"
                            className="h-9 w-24 text-sm"
                          />
                        </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>
  )
}
