"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { ArrowDown, ArrowUp, ArrowUpDown, Ban, CheckCircle2, ChevronLeft, ChevronRight, ListTree, Network, Pencil, Plus, Search } from "lucide-react"

import { categoriesApi } from "@/lib/api/categories"
import { errorMessage } from "@/lib/error-map"
import { validateCategoryName } from "@/lib/validations/master-data"
import { cn } from "@/lib/utils"
import { EntityStatus, PaginationMeta } from "@/types/common"
import { Category } from "@/types/master-data"

import { AlertDialog, AlertDialogContent, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import { Button, buttonVariants } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
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"

type SortOrder = "asc" | "desc"
type SortKey = "categoryId" | "name" | "status" | "createdAt"
type StatusFilter = EntityStatus | "All"

const PAGE_SIZE = 5

export default function CategoriesPage() {
  const [categories, setCategories] = useState<Category[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [searchInput, setSearchInput] = useState("")
  const [search, setSearch] = useState("")
  const [status, setStatus] = useState<StatusFilter>("All")
  const [page, setPage] = useState(1)
  // Sorts only the currently loaded page client-side — the backend ignores `sort` and
  // always returns Name ascending, so this doesn't hold across page turns or other columns.
  const [sortKey, setSortKey] = useState<SortKey>("name")
  const [sortOrder, setSortOrder] = useState<SortOrder>("asc")

  const [open, setOpen] = useState(false)
  const [editing, setEditing] = useState<Category | null>(null)
  const [name, setName] = useState("")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)
  const [deletingId, setDeletingId] = useState<number | null>(null)

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

  useEffect(() => {
    setPage(1)
  }, [search, status])

  function load() {
    setError(null)
    categoriesApi
      .list({ q: search || undefined, status: status === "All" ? undefined : status, sort: "name", page, pageSize: PAGE_SIZE })
      .then((res) => {
        setCategories(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }

  useEffect(load, [search, status, page])

  const hasFilters = search.trim().length > 0 || status !== "All"

  const sortedCategories = categories
    ? [...categories].sort((a, b) => {
        const cmp =
          sortKey === "categoryId"
            ? a.categoryId - b.categoryId
            : sortKey === "createdAt"
              ? new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
              : a[sortKey].localeCompare(b[sortKey])
        return sortOrder === "asc" ? cmp : -cmp
      })
    : null

  function toggleSort(key: SortKey) {
    if (key === sortKey) {
      setSortOrder((o) => (o === "asc" ? "desc" : "asc"))
    } else {
      setSortKey(key)
      setSortOrder("asc")
    }
  }

  function openCreateDialog() {
    setEditing(null)
    setName("")
    setErrors({})
    setOpen(true)
  }

  function openEditDialog(category: Category) {
    setEditing(category)
    setName(category.name)
    setErrors({})
    setOpen(true)
  }

  async function handleSubmit() {
    const nextErrors = validateCategoryName(name)
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setSubmitting(true)
    try {
      let result
      if (editing) {
        // The list carries no ETag, so re-read for a fresh If-Match rather than guessing.
        const current = await categoriesApi.get(editing.categoryId)
        result = await categoriesApi.update(editing.categoryId, { name }, current.etag ?? "")
      } else {
        result = await categoriesApi.create({ name })
      }
      toast.success(editing ? "Category updated" : "Category created", result.data.name)
      setOpen(false)
      setName("")
      setEditing(null)
      setErrors({})
      load()
    } catch (err) {
      setErrors({ name: errorMessage(err) })
      toast.error(editing ? "Could not update category" : "Could not create category", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  /** Masters are deactivated, never deleted — the API has no DELETE (FR-MD-08). */
  async function handleToggleStatus(category: Category) {
    const next = category.status === "Active" ? "Inactive" : "Active"
    setDeletingId(category.categoryId)
    try {
      await categoriesApi.updateStatus(category.categoryId, next)
      toast.success(next === "Inactive" ? "Category deactivated" : "Category activated", category.name)
      load()
    } catch (err) {
      toast.error("Could not update category status", errorMessage(err))
    } finally {
      setDeletingId(null)
    }
  }

  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">Categories</h1>
          <p className="text-base text-muted-foreground">Item category master (FR-MD-04).</p>
        </div>

        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger render={<Button size="lg" onClick={openCreateDialog}><Plus className="size-5" />New Category</Button>} />
          <DialogContent className="sm:max-w-sm">
            <DialogHeader className="items-center text-center">
              <DialogTitle>{editing ? "Edit category" : "New category"}</DialogTitle>
              <DialogDescription>Give the category a name.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.name}>
                <FieldLabel htmlFor="cat-name">Name</FieldLabel>
                <Input id="cat-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Fasteners" aria-invalid={!!errors.name} />
                <FieldError errors={[errors.name ? { message: errors.name } : undefined]} />
              </Field>
            </FieldGroup>
            <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-center">
              <Button variant="outline" className="w-full sm:w-auto sm:min-w-36" onClick={() => setOpen(false)} disabled={submitting}>
                Cancel
              </Button>
              <Button className="w-full sm:w-auto sm:min-w-36" onClick={handleSubmit} disabled={submitting}>
                {submitting ? (editing ? "Saving…" : "Creating…") : editing ? "Save" : "Create"}
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </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 categories…"
            className="h-14 w-full pl-11 text-base"
            aria-label="Search categories"
          />
        </div>
        <Select<StatusFilter> value={status} onValueChange={(v) => setStatus(v ?? "All")}>
          <SelectTrigger className="h-14! w-full sm:w-48 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 && categories === null && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 3 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      )}

      {!error && categories !== null && categories.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <ListTree className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">
            {hasFilters ? "No categories match your search/filter." : "No categories yet."}
          </p>
        </div>
      )}

      {!error && categories !== null && categories.length > 0 && (
        <>
          <Table className="text-base">
            <TableHeader>
              <TableRow>
                <TableHead className="h-12 px-3 text-sm">
                  <SortableHeader label="ID" active={sortKey === "categoryId"} order={sortOrder} onClick={() => toggleSort("categoryId")} />
                </TableHead>
                <TableHead className="h-12 px-3 text-sm">
                  <SortableHeader label="Name" active={sortKey === "name"} order={sortOrder} onClick={() => toggleSort("name")} />
                </TableHead>
                <TableHead className="h-12 px-3 text-sm">
                  <SortableHeader label="Status" active={sortKey === "status"} order={sortOrder} onClick={() => toggleSort("status")} />
                </TableHead>
                <TableHead className="h-12 px-3 text-sm">
                  <SortableHeader label="Created At" active={sortKey === "createdAt"} order={sortOrder} onClick={() => toggleSort("createdAt")} />
                </TableHead>
                <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sortedCategories!.map((c) => (
                <TableRow key={c.categoryId}>
                  <TableCell className="px-3 py-3.5 text-muted-foreground">#{c.categoryId}</TableCell>
                  <TableCell className="px-3 py-3.5 font-medium">{c.name}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <Badge
                      variant="outline"
                      className={cn(
                        "border-transparent",
                        c.status === "Active" ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive"
                      )}
                    >
                      {c.status}
                    </Badge>
                  </TableCell>
                  <TableCell className="px-3 py-3.5 text-muted-foreground">{new Date(c.createdAt).toLocaleDateString()}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <div className="flex items-center gap-1">
                      {/* Subcategories are their own resource now, not a nested tree. */}
                      <Link
                        href={`/dashboard/products/categories/${c.categoryId}`}
                        className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))}
                        aria-label={`Manage subcategories of ${c.name}`}
                      >
                        <Network className="size-4" />
                      </Link>

                      <Button
                        variant="ghost"
                        size="icon-sm"
                        aria-label={`Edit ${c.name}`}
                        onClick={() => openEditDialog(c)}
                      >
                        <Pencil className="size-4" />
                      </Button>

                      {/* Deactivate, not delete: no DELETE exists for any master (FR-MD-08). */}
                      <AlertDialog>
                        <AlertDialogTrigger
                          render={
                            <Button
                              variant="ghost"
                              size="icon-sm"
                              className={c.status === "Active" ? "text-destructive hover:bg-destructive/10" : ""}
                              aria-label={`${c.status === "Active" ? "Deactivate" : "Activate"} ${c.name}`}
                              disabled={deletingId === c.categoryId}
                            />
                          }
                        >
                          {c.status === "Active" ? <Ban className="size-4" /> : <CheckCircle2 className="size-4" />}
                        </AlertDialogTrigger>
                        <AlertDialogContent
                          variant={c.status === "Active" ? "destructive" : "success"}
                          title={`${c.status === "Active" ? "Deactivate" : "Activate"} ${c.name}?`}
                          description={
                            c.status === "Active"
                              ? "The category stays on existing items but cannot take new subcategories or items."
                              : "The category becomes selectable again."
                          }
                          confirmLabel={c.status === "Active" ? "Deactivate" : "Activate"}
                          onConfirm={() => handleToggleStatus(c)}
                        />
                      </AlertDialog>
                    </div>
                  </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>
  )
}

function SortableHeader({
  label,
  active,
  order,
  onClick,
}: {
  label: string
  active: boolean
  order: SortOrder
  onClick: () => void
}) {
  return (
    <button
      type="button"
      className="flex items-center gap-1 hover:text-foreground"
      onClick={onClick}
      aria-label={`Sort by ${label}, ${active && order === "asc" ? "descending" : "ascending"}`}
    >
      {label}
      {active ? (
        order === "asc" ? (
          <ArrowUp className="size-3.5" />
        ) : (
          <ArrowDown className="size-3.5" />
        )
      ) : (
        <ArrowUpDown className="size-3.5 text-muted-foreground/50" />
      )}
    </button>
  )
}
