"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { CheckCircle2, ClipboardCheck, Save } from "lucide-react"

import { stockCountsApi } from "@/lib/api/stock-counts"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PostCountResponse, StockCount } from "@/types/stock"

import { Button } from "@/components/ui/button"
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"
import { CountStatusBadge } from "@/components/stock/status-badges"

export default function CountDetailPage() {
  const params = useParams<{ id: string }>()
  const countId = Number(params.id)

  const [count, setCount] = useState<StockCount | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [drafts, setDrafts] = useState<Record<number, string>>({})
  const [saving, setSaving] = useState(false)
  const [posting, setPosting] = useState(false)
  const [postResult, setPostResult] = useState<PostCountResponse | null>(null)

  useEffect(() => {
    if (!Number.isFinite(countId)) return
    stockCountsApi
      .get(countId)
      .then((c) => {
        setCount(c)
        setDrafts(Object.fromEntries(c.lines.map((l) => [l.countLineId, l.countedQty !== null ? String(l.countedQty) : ""])))
      })
      .catch((err) => setError(errorMessage(err)))
  }, [countId])

  async function handleSave() {
    if (!count) return
    setError(null)
    setSaving(true)
    try {
      const lines = Object.entries(drafts)
        .filter(([, v]) => v !== "")
        .map(([countLineId, v]) => ({ countLineId: Number(countLineId), countedQty: Number(v) }))
      const result = await stockCountsApi.enterCounts(countId, { lines })
      setCount((prev) => (prev ? { ...prev, lines: result.lines } : prev))
      toast.success("Counts saved", "Variances recalculated.")
    } catch (err) {
      setError(errorMessage(err))
      toast.error("Could not save counts", errorMessage(err))
    } finally {
      setSaving(false)
    }
  }

  async function handlePost() {
    setError(null)
    setPosting(true)
    try {
      const result = await stockCountsApi.post(countId)
      setPostResult(result)
      setCount((prev) => (prev ? { ...prev, status: result.status } : prev))
      toast.success("Count posted", `Variance adjustment ${result.adjustmentId} created.`)
    } catch (err) {
      setError(errorMessage(err))
      toast.error("Could not post count", errorMessage(err))
    } finally {
      setPosting(false)
    }
  }

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

  if (!count) {
    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>
            <div className="flex items-center gap-3">
              <h1 className="text-2xl font-bold text-foreground">{count.docNo}</h1>
              <CountStatusBadge status={count.status} />
            </div>
            <p className="text-base text-muted-foreground">{count.countType} count · Warehouse #{count.warehouseId}</p>
          </div>
        </div>

        {count.status === "Draft" && (
          <div className="flex gap-3">
            <Button size="lg" variant="outline" onClick={handleSave} disabled={saving}>
              <Save className="size-5" />
              {saving ? "Saving…" : "Save counts"}
            </Button>
            <Button size="lg" onClick={handlePost} disabled={posting}>
              <ClipboardCheck className="size-5" />
              {posting ? "Posting…" : "Post count"}
            </Button>
          </div>
        )}
      </div>

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

      {postResult && (
        <div className="flex flex-col gap-2 rounded-xl border border-success/30 bg-success/5 p-5">
          <div className="flex items-center gap-2 text-success">
            <CheckCircle2 className="size-6" />
            <p className="text-base font-semibold">Posted — variance adjustment #{postResult.adjustmentId} created</p>
          </div>
          <div className="text-sm text-muted-foreground">Ledger refs: {postResult.ledgerRefs.join(", ") || "none (no variance)"}</div>
          {postResult.glJournalNo && (
            <div className="text-sm text-muted-foreground">GL journal: <span className="font-medium text-foreground">{postResult.glJournalNo}</span></div>
          )}
        </div>
      )}

      <Table className="text-base">
        <TableHeader>
          <TableRow>
            <TableHead className="h-12 px-3 text-sm">Item</TableHead>
            <TableHead className="h-12 px-3 text-sm">System qty</TableHead>
            <TableHead className="h-12 px-3 text-sm">Counted qty</TableHead>
            <TableHead className="h-12 px-3 text-sm">Variance</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {count.lines.map((line) => (
            <TableRow key={line.countLineId}>
              <TableCell className="px-3 py-3.5">#{line.itemId}</TableCell>
              <TableCell className="px-3 py-3.5">{line.systemQty}</TableCell>
              <TableCell className="px-3 py-3.5">
                {count.status === "Draft" ? (
                  <Input
                    type="number"
                    step="any"
                    value={drafts[line.countLineId] ?? ""}
                    onChange={(e) => setDrafts((prev) => ({ ...prev, [line.countLineId]: e.target.value }))}
                    className="h-11 w-32 text-base"
                  />
                ) : (
                  (line.countedQty ?? "—")
                )}
              </TableCell>
              <TableCell className={cn("px-3 py-3.5 font-medium", line.variance && line.variance !== 0 && (line.variance > 0 ? "text-success" : "text-destructive"))}>
                {line.variance ?? "—"}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  )
}
