"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { ChevronLeft, ChevronRight, Eye, Pencil, Plus, Search, Trash2, Truck } from "lucide-react"

import { vendorsApi } from "@/lib/api/vendors"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { generateVendorCode } from "@/lib/vendor-code"
import { EntityStatus, PaginationMeta } from "@/types/common"
import { Vendor } 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 { Badge } from "@/components/ui/badge"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import {
  Dialog,
  DialogClose,
  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 StatusFilter = EntityStatus | "All"

const PAGE_SIZE = 5

export default function VendorsPage() {
  const [vendors, setVendors] = useState<Vendor[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [searchInput, setSearchInput] = useState("")
  const [query, setQuery] = useState("")
  const [status, setStatus] = useState<StatusFilter>("All")
  const [page, setPage] = useState(1)

  const [open, setOpen] = useState(false)
  const [name, setName] = useState("")
  const [terms, setTerms] = useState("")
  const [taxReg, setTaxReg] = useState("")
  const [currency, setCurrency] = useState("LKR")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  // Separate from the paginated table list above — this needs every existing code (up to the
  // server's page-size cap) to de-dupe against, not just the current page's 5 rows.
  const [allVendorCodes, setAllVendorCodes] = useState<string[]>([])

  const [actionPendingId, setActionPendingId] = useState<number | null>(null)

  const generatedCode = name.trim() ? generateVendorCode(name, allVendorCodes) : ""

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

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

  function load() {
    vendorsApi
      .list({ q: query || undefined, status: status === "All" ? undefined : status, page, pageSize: PAGE_SIZE })
      .then((res) => {
        setVendors(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }

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

  useEffect(() => {
    vendorsApi.list({ pageSize: 200 }).then((res) => setAllVendorCodes(res.items.map((v) => v.code))).catch(() => {})
  }, [])

  function resetForm() {
    setName("")
    setTerms("")
    setTaxReg("")
    setCurrency("LKR")
    setErrors({})
  }

  async function handleCreate() {
    const nextErrors: Record<string, string> = {}
    if (!name.trim()) nextErrors.name = "Vendor name is required"
    if (!currency.trim()) nextErrors.currency = "Currency is required"
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setSubmitting(true)
    try {
      const result = await vendorsApi.create({ code: generatedCode, name, terms: terms || null, taxReg: taxReg || null, currency })
      toast.success("Vendor created", `${result.data.code} — ${result.data.name}`)
      setOpen(false)
      resetForm()
      load()
      setAllVendorCodes((codes) => [...codes, result.data.code])
    } catch (err) {
      // A 409 here means another creation raced ours for the same generated code — the
      // proactive de-dupe above only knows about codes loaded when the dialog opened.
      toast.error("Could not create vendor", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  // FR-MD-08: masters are deactivated, never hard-deleted — "Delete" in the UI
  // maps to PATCH status → Inactive, same mechanism as the detail page's toggle.
  async function handleDeactivate(vendor: Vendor) {
    setActionPendingId(vendor.vendorId)
    try {
      await vendorsApi.updateStatus(vendor.vendorId, "Inactive")
      toast.success("Vendor deleted", `${vendor.code} has been deactivated.`)
      load()
    } catch (err) {
      toast.error("Could not delete vendor", errorMessage(err))
    } finally {
      setActionPendingId(null)
    }
  }

  const hasFilters = query.length > 0 || status !== "All"

  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">Vendors</h1>
          <p className="text-base text-muted-foreground">Supplier master data — code, terms, tax registration, currency (FR-MD-06).</p>
        </div>

        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger
            render={
              <Button size="lg">
                <Plus className="size-5" />
                New Vendor
              </Button>
            }
          />
          <DialogContent className="sm:max-w-md">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New vendor</DialogTitle>
              <DialogDescription>Create a supplier record. Its code is generated from the name.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.name}>
                <FieldLabel htmlFor="v-name">Name</FieldLabel>
                <Input id="v-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Lanka Steel Traders (Pvt) Ltd" aria-invalid={!!errors.name} />
                <FieldError errors={[errors.name ? { message: errors.name } : undefined]} />
              </Field>
              <Field>
                <FieldLabel htmlFor="v-code">Code (auto-generated)</FieldLabel>
                <Input id="v-code" value={generatedCode} readOnly disabled placeholder="Enter a name to generate a code" className="text-muted-foreground" />
              </Field>
              <Field>
                <FieldLabel htmlFor="v-terms">Payment terms (optional)</FieldLabel>
                <Input id="v-terms" value={terms} onChange={(e) => setTerms(e.target.value)} placeholder="NET30" />
              </Field>
              <Field>
                <FieldLabel htmlFor="v-taxreg">Tax registration (optional)</FieldLabel>
                <Input id="v-taxreg" value={taxReg} onChange={(e) => setTaxReg(e.target.value)} placeholder="134567890-7000" />
              </Field>
              <Field data-invalid={!!errors.currency}>
                <FieldLabel htmlFor="v-currency">Currency</FieldLabel>
                <Input id="v-currency" value={currency} onChange={(e) => setCurrency(e.target.value)} placeholder="LKR" maxLength={3} aria-invalid={!!errors.currency} />
                <FieldError errors={[errors.currency ? { message: errors.currency } : 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={handleCreate} disabled={submitting}>
                {submitting ? "Creating…" : "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 code or name…"
            className="h-14 w-full pl-11 text-base"
            aria-label="Search vendors"
          />
        </div>
        <Select<StatusFilter> value={status} onValueChange={(v) => setStatus(v ?? "All")}>
          <SelectTrigger className="h-14! w-full flex-1 basis-0 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 && vendors === null && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      )}

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

      {!error && vendors !== null && vendors.length > 0 && (
        <>
          <Table className="text-base">
            <TableHeader>
              <TableRow>
                <TableHead className="h-12 px-3 text-sm">Code</TableHead>
                <TableHead className="h-12 px-3 text-sm">Name</TableHead>
                <TableHead className="h-12 px-3 text-sm">Terms</TableHead>
                <TableHead className="h-12 px-3 text-sm">Currency</TableHead>
                <TableHead className="h-12 px-3 text-sm">Status</TableHead>
                <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {vendors.map((v) => (
                <TableRow key={v.vendorId}>
                  <TableCell className="px-3 py-3.5 font-medium">{v.code}</TableCell>
                  <TableCell className="px-3 py-3.5">{v.name}</TableCell>
                  <TableCell className="px-3 py-3.5">{v.terms ?? "—"}</TableCell>
                  <TableCell className="px-3 py-3.5">{v.currency}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <Badge
                      variant="outline"
                      className={cn(
                        "h-6 w-fit justify-center border-transparent px-2.5 text-sm",
                        v.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"
                      )}
                    >
                      {v.status}
                    </Badge>
                  </TableCell>
                  <TableCell className="px-3 py-3.5">
                    <div className="flex items-center gap-1">
                      <Dialog>
                        <DialogTrigger
                          render={<Button variant="ghost" size="icon-sm" aria-label={`View ${v.code}`} />}
                        >
                          <Eye className="size-4" />
                        </DialogTrigger>
                        <DialogContent className="sm:max-w-md">
                          <DialogHeader className="items-center text-center">
                            <DialogTitle>{v.code}</DialogTitle>
                            <DialogDescription>{v.name}</DialogDescription>
                          </DialogHeader>
                          <div className="flex flex-col gap-3 text-base">
                            <div className="flex items-center justify-between border-b pb-2">
                              <span className="text-muted-foreground">Payment terms</span>
                              <span className="font-medium">{v.terms ?? "—"}</span>
                            </div>
                            <div className="flex items-center justify-between border-b pb-2">
                              <span className="text-muted-foreground">Tax registration</span>
                              <span className="font-medium">{v.taxReg ?? "—"}</span>
                            </div>
                            <div className="flex items-center justify-between border-b pb-2">
                              <span className="text-muted-foreground">Currency</span>
                              <span className="font-medium">{v.currency}</span>
                            </div>
                            <div className="flex items-center justify-between border-b pb-2">
                              <span className="text-muted-foreground">Status</span>
                              <Badge
                                variant="outline"
                                className={cn(
                                  "h-6 w-fit justify-center border-transparent px-2.5 text-sm",
                                  v.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"
                                )}
                              >
                                {v.status}
                              </Badge>
                            </div>
                            <div className="flex items-center justify-between">
                              <span className="text-muted-foreground">Created</span>
                              <span className="font-medium">{new Date(v.createdAt).toLocaleString()}</span>
                            </div>
                          </div>
                          <div className="flex justify-center pt-2">
                            <DialogClose render={<Button variant="outline" className="w-full sm:w-auto sm:min-w-36" />}>Close</DialogClose>
                          </div>
                        </DialogContent>
                      </Dialog>

                      <Link
                        href={`/dashboard/vendors/${v.vendorId}`}
                        className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))}
                        aria-label={`Update ${v.code}`}
                      >
                        <Pencil className="size-4" />
                      </Link>

                      <AlertDialog>
                        <AlertDialogTrigger
                          render={
                            <Button
                              variant="ghost"
                              size="icon-sm"
                              className="text-destructive hover:bg-destructive/10"
                              aria-label={`Delete ${v.code}`}
                              disabled={v.status === "Inactive" || actionPendingId === v.vendorId}
                            />
                          }
                        >
                          <Trash2 className="size-4" />
                        </AlertDialogTrigger>
                        <AlertDialogContent
                          variant="destructive"
                          title={`Delete ${v.code}?`}
                          description={`This deactivates ${v.name} (FR-MD-08 — master data is deactivated, not hard-deleted). It can be reactivated later from its detail page.`}
                          confirmLabel="Delete"
                          onConfirm={() => handleDeactivate(v)}
                        />
                      </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>
  )
}
