"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { MapPinned, Plus } from "lucide-react"

import { warehousesApi } from "@/lib/api/warehouses"
import { errorMessage, fieldErrors } from "@/lib/error-map"
import { Bin, Warehouse } from "@/types/master-data"

import { Button } 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 WarehouseDetailPage() {
  const params = useParams<{ id: string }>()
  const warehouseId = Number(params.id)

  const [warehouse, setWarehouse] = useState<Warehouse | null>(null)
  const [bins, setBins] = useState<Bin[] | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [open, setOpen] = useState(false)
  const [code, setCode] = useState("")
  const [binType, setBinType] = useState("")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  function loadBins() {
    warehousesApi.listBins(warehouseId).then(setBins).catch((err) => setError(errorMessage(err)))
  }

  useEffect(() => {
    if (!Number.isFinite(warehouseId)) return
    warehousesApi.get(warehouseId).then(setWarehouse).catch((err) => setError(errorMessage(err)))
    loadBins()
  }, [warehouseId])

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

    setSubmitting(true)
    try {
      const bin = await warehousesApi.createBin(warehouseId, { code, binType: binType || null })
      toast.success("Bin created", bin.code)
      setOpen(false)
      setCode("")
      setBinType("")
      setErrors({})
      loadBins()
    } catch (err) {
      const fe = fieldErrors(err)
      if (fe?.code) setErrors({ code: fe.code })
      toast.error("Could not create bin", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

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

  if (!warehouse || !bins) {
    return (
      <div className="flex flex-col gap-3">
        <Skeleton className="h-10 w-72" />
        <Skeleton className="h-48 w-full" />
      </div>
    )
  }

  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">{warehouse.code}</h1>
            <p className="text-base text-muted-foreground">{warehouse.name} · Bin/location structure (FR-WH-01, FR-MD-07)</p>
          </div>
        </div>

        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger
            render={
              <Button size="lg">
                <Plus className="size-5" />
                New Bin
              </Button>
            }
          />
          <DialogContent className="sm:max-w-md">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New bin</DialogTitle>
              <DialogDescription>Add a bin/location to {warehouse.code}.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.code}>
                <FieldLabel htmlFor="bin-code">Code</FieldLabel>
                <Input id="bin-code" value={code} onChange={(e) => setCode(e.target.value)} placeholder="A-01-01" aria-invalid={!!errors.code} />
                <FieldError errors={[errors.code ? { message: errors.code } : undefined]} />
              </Field>
              <Field>
                <FieldLabel htmlFor="bin-type">Bin type (optional)</FieldLabel>
                <Input id="bin-type" value={binType} onChange={(e) => setBinType(e.target.value)} placeholder="Shelf, Pallet, …" />
              </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>

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

      {bins.length === 0 ? (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <MapPinned className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No bins yet in this warehouse.</p>
        </div>
      ) : (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Code</TableHead>
              <TableHead className="h-12 px-3 text-sm">Type</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {bins.map((b) => (
              <TableRow key={b.binId}>
                <TableCell className="px-3 py-3.5 font-medium">{b.code}</TableCell>
                <TableCell className="px-3 py-3.5">{b.binType ?? "—"}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
