"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { Ban, CheckCircle2, Network, Pencil, Plus } from "lucide-react"

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

import { AlertDialog, AlertDialogContent, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

/**
 * Subcategories of one category — the single optional level below it (FR-MD-04).
 * The hierarchy is exactly two deep, so there is no recursion here by design.
 */
export default function CategorySubCategoriesPage() {
  const params = useParams<{ id: string }>()
  const categoryId = Number(params.id)

  const [category, setCategory] = useState<Category | null>(null)
  const [subCategories, setSubCategories] = useState<SubCategory[] | null>(null)
  const [error, setError] = useState<string | null>(null)

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

  function load() {
    setError(null)
    categoriesApi
      .get(categoryId)
      .then((res) => setCategory(res.data))
      .catch((err) => setError(errorMessage(err)))
    categoriesApi
      .listSubCategories(categoryId, { pageSize: 200 })
      .then((res) => setSubCategories(res.items))
      .catch((err) => setError(errorMessage(err)))
  }

  useEffect(load, [categoryId])

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

  function openEditDialog(sub: SubCategory) {
    setEditing(sub)
    setName(sub.name)
    setErrors({})
    setOpen(true)
  }

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

    setSubmitting(true)
    try {
      if (editing) {
        // Re-read for a fresh If-Match; a concurrent edit surfaces as 412.
        const current = await subCategoriesApi.get(editing.subCategoryId)
        await subCategoriesApi.update(editing.subCategoryId, { name }, current.etag ?? "")
      } else {
        await categoriesApi.createSubCategory(categoryId, { name })
      }
      toast.success(editing ? "Subcategory updated" : "Subcategory created", name)
      setOpen(false)
      setName("")
      setEditing(null)
      load()
    } catch (err) {
      setErrors({ name: errorMessage(err) })
      toast.error(editing ? "Could not update subcategory" : "Could not create subcategory", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  async function handleToggleStatus(sub: SubCategory) {
    const next = sub.status === "Active" ? "Inactive" : "Active"
    setTogglingId(sub.subCategoryId)
    try {
      await subCategoriesApi.updateStatus(sub.subCategoryId, next)
      toast.success(next === "Inactive" ? "Subcategory deactivated" : "Subcategory activated", sub.name)
      load()
    } catch (err) {
      toast.error("Could not update status", errorMessage(err))
    } finally {
      setTogglingId(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 className="flex items-center gap-3">
          <div>
            <h1 className="text-2xl font-bold text-foreground">{category ? `${category.name} — Subcategories` : "Subcategories"}</h1>
            <p className="text-base text-muted-foreground">
              The one optional level below a category (FR-MD-04). A subcategory cannot be moved to another category.
            </p>
          </div>
        </div>

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

      {error && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>
      )}

      {!error && subCategories === null && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 3 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      )}

      {!error && subCategories !== null && subCategories.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <Network className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No subcategories yet — items can attach straight to the category.</p>
        </div>
      )}

      {!error && subCategories !== null && subCategories.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">ID</TableHead>
              <TableHead className="h-12 px-3 text-sm">Name</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Created At</TableHead>
              <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {subCategories.map((s) => (
              <TableRow key={s.subCategoryId}>
                <TableCell className="px-3 py-3.5 text-muted-foreground">#{s.subCategoryId}</TableCell>
                <TableCell className="px-3 py-3.5 font-medium">{s.name}</TableCell>
                <TableCell className="px-3 py-3.5">
                  <Badge
                    variant="outline"
                    className={cn(
                      "border-transparent",
                      s.status === "Active" ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive"
                    )}
                  >
                    {s.status}
                  </Badge>
                </TableCell>
                <TableCell className="px-3 py-3.5 text-muted-foreground">{new Date(s.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 ${s.name}`} onClick={() => openEditDialog(s)}>
                      <Pencil className="size-4" />
                    </Button>

                    <AlertDialog>
                      <AlertDialogTrigger
                        render={
                          <Button
                            variant="ghost"
                            size="icon-sm"
                            className={s.status === "Active" ? "text-destructive hover:bg-destructive/10" : ""}
                            aria-label={`${s.status === "Active" ? "Deactivate" : "Activate"} ${s.name}`}
                            disabled={togglingId === s.subCategoryId}
                          />
                        }
                      >
                        {s.status === "Active" ? <Ban className="size-4" /> : <CheckCircle2 className="size-4" />}
                      </AlertDialogTrigger>
                      <AlertDialogContent
                        variant={s.status === "Active" ? "destructive" : "success"}
                        title={`${s.status === "Active" ? "Deactivate" : "Activate"} ${s.name}?`}
                        description={
                          s.status === "Active"
                            ? "It stays on existing items but cannot be assigned to new ones."
                            : "It becomes selectable again."
                        }
                        confirmLabel={s.status === "Active" ? "Deactivate" : "Activate"}
                        onConfirm={() => handleToggleStatus(s)}
                      />
                    </AlertDialog>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
