"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Plus, Trash2 } from "lucide-react"

import { requisitionsApi } from "@/lib/api/requisitions"
import { itemsApi } from "@/lib/api/items"
import { errorMessage } from "@/lib/error-map"
import { validateRequisitionLine } from "@/lib/validations/procurement"
import { cn } from "@/lib/utils"
import { CreateReqLineInput } from "@/types/procurement"
import { ItemListItem } from "@/types/master-data"

import { Button, buttonVariants } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { FieldError } from "@/components/ui/field"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Skeleton } from "@/components/ui/skeleton"
import { toast } from "@/components/ui/toast"

interface DraftLine {
  key: string
  itemId: number | null
  qty: string
  requiredBy: string
}

let keySeq = 0
function newKey() {
  keySeq += 1
  return `rline-${keySeq}`
}

function emptyLine(): DraftLine {
  return { key: newKey(), itemId: null, qty: "", requiredBy: "" }
}

export default function NewRequisitionPage() {
  const router = useRouter()

  const [items, setItems] = useState<ItemListItem[] | null>(null)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [lines, setLines] = useState<DraftLine[]>([emptyLine()])
  const [lineErrors, setLineErrors] = useState<Record<string, Record<string, string>>>({})
  const [submitError, setSubmitError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    itemsApi.list({ pageSize: 200, status: "Active" }).then((res) => setItems(res.items)).catch((err) => setLoadError(errorMessage(err)))
  }, [])

  function updateLine(key: string, patch: Partial<DraftLine>) {
    setLines((prev) => prev.map((l) => (l.key === key ? { ...l, ...patch } : l)))
  }

  function removeLine(key: string) {
    setLines((prev) => prev.filter((l) => l.key !== key))
  }

  async function handleSubmit() {
    setSubmitError(null)

    if (lines.length === 0) {
      setSubmitError("Add at least one line.")
      return
    }

    const nextLineErrors: Record<string, Record<string, string>> = {}
    for (const line of lines) {
      const errors = validateRequisitionLine({ itemId: line.itemId, qty: line.qty, requiredBy: line.requiredBy })
      if (Object.keys(errors).length > 0) nextLineErrors[line.key] = errors
    }
    setLineErrors(nextLineErrors)
    if (Object.keys(nextLineErrors).length > 0) {
      setSubmitError("Fix the highlighted lines before submitting.")
      return
    }

    const payloadLines: CreateReqLineInput[] = lines.map((l) => ({
      itemId: l.itemId as number,
      qty: Number(l.qty),
      requiredBy: l.requiredBy,
    }))

    setSubmitting(true)
    try {
      const requisition = await requisitionsApi.create({ lines: payloadLines })
      toast.success("Requisition created", `${requisition.docNo} is a draft — submit it when ready.`)
      router.push(`/dashboard/procurement/requisitions/${requisition.requisitionId}`)
    } catch (err) {
      setSubmitError(errorMessage(err))
      toast.error("Could not create requisition", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  const loading = !items

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <div>
          <h1 className="text-2xl font-bold text-foreground">New Requisition</h1>
          <p className="text-base text-muted-foreground">Request items for procurement; submit once the lines are ready (FR-PROC-01).</p>
        </div>
      </div>

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

      {loading && !loadError && <Skeleton className="h-24 w-full" />}

      {!loading && (
        <>
          <div className="flex flex-col gap-3">
            <div className="flex items-center justify-between">
              <h2 className="text-base font-semibold text-foreground">Lines</h2>
              <Button type="button" variant="outline" onClick={() => setLines((prev) => [...prev, emptyLine()])}>
                <Plus className="size-5" />
                Add line
              </Button>
            </div>

            {lines.length > 0 && (
              <Table className="text-base">
                <TableHeader>
                  <TableRow>
                    <TableHead className="h-12 w-72 px-3 text-sm">Item</TableHead>
                    <TableHead className="h-12 w-32 px-3 text-sm">Qty</TableHead>
                    <TableHead className="h-12 w-44 px-3 text-sm">Required by</TableHead>
                    <TableHead className="h-12 w-10 px-3" />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {lines.map((line) => {
                    const errors = lineErrors[line.key] ?? {}
                    return (
                      <TableRow key={line.key}>
                        <TableCell className="px-3 py-3 align-top">
                          <Select<number | null> value={line.itemId} onValueChange={(v) => updateLine(line.key, { itemId: v })}>
                            <SelectTrigger className="h-11! w-full text-base" aria-invalid={!!errors.itemId}>
                              <SelectValue placeholder="Select item" />
                            </SelectTrigger>
                            <SelectContent>
                              {(items ?? []).map((i) => (
                                <SelectItem key={i.itemId} value={i.itemId} className="text-base">
                                  {i.sku} — {i.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FieldError errors={[errors.itemId ? { message: errors.itemId } : undefined]} />
                        </TableCell>
                        <TableCell className="px-3 py-3 align-top">
                          <Input
                            type="number"
                            min="0"
                            step="any"
                            value={line.qty}
                            aria-invalid={!!errors.qty}
                            onChange={(e) => updateLine(line.key, { qty: e.target.value })}
                            className="h-11 text-base"
                          />
                          <FieldError errors={[errors.qty ? { message: errors.qty } : undefined]} />
                        </TableCell>
                        <TableCell className="px-3 py-3 align-top">
                          <Input
                            type="date"
                            value={line.requiredBy}
                            aria-invalid={!!errors.requiredBy}
                            onChange={(e) => updateLine(line.key, { requiredBy: e.target.value })}
                            className="h-11 text-base"
                          />
                          <FieldError errors={[errors.requiredBy ? { message: errors.requiredBy } : undefined]} />
                        </TableCell>
                        <TableCell className="px-3 py-3 align-top">
                          <Button type="button" variant="ghost" size="icon" onClick={() => removeLine(line.key)} aria-label="Remove line">
                            <Trash2 className="size-5" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    )
                  })}
                </TableBody>
              </Table>
            )}
          </div>

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

          <div className="flex justify-end gap-3">
            <Link href="/dashboard/procurement/requisitions" className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>
              Cancel
            </Link>
            <Button size="lg" type="button" onClick={handleSubmit} disabled={submitting}>
              {submitting ? "Creating…" : "Create Requisition"}
            </Button>
          </div>
        </>
      )}
    </div>
  )
}
