"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { ChevronLeft, ChevronRight, ListTree, Package, Pencil, Plus, Ruler, Search } from "lucide-react"

import { itemsApi } from "@/lib/api/items"
import { categoriesApi } from "@/lib/api/categories"
import { brandsApi } from "@/lib/api/brands"
import { productConfig } from "@/lib/api/product-config"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { EntityStatus, PaginationMeta } from "@/types/common"
import { Brand, Category, ItemListItem, ProductConfig, SubCategory, TrackingMode } from "@/types/master-data"

import { Badge } from "@/components/ui/badge"
import { Button, buttonVariants } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
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"

type StatusFilter = EntityStatus | "All"
type TrackingFilter = TrackingMode | "All"

const PAGE_SIZE = 10

export default function ItemsPage() {
  const [items, setItems] = useState<ItemListItem[] | null>(null)
  const [categories, setCategories] = useState<Category[]>([])
  const [subCategories, setSubCategories] = useState<SubCategory[]>([])
  const [brands, setBrands] = useState<Brand[]>([])
  const [config, setConfig] = useState<ProductConfig | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [searchInput, setSearchInput] = useState("")
  const [query, setQuery] = useState("")
  const [status, setStatus] = useState<StatusFilter>("All")
  const [categoryId, setCategoryId] = useState<number | "All">("All")
  const [trackingMode, setTrackingMode] = useState<TrackingFilter>("All")
  const [page, setPage] = useState(1)

  useEffect(() => {
    const timeout = setTimeout(() => setQuery(searchInput.trim()), 300)
    return () => clearTimeout(timeout)
  }, [searchInput])

  useEffect(() => setPage(1), [query, status, categoryId, trackingMode])

  function load() {
    setError(null)
    itemsApi
      .list({
        page,
        pageSize: PAGE_SIZE,
        q: query || undefined,
        status: status === "All" ? undefined : status,
        categoryId: categoryId === "All" ? undefined : categoryId,
        trackingMode: trackingMode === "All" ? undefined : trackingMode,
      })
      .then((res) => {
        setItems(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }

  useEffect(load, [page, query, status, categoryId, trackingMode])
  useEffect(() => {
    categoriesApi.list().then((res) => setCategories(res.items)).catch(() => {})
    brandsApi.list({ pageSize: 200 }).then((res) => setBrands(res.items)).catch(() => {})
    productConfig().then(setConfig).catch(() => {})
  }, [])

  // No "list all subcategories" endpoint exists — they're scoped per category — so once
  // categories are in, fetch each one's subcategories in parallel to build a flat lookup.
  useEffect(() => {
    if (categories.length === 0) return
    Promise.all(
      categories.map((c) =>
        categoriesApi.listSubCategories(c.categoryId, { pageSize: 200 }).catch(() => ({ items: [] as SubCategory[] }))
      )
    ).then((results) => setSubCategories(results.flatMap((r) => r.items)))
  }, [categories])

  function categoryName(id: number) {
    return categories.find((c) => c.categoryId === id)?.name ?? `#${id}`
  }

  function subCategoryName(id: number) {
    return subCategories.find((s) => s.subCategoryId === id)?.name ?? `#${id}`
  }

  function brandName(id: number) {
    return brands.find((b) => b.brandId === id)?.name ?? `#${id}`
  }

  const hasFilters = query.length > 0 || status !== "All" || categoryId !== "All" || trackingMode !== "All"

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Items</h1>
          <p className="text-base text-muted-foreground">Item master — SKU, tracking mode, category, default vendor (FR-MD-01).</p>
        </div>
        <div className="flex items-center gap-2">
          <Link href="/dashboard/products/uoms" className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>
            <Ruler className="size-5" />
            UOMs
          </Link>
          <Link href="/dashboard/products/categories" className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>
            <ListTree className="size-5" />
            Categories
          </Link>
          <Link href="/dashboard/products/new" className={cn(buttonVariants({ size: "lg" }))}>
            <Plus className="size-5" />
            New Item
          </Link>
        </div>
      </div>

      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <div className="relative flex-1 basis-0">
          <Search className="pointer-events-none absolute top-1/2 left-4 size-5 -translate-y-1/2 text-muted-foreground" />
          <Input
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            placeholder="Search SKU or name…"
            className="h-14 w-full pl-11 text-base"
            aria-label="Search items"
          />
        </div>
        <Select<number | "All">
          value={categoryId}
          onValueChange={(v) => setCategoryId(v ?? "All")}
          items={[{ label: "All categories", value: "All" as const }, ...categories.map((c) => ({ label: c.name, value: c.categoryId }))]}
        >
          <SelectTrigger className="h-14! w-full flex-1 basis-0 text-base">
            <SelectValue placeholder="All categories" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="All" className="text-base">All categories</SelectItem>
            {categories.map((c) => (
              <SelectItem key={c.categoryId} value={c.categoryId} className="text-base">
                {c.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select<TrackingFilter> value={trackingMode} onValueChange={(v) => setTrackingMode(v ?? "All")}>
          <SelectTrigger className="h-14! w-full flex-1 basis-0 text-base">
            <SelectValue placeholder="All tracking modes" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="All" className="text-base">All tracking modes</SelectItem>
            <SelectItem value="None" className="text-base">None</SelectItem>
            <SelectItem value="Batch" className="text-base">Batch</SelectItem>
            <SelectItem value="Serial" className="text-base">Serial</SelectItem>
          </SelectContent>
        </Select>
        <Select<StatusFilter> value={status} onValueChange={(v) => setStatus(v ?? "All")}>
          <SelectTrigger className="h-14! w-full flex-1 basis-0 text-base">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="All" className="text-base">All statuses</SelectItem>
            <SelectItem value="Active" className="text-base">Active</SelectItem>
            <SelectItem value="Inactive" className="text-base">Inactive</SelectItem>
          </SelectContent>
        </Select>
      </div>

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

      {!error && items === null && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 5 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      )}

      {!error && items !== null && items.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <Package className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">{hasFilters ? "No items match your search/filter." : "No items yet."}</p>
          {!hasFilters && (
            <Link href="/dashboard/products/new" className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>
              <Plus className="size-5" />
              New Item
            </Link>
          )}
        </div>
      )}

      {!error && items !== null && items.length > 0 && (
        <>
          <Table className="text-base">
            <TableHeader>
              <TableRow>
                <TableHead className="h-12 px-3 text-sm">SKU</TableHead>
                <TableHead className="h-12 px-3 text-sm">Name</TableHead>
                <TableHead className="h-12 px-3 text-sm">Category</TableHead>
                {config?.subcategoriesEnabled && <TableHead className="h-12 px-3 text-sm">Subcategory</TableHead>}
                {config?.brandsEnabled && <TableHead className="h-12 px-3 text-sm">Brand</TableHead>}
                <TableHead className="h-12 px-3 text-sm">Type</TableHead>
                <TableHead className="h-12 px-3 text-sm">Tracking</TableHead>
                <TableHead className="h-12 px-3 text-sm">Status</TableHead>
                <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {items.map((item) => (
                <TableRow key={item.itemId}>
                  <TableCell className="px-3 py-3.5 font-medium">
                    <Link href={`/dashboard/products/${item.itemId}`} className="hover:underline">
                      {item.sku}
                    </Link>
                  </TableCell>
                  <TableCell className="px-3 py-3.5">{item.name}</TableCell>
                  <TableCell className="px-3 py-3.5">{categoryName(item.categoryId)}</TableCell>
                  {config?.subcategoriesEnabled && (
                    <TableCell className="px-3 py-3.5 text-muted-foreground">
                      {item.subCategoryId !== null ? subCategoryName(item.subCategoryId) : "—"}
                    </TableCell>
                  )}
                  {config?.brandsEnabled && (
                    <TableCell className="px-3 py-3.5 text-muted-foreground">
                      {item.brandId !== null ? brandName(item.brandId) : "—"}
                    </TableCell>
                  )}
                  <TableCell className="px-3 py-3.5">{item.stockNature}</TableCell>
                  <TableCell className="px-3 py-3.5">{item.trackingMode}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <Badge
                      variant="outline"
                      className={cn(
                        "h-6 w-fit justify-center border-transparent px-2.5 text-sm",
                        item.status === "Active" ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive"
                      )}
                    >
                      {item.status}
                    </Badge>
                  </TableCell>
                  <TableCell className="px-3 py-3.5">
                    <Link
                      href={`/dashboard/products/${item.itemId}`}
                      className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))}
                      aria-label={`Edit ${item.sku}`}
                    >
                      <Pencil className="size-4" />
                    </Link>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>

          {pagination && pagination.totalPages > 1 && (
            <div className="flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                Showing {(pagination.page - 1) * pagination.pageSize + 1}–
                {Math.min(pagination.page * pagination.pageSize, pagination.totalItems)} of {pagination.totalItems}
              </p>
              <div className="flex items-center gap-2">
                <Button type="button" variant="outline" size="sm" disabled={pagination.page <= 1} onClick={() => setPage((p) => Math.max(1, p - 1))}>
                  <ChevronLeft />
                  Previous
                </Button>
                <span className="text-sm text-muted-foreground">Page {pagination.page} of {pagination.totalPages}</span>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  disabled={pagination.page >= pagination.totalPages}
                  onClick={() => setPage((p) => Math.min(pagination.totalPages, p + 1))}
                >
                  Next
                  <ChevronRight />
                </Button>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  )
}
