"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { ArrowLeft, ChevronLeft, ChevronRight, Pencil, Plus, Search, Tag, Trash2 } 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 { PaginationMeta } from "@/types/common"
import { Brand } from "@/types/master-data"

import { AlertDialog, AlertDialogContent, AlertDialogTrigger } from "@/components/ui/alert-dialog"
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"

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 [sortOrder, setSortOrder] = useState<SortOrder>("asc")
  const [page, setPage] = useState(1)

  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, sortOrder])

  function load() {
    setError(null)
    brandsApi
      .list({ q: search || undefined, sortOrder, page, pageSize: PAGE_SIZE })
      .then((res) => {
        setBrands(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }

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

  const hasFilters = search.trim().length > 0

  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 {
      const brand = editing
        ? await brandsApi.update(editing.brandId, { name })
        : await brandsApi.create({ name })
      toast.success(editing ? "Brand updated" : "Brand created", brand.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)
    }
  }

  async function handleDelete(brand: Brand) {
    setDeletingId(brand.brandId)
    try {
      await brandsApi.remove(brand.brandId)
      toast.success("Brand deleted", brand.name)
      load()
    } catch (err) {
      toast.error("Could not delete brand", errorMessage(err))
    } finally {
      setDeletingId(null)
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center justify-between">
        <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">Brands</h1>
            <p className="text-base text-muted-foreground">Manage product brands.</p>
          </div>
        </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 justify-center gap-3 pt-2">
              <Button variant="outline" className="min-w-36" onClick={() => setOpen(false)} disabled={submitting}>
                Cancel
              </Button>
              <Button className="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<SortOrder> value={sortOrder} onValueChange={(v) => setSortOrder(v ?? "asc")}>
          <SelectTrigger className="h-14! w-full flex-1 basis-0 text-base">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="asc" className="text-base">Name (A–Z)</SelectItem>
            <SelectItem value="desc" className="text-base">Name (Z–A)</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." : "No brands yet."}
          </p>
        </div>
      )}

      {!error && brands !== null && brands.length > 0 && (
        <>
          <Table className="text-base">
            <TableHeader className="bg-indigo-50">
              <TableRow className="hover:bg-indigo-50">
                <TableHead className="h-12 px-3 text-sm text-indigo-700">ID</TableHead>
                <TableHead className="h-12 px-3 text-sm text-indigo-700">Name</TableHead>
                <TableHead className="h-12 px-3 text-sm text-indigo-700">Created At</TableHead>
                <TableHead className="h-12 px-3 text-sm text-indigo-700">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {brands.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 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>

                      <AlertDialog>
                        <AlertDialogTrigger
                          render={
                            <Button
                              variant="ghost"
                              size="icon-sm"
                              className="text-destructive hover:bg-destructive/10"
                              aria-label={`Delete ${b.name}`}
                              disabled={deletingId === b.brandId}
                            />
                          }
                        >
                          <Trash2 className="size-4" />
                        </AlertDialogTrigger>
                        <AlertDialogContent
                          variant="destructive"
                          title={`Delete ${b.name}?`}
                          description="This permanently removes the brand."
                          confirmLabel="Delete"
                          onConfirm={() => handleDelete(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>
  )
}
