"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { ArrowLeft, Pencil, Plus, SwatchBook, Trash2 } from "lucide-react"

import { variantCategoriesApi } from "@/lib/api/variants"
import { errorMessage } from "@/lib/error-map"
import { validateVariantCategoryName } from "@/lib/validations/master-data"
import { cn } from "@/lib/utils"
import { VariantCategory } 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 { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

export default function VariantsPage() {
  const [categories, setCategories] = useState<VariantCategory[] | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [open, setOpen] = useState(false)
  const [editing, setEditing] = useState<VariantCategory | 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)

  function load() {
    setError(null)
    variantCategoriesApi
      .list()
      .then((res) => setCategories(res.items))
      .catch((err) => setError(errorMessage(err)))
  }

  useEffect(load, [])

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

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

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

    setSubmitting(true)
    try {
      const category = editing
        ? await variantCategoriesApi.update(editing.variantCategoryId, { name })
        : await variantCategoriesApi.create({ name })
      toast.success(editing ? "Variant category updated" : "Variant category created", category.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)
    }
  }

  async function handleDelete(category: VariantCategory) {
    setDeletingId(category.variantCategoryId)
    try {
      await variantCategoriesApi.remove(category.variantCategoryId)
      toast.success("Variant category deleted", category.name)
      load()
    } catch (err) {
      toast.error("Could not delete category", 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">Variants</h1>
            <p className="text-base text-muted-foreground">Variant categories used by the item variant builder (e.g. Color, Size, Material).</p>
          </div>
        </div>

        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger render={<Button size="lg" onClick={openCreateDialog}><Plus className="size-5" />Add Category</Button>} />
          <DialogContent className="sm:max-w-sm">
            <DialogHeader className="items-center text-center">
              <DialogTitle>{editing ? "Edit variant category" : "New variant category"}</DialogTitle>
              <DialogDescription>Give the category a name.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.name}>
                <FieldLabel htmlFor="variant-category-name">Name</FieldLabel>
                <Input
                  id="variant-category-name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Material"
                  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>

      {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">
          <SwatchBook className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No variant categories yet.</p>
        </div>
      )}

      {!error && categories !== null && categories.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>
            {categories.map((c) => (
              <TableRow key={c.variantCategoryId}>
                <TableCell className="px-3 py-3.5 text-muted-foreground">#{c.variantCategoryId}</TableCell>
                <TableCell className="px-3 py-3.5 font-medium">{c.name}</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">
                    <Button
                      variant="ghost"
                      size="icon-sm"
                      aria-label={`Edit ${c.name}`}
                      onClick={() => openEditDialog(c)}
                    >
                      <Pencil className="size-4" />
                    </Button>

                    <AlertDialog>
                      <AlertDialogTrigger
                        render={
                          <Button
                            variant="ghost"
                            size="icon-sm"
                            className="text-destructive hover:bg-destructive/10"
                            aria-label={`Delete ${c.name}`}
                            disabled={deletingId === c.variantCategoryId}
                          />
                        }
                      >
                        <Trash2 className="size-4" />
                      </AlertDialogTrigger>
                      <AlertDialogContent
                        variant="destructive"
                        title={`Delete ${c.name}?`}
                        description="This permanently removes the variant category."
                        confirmLabel="Delete"
                        onConfirm={() => handleDelete(c)}
                      />
                    </AlertDialog>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
