"use client"

import { useState, useEffect, useMemo } from "react"
import { usePaginatedQuery, useQuery } from "convex/react"
import { api } from "../../../../../../convex/_generated/api"
import type { Id } from "../../../../../../convex/_generated/dataModel"
import Link from "next/link"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Button, buttonVariants } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { HugeiconsIcon } from "@hugeicons/react"
import {
  Search01Icon,
  Cancel01Icon,
  ArrowUpDownIcon,
  SortByUp01Icon,
  SortByDown01Icon,
  AddCircleIcon,
} from "@hugeicons/core-free-icons"
import {
  ProductPreviewDialog,
  type PreviewProduct,
} from "@/components/products/ProductPreviewDialog"
import { ProductActionsMenu } from "@/components/products/ProductActionsMenu"
import { cn } from "@/lib/utils"

// ─── Types ────────────────────────────────────────────────────────────────────

type SortField = "name" | "brand" | "childCategory"
type SortOrder = "asc" | "desc"
type ColumnKey = "brand" | "childCategory" | "status" | "slug" | "tags" | "updated"

const OPTIONAL_COLUMNS: { key: ColumnKey; label: string }[] = [
  { key: "brand", label: "Brand" },
  { key: "childCategory", label: "Category" },
  { key: "status", label: "Status" },
  { key: "slug", label: "Slug" },
  { key: "tags", label: "Tags" },
  { key: "updated", label: "Updated" },
]

const DEFAULT_VISIBLE: Record<ColumnKey, boolean> = {
  brand: true,
  childCategory: true,
  status: true,
  slug: true,
  tags: false,
  updated: false,
}

const STATUS_CONFIG = {
  active: { label: "Active", variant: "default" as const },
  draft: { label: "Draft", variant: "secondary" as const },
  archived: { label: "Archived", variant: "outline" as const },
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function SortableHeader({
  field,
  sortField,
  sortOrder,
  onSort,
  children,
}: {
  field: SortField
  sortField: SortField | null
  sortOrder: SortOrder
  onSort: (field: SortField) => void
  children: React.ReactNode
}) {
  const active = sortField === field
  return (
    <button
      type="button"
      className="flex items-center gap-1 hover:text-foreground"
      onClick={() => onSort(field)}
    >
      {children}
      <HugeiconsIcon
        icon={
          active
            ? sortOrder === "asc"
              ? SortByUp01Icon
              : SortByDown01Icon
            : ArrowUpDownIcon
        }
        strokeWidth={2}
        className={cn(
          "size-3.5",
          active ? "text-foreground" : "text-muted-foreground",
        )}
      />
    </button>
  )
}

function TableSkeleton({
  visibleCols,
}: {
  visibleCols: Record<ColumnKey, boolean>
}) {
  return (
    <>
      {Array.from({ length: 10 }).map((_, i) => (
        <TableRow key={i}>
          <TableCell>
            <Skeleton className="h-4 w-36" />
          </TableCell>
          {visibleCols.brand && (
            <TableCell>
              <Skeleton className="h-4 w-24" />
            </TableCell>
          )}
          {visibleCols.childCategory && (
            <TableCell>
              <Skeleton className="h-4 w-24" />
            </TableCell>
          )}
          {visibleCols.status && (
            <TableCell>
              <Skeleton className="h-5 w-16 rounded-full" />
            </TableCell>
          )}
          {visibleCols.slug && (
            <TableCell>
              <Skeleton className="h-4 w-32" />
            </TableCell>
          )}
          {visibleCols.tags && (
            <TableCell>
              <Skeleton className="h-4 w-20" />
            </TableCell>
          )}
          {visibleCols.updated && (
            <TableCell>
              <Skeleton className="h-4 w-28" />
            </TableCell>
          )}
          <TableCell>
            <Skeleton className="size-7 rounded-lg" />
          </TableCell>
        </TableRow>
      ))}
    </>
  )
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function ProductsPage() {
  const [searchInput, setSearchInput] = useState("")
  const [searchQuery, setSearchQuery] = useState("")
  const [visibleCols, setVisibleCols] =
    useState<Record<ColumnKey, boolean>>(DEFAULT_VISIBLE)
  const [sortField, setSortField] = useState<SortField | null>(null)
  const [sortOrder, setSortOrder] = useState<SortOrder>("asc")
  const [previewProduct, setPreviewProduct] = useState<PreviewProduct | null>(null)
  const [previewOpen, setPreviewOpen] = useState(false)

  // Debounce search input by 300ms
  useEffect(() => {
    const t = setTimeout(() => setSearchQuery(searchInput), 300)
    return () => clearTimeout(t)
  }, [searchInput])

  const isSearching = searchQuery.trim().length > 0

  const {
    results: listResults,
    status: listStatus,
    loadMore,
  } = usePaginatedQuery(api.products.list, {}, { initialNumItems: 25 })

  const searchResults = useQuery(
    api.products.search,
    isSearching ? { query: searchQuery, limit: 100 } : "skip",
  )

  const isLoading = isSearching
    ? searchResults === undefined
    : listStatus === "LoadingFirstPage"

  const rawProducts = useMemo(
    () => (isSearching ? (searchResults ?? []) : listResults),
    [isSearching, searchResults, listResults],
  )

  const products = useMemo(() => {
    if (!sortField) return rawProducts
    return [...rawProducts].sort((a: PreviewProduct, b: PreviewProduct) => {
      const aVal: string =
        sortField === "name"
          ? (a.name ?? "")
          : sortField === "brand"
            ? (a.brand ?? "")
            : (a.childCategorySlug ?? "")
      const bVal: string =
        sortField === "name"
          ? (b.name ?? "")
          : sortField === "brand"
            ? (b.brand ?? "")
            : (b.childCategorySlug ?? "")
      return sortOrder === "asc"
        ? aVal.localeCompare(bVal)
        : bVal.localeCompare(aVal)
    })
  }, [rawProducts, sortField, sortOrder])

  function handleSort(field: SortField) {
    if (sortField === field) {
      setSortOrder((o) => (o === "asc" ? "desc" : "asc"))
    } else {
      setSortField(field)
      setSortOrder("asc")
    }
  }

  function toggleColumn(key: ColumnKey, checked: boolean) {
    setVisibleCols((prev) => ({ ...prev, [key]: checked }))
  }

  function openPreview(product: PreviewProduct) {
    setPreviewProduct(product)
    setPreviewOpen(true)
  }

  const visibleOptionalCount = Object.values(visibleCols).filter(Boolean).length
  // Name + visible optional cols + Actions
  const totalColSpan = 1 + visibleOptionalCount + 1

  return (
    <main className="flex flex-1 flex-col gap-4 p-4 pt-0">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">Products</h1>
        <Link href="/products/new" className={buttonVariants()}>
          <HugeiconsIcon icon={AddCircleIcon} strokeWidth={2} />
          New product
        </Link>
      </div>

      {/* Toolbar */}
      <div className="flex items-center gap-2">
        <div className="relative max-w-sm flex-1">
          <HugeiconsIcon
            icon={Search01Icon}
            strokeWidth={2}
            className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
          />
          <Input
            placeholder="Search products…"
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            className="pl-8 pr-8"
          />
          {searchInput && (
            <button
              type="button"
              className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              onClick={() => setSearchInput("")}
              aria-label="Clear search"
            >
              <HugeiconsIcon
                icon={Cancel01Icon}
                strokeWidth={2}
                className="size-4"
              />
            </button>
          )}
        </div>

        <DropdownMenu>
          <DropdownMenuTrigger render={<Button variant="outline" size="sm" />}>
            Columns
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuGroup>
              <DropdownMenuLabel>Toggle columns</DropdownMenuLabel>
              <DropdownMenuSeparator />
              {OPTIONAL_COLUMNS.map(({ key, label }) => (
                <DropdownMenuCheckboxItem
                  key={key}
                  checked={visibleCols[key]}
                  onCheckedChange={(checked: boolean) =>
                    toggleColumn(key, checked)
                  }
                >
                  {label}
                </DropdownMenuCheckboxItem>
              ))}
            </DropdownMenuGroup>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* Table */}
      <div className="rounded-lg border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead scope="col">
                <SortableHeader
                  field="name"
                  sortField={sortField}
                  sortOrder={sortOrder}
                  onSort={handleSort}
                >
                  Name
                </SortableHeader>
              </TableHead>
              {visibleCols.brand && (
                <TableHead scope="col">
                  <SortableHeader
                    field="brand"
                    sortField={sortField}
                    sortOrder={sortOrder}
                    onSort={handleSort}
                  >
                    Brand
                  </SortableHeader>
                </TableHead>
              )}
              {visibleCols.childCategory && (
                <TableHead scope="col">
                  <SortableHeader
                    field="childCategory"
                    sortField={sortField}
                    sortOrder={sortOrder}
                    onSort={handleSort}
                  >
                    Category
                  </SortableHeader>
                </TableHead>
              )}
              {visibleCols.status && (
                <TableHead scope="col">Status</TableHead>
              )}
              {visibleCols.slug && <TableHead scope="col">Slug</TableHead>}
              {visibleCols.tags && <TableHead scope="col">Tags</TableHead>}
              {visibleCols.updated && (
                <TableHead scope="col">Updated</TableHead>
              )}
              <TableHead scope="col" className="w-10" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableSkeleton visibleCols={visibleCols} />
            ) : products.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={totalColSpan}
                  className="py-16 text-center text-sm text-muted-foreground"
                >
                  {isSearching
                    ? `No products match "${searchQuery}".`
                    : "No products yet. Create your first product to get started."}
                </TableCell>
              </TableRow>
            ) : (
              products.map((product: PreviewProduct) => {
                const statusCfg =
                  STATUS_CONFIG[product.status as keyof typeof STATUS_CONFIG]
                return (
                  <TableRow key={product._id}>
                    <TableCell>
                      <button
                        type="button"
                        className="font-medium hover:underline text-left"
                        onClick={() => openPreview(product)}
                      >
                        {product.name}
                      </button>
                    </TableCell>
                    {visibleCols.brand && (
                      <TableCell className="text-muted-foreground">
                        {product.brand ?? "—"}
                      </TableCell>
                    )}
                    {visibleCols.childCategory && (
                      <TableCell className="text-muted-foreground">
                        {product.childCategorySlug ?? "—"}
                      </TableCell>
                    )}
                    {visibleCols.status && (
                      <TableCell>
                        {statusCfg ? (
                          <Badge variant={statusCfg.variant}>
                            {statusCfg.label}
                          </Badge>
                        ) : (
                          <span className="text-muted-foreground">
                            {product.status}
                          </span>
                        )}
                      </TableCell>
                    )}
                    {visibleCols.slug && (
                      <TableCell className="font-mono text-xs text-muted-foreground">
                        {product.slug}
                      </TableCell>
                    )}
                    {visibleCols.tags && (
                      <TableCell className="text-muted-foreground">
                        {product.tags?.length > 0
                          ? product.tags.join(", ")
                          : "—"}
                      </TableCell>
                    )}
                    {visibleCols.updated && (
                      <TableCell className="whitespace-nowrap text-xs text-muted-foreground">
                        {product.updatedAt
                          ? new Date(product.updatedAt).toLocaleDateString()
                          : "—"}
                      </TableCell>
                    )}
                    <TableCell>
                      <ProductActionsMenu
                        productId={product._id as Id<"products">}
                        productName={product.name}
                        isArchived={product.status === "archived"}
                      />
                    </TableCell>
                  </TableRow>
                )
              })
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination footer — list mode only */}
      {!isSearching && (
        <div className="flex items-center justify-between text-sm text-muted-foreground">
          <span>
            {listStatus === "Exhausted"
              ? `${listResults.length} product${listResults.length !== 1 ? "s" : ""} total`
              : `${listResults.length} loaded`}
          </span>
          {listStatus === "CanLoadMore" && (
            <Button variant="outline" size="sm" onClick={() => loadMore(25)}>
              Load more
            </Button>
          )}
        </div>
      )}

      <ProductPreviewDialog
        product={previewProduct}
        open={previewOpen}
        onOpenChange={setPreviewOpen}
      />
    </main>
  )
}
