"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { Plus, Warehouse as WarehouseIcon } from "lucide-react"

import { warehousesApi } from "@/lib/api/warehouses"
import { errorMessage } 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"

/** First word of the name, uppercased and stripped to alphanumerics — falls back to "WH"
 * so an empty/punctuation-only name still yields a usable base. */
function warehouseCodeBase(name: string): string {
  const firstWord = name.trim().split(/\s+/)[0] ?? ""
  const cleaned = firstWord.toUpperCase().replace(/[^A-Z0-9]/g, "")
  return cleaned.slice(0, 10) || "WH"
}

/** Appends a numeric suffix until the code doesn't collide with an existing one — the
 * backend enforces global uniqueness (409 on conflict) but has no generation of its own. */
function generateWarehouseCode(name: string, existingCodes: string[]): string {
  const base = `WH-${warehouseCodeBase(name)}`
  if (!existingCodes.includes(base)) return base
  let suffix = 2
  while (existingCodes.includes(`${base}${suffix}`)) suffix += 1
  return `${base}${suffix}`
}

export default function WarehousesPage() {
  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [bins, setBins] = useState<Bin[] | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [open, setOpen] = useState(false)
  const [name, setName] = useState("")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  const generatedCode = name.trim() ? generateWarehouseCode(name, (warehouses ?? []).map((w) => w.code)) : ""

  function load() {
    warehousesApi
      .list()
      .then(async (res) => {
        setWarehouses(res.items)
        const allBins = await Promise.all(res.items.map((w) => warehousesApi.listBins(w.warehouseId)))
        setBins(allBins.flat())
      })
      .catch((err) => setError(errorMessage(err)))
  }

  useEffect(load, [])

  function binCount(warehouseId: number) {
    return (bins ?? []).filter((b) => b.warehouseId === warehouseId).length
  }

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

    setSubmitting(true)
    try {
      const warehouse = await warehousesApi.create({ code: generatedCode, name })
      toast.success("Warehouse created", `${warehouse.code} — ${warehouse.name}`)
      setOpen(false)
      setName("")
      setErrors({})
      load()
    } catch (err) {
      // A 409 here means another creation raced ours for the same generated code — the
      // proactive de-dupe above only knows about warehouses loaded when the dialog opened.
      toast.error("Could not create warehouse", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  const loading = !warehouses || !bins

  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">Warehouses</h1>
            <p className="text-base text-muted-foreground">Multi-warehouse master data with per-warehouse 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 Warehouse
              </Button>
            }
          />
          <DialogContent className="sm:max-w-md">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New warehouse</DialogTitle>
              <DialogDescription>Create a new warehouse. Its code is generated from the name. Bins are added from its detail page.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.name}>
                <FieldLabel htmlFor="wh-name">Name</FieldLabel>
                <Input id="wh-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Main Warehouse - Negombo" aria-invalid={!!errors.name} />
                <FieldError errors={[errors.name ? { message: errors.name } : undefined]} />
              </Field>
              <Field>
                <FieldLabel htmlFor="wh-code">Code (auto-generated)</FieldLabel>
                <Input id="wh-code" value={generatedCode} readOnly disabled placeholder="Enter a name to generate a code" className="text-muted-foreground" />
              </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>
      )}

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

      {!loading && !error && warehouses.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <WarehouseIcon className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No warehouses yet.</p>
        </div>
      )}

      {!loading && !error && warehouses.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">Bins</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {warehouses.map((w) => (
              <TableRow key={w.warehouseId}>
                <TableCell className="px-3 py-3.5">
                  <Link href={`/dashboard/warehouse/${w.warehouseId}`} className="font-medium text-primary hover:underline">
                    {w.code}
                  </Link>
                </TableCell>
                <TableCell className="px-3 py-3.5">{w.name}</TableCell>
                <TableCell className="px-3 py-3.5">{binCount(w.warehouseId)}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
