"use client"

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

import { brandsApi } from "@/lib/api/brands"
import { errorMessage } from "@/lib/error-map"
import { validateBrandName } from "@/lib/validations/master-data"
import { cn } from "@/lib/utils"
import { EntityStatus, PaginationMeta } from "@/types/common"
import { Brand } 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 = "brandId" | "name" | "status" | "createdAt"
type StatusFilter = EntityStatus | "All"

const PAGE_SIZE = 5

export default function BrandsPage() {
  const [brands, setBrands] = useState<Brand[] | 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<Brand | 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)
    brandsApi
      .list({ q: search || undefined, status: status === "All" ? undefined : status, sort: "name", page, pageSize: PAGE_SIZE })
      .then((res) => {
        setBrands(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }

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

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

  const sortedBrands = brands
    ? [...brands].sort((a, b) => {
        const cmp =
          sortKey === "brandId"
            ? a.brandId - b.brandId
            : 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(brand: Brand) {
    setEditing(brand)
    setName(brand.name)
    setErrors({})
    setOpen(true)
  }

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

    setSubmitting(true)
    try {
      let result
      if (editing) {
        // The list response carries no ETag, so re-read to get a fresh If-Match token
        // rather than guessing one. A concurrent edit surfaces as 412 from the server.
        const current = await brandsApi.get(editing.brandId)
        result = await brandsApi.update(editing.brandId, { name }, current.etag ?? "")
      } else {
        result = await brandsApi.create({ name })
      }
      toast.success(editing ? "Brand updated" : "Brand created", result.data.name)
      setOpen(false)
      setName("")
      setEditing(null)
      setErrors({})
      load()
    } catch (err) {
      setErrors({ name: errorMessage(err) })
      toast.error(editing ? "Could not update brand" : "Could not create brand", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  /** Masters are deactivated, never deleted — the API has no DELETE (FR-MD-08). */
  async function handleToggleStatus(brand: Brand) {
    const next = brand.status === "Active" ? "Inactive" : "Active"
    setDeletingId(brand.brandId)
    try {
      await brandsApi.updateStatus(brand.brandId, next)
      toast.success(next === "Inactive" ? "Brand deactivated" : "Brand activated", brand.name)
      load()
    } catch (err) {
      toast.error("Could not update brand 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">Brands</h1>
          <p className="text-base text-muted-foreground">Manage product brands.</p>
        </div>

        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger render={<Button size="lg" onClick={openCreateDialog}><Plus className="size-5" />Add Brand</Button>} />
          <DialogContent className="sm:max-w-sm">
            <DialogHeader className="items-center text-center">
              <DialogTitle>{editing ? "Edit brand" : "New brand"}</DialogTitle>
              <DialogDescription>Give the brand a name.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.name}>
                <FieldLabel htmlFor="brand-name">Name</FieldLabel>
                <Input id="brand-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Bosch" 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 brands…"
            className="h-14 w-full pl-11 text-base"
            aria-label="Search brands"
          />
        </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 && brands === null && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 3 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      )}

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

      {!error && brands !== null && brands.length > 0 && (
        <>
          <Table className="text-base">
            <TableHeader>
              <TableRow>
                <TableHead className="h-12 px-3 text-sm">
                  <SortableHeader label="ID" active={sortKey === "brandId"} order={sortOrder} onClick={() => toggleSort("brandId")} />
                </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>
              {sortedBrands!.map((b) => (
                <TableRow key={b.brandId}>
                  <TableCell className="px-3 py-3.5 text-muted-foreground">#{b.brandId}</TableCell>
                  <TableCell className="px-3 py-3.5 font-medium">{b.name}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <Badge
                      variant="outline"
                      className={cn(
                        "border-transparent",
                        b.status === "Active" ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive"
                      )}
                    >
                      {b.status}
                    </Badge>
                  </TableCell>
                  <TableCell className="px-3 py-3.5 text-muted-foreground">{new Date(b.createdAt).toLocaleDateString()}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <div className="flex items-center gap-1">
                      <Button
                        variant="ghost"
                        size="icon-sm"
                        aria-label={`Edit ${b.name}`}
                        onClick={() => openEditDialog(b)}
                      >
                        <Pencil className="size-4" />
                      </Button>

                      {/* Deactivate, not delete: the API has no DELETE for any master
                          (FR-MD-08) — records referenced by transactions must survive. */}
                      <AlertDialog>
                        <AlertDialogTrigger
                          render={
                            <Button
                              variant="ghost"
                              size="icon-sm"
                              className={b.status === "Active" ? "text-destructive hover:bg-destructive/10" : ""}
                              aria-label={`${b.status === "Active" ? "Deactivate" : "Activate"} ${b.name}`}
                              disabled={deletingId === b.brandId}
                            />
                          }
                        >
                          {b.status === "Active" ? <Ban className="size-4" /> : <CheckCircle2 className="size-4" />}
                        </AlertDialogTrigger>
                        <AlertDialogContent
                          variant={b.status === "Active" ? "destructive" : "success"}
                          title={`${b.status === "Active" ? "Deactivate" : "Activate"} ${b.name}?`}
                          description={
                            b.status === "Active"
                              ? "The brand stays on existing items but cannot be assigned to new ones."
                              : "The brand becomes selectable again."
                          }
                          confirmLabel={b.status === "Active" ? "Deactivate" : "Activate"}
                          onConfirm={() => handleToggleStatus(b)}
                        />
                      </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>
  )
}
