"use client"

import { useEffect, useMemo, useState } from "react"
import { ChevronLeft, ChevronRight, ScrollText } from "lucide-react"

import { stockApi } from "@/lib/api/stock"
import { itemsApi } from "@/lib/api/items"
import { warehousesApi } from "@/lib/api/warehouses"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { LedgerEntry } from "@/types/stock"
import { PaginationMeta } from "@/types/common"
import { ItemListItem, Warehouse } from "@/types/master-data"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

const PAGE_SIZE = 10

export default function StockLedgerPage() {
  const [entries, setEntries] = useState<LedgerEntry[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [items, setItems] = useState<ItemListItem[] | null>(null)
  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [itemId, setItemId] = useState<number | "All">("All")
  const [warehouseId, setWarehouseId] = useState<number | "All">("All")
  const [from, setFrom] = useState("")
  const [to, setTo] = useState("")
  const [page, setPage] = useState(1)

  useEffect(() => {
    Promise.all([itemsApi.list({ pageSize: 200 }), warehousesApi.list()])
      .then(([it, wh]) => {
        setItems(it.items)
        setWarehouses(wh.items)
      })
      .catch((err) => setError(errorMessage(err)))
  }, [])

  useEffect(() => {
    setPage(1)
  }, [itemId, warehouseId, from, to])

  useEffect(() => {
    let cancelled = false
    stockApi
      .ledger({
        itemId: itemId === "All" ? undefined : itemId,
        warehouseId: warehouseId === "All" ? undefined : warehouseId,
        from: from || undefined,
        to: to || undefined,
        page,
        pageSize: PAGE_SIZE,
      })
      .then((res) => {
        if (cancelled) return
        setEntries(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => {
        if (!cancelled) setError(errorMessage(err))
      })
    return () => {
      cancelled = true
    }
  }, [itemId, warehouseId, from, to, page])

  const itemsById = useMemo(() => new Map((items ?? []).map((i) => [i.itemId, i])), [items])
  const warehousesById = useMemo(() => new Map((warehouses ?? []).map((w) => [w.warehouseId, w])), [warehouses])

  const loading = entries === null || items === null || warehouses === null

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Stock Ledger</h1>
          <p className="text-base text-muted-foreground">Immutable, append-only movement journal (FR-STK-01).</p>
        </div>
      </div>

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

      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <div className="flex flex-col gap-1.5">
          <Label className="text-base">Item</Label>
          <Select<number | "All"> value={itemId} onValueChange={(v) => setItemId(v ?? "All")}>
            <SelectTrigger className="h-11! w-full text-base">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="All" className="text-base">All items</SelectItem>
              {(items ?? []).map((i) => (
                <SelectItem key={i.itemId} value={i.itemId} className="text-base">
                  {i.sku}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="flex flex-col gap-1.5">
          <Label className="text-base">Warehouse</Label>
          <Select<number | "All"> value={warehouseId} onValueChange={(v) => setWarehouseId(v ?? "All")}>
            <SelectTrigger className="h-11! w-full text-base">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="All" className="text-base">All warehouses</SelectItem>
              {(warehouses ?? []).map((w) => (
                <SelectItem key={w.warehouseId} value={w.warehouseId} className="text-base">
                  {w.code}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="flex flex-col gap-1.5">
          <Label className="text-base">From</Label>
          <Input type="date" value={from} onChange={(e) => setFrom(e.target.value)} className="h-11 text-base" />
        </div>

        <div className="flex flex-col gap-1.5">
          <Label className="text-base">To</Label>
          <Input type="date" value={to} onChange={(e) => setTo(e.target.value)} className="h-11 text-base" />
        </div>
      </div>

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

      {!loading && !error && entries !== null && entries.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <ScrollText className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No ledger entries match this filter.</p>
        </div>
      )}

      {!loading && !error && entries !== null && entries.length > 0 && (
        <>
          <Table className="text-base">
            <TableHeader>
              <TableRow>
                <TableHead className="h-12 px-3 text-sm">Date</TableHead>
                <TableHead className="h-12 px-3 text-sm">Item</TableHead>
                <TableHead className="h-12 px-3 text-sm">Warehouse</TableHead>
                <TableHead className="h-12 px-3 text-sm">Direction</TableHead>
                <TableHead className="h-12 px-3 text-sm">Qty</TableHead>
                <TableHead className="h-12 px-3 text-sm">Unit cost</TableHead>
                <TableHead className="h-12 px-3 text-sm">Value</TableHead>
                <TableHead className="h-12 px-3 text-sm">Running balance</TableHead>
                <TableHead className="h-12 px-3 text-sm">Source</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {entries.map((entry) => {
                const item = itemsById.get(entry.itemId)
                const wh = warehousesById.get(entry.warehouseId)
                return (
                  <TableRow key={entry.ledgerId}>
                    <TableCell className="px-3 py-3.5">{new Date(entry.createdAt).toLocaleString()}</TableCell>
                    <TableCell className="px-3 py-3.5">{item?.sku ?? `#${entry.itemId}`}</TableCell>
                    <TableCell className="px-3 py-3.5">{wh?.code ?? `#${entry.warehouseId}`}</TableCell>
                    <TableCell className="px-3 py-3.5">
                      <Badge
                        variant="outline"
                        className={cn(
                          "h-6 w-20 justify-center text-sm",
                          entry.direction === "In"
                            ? "border-transparent bg-success/10 text-success"
                            : "border-transparent bg-destructive/10 text-destructive"
                        )}
                      >
                        {entry.direction}
                      </Badge>
                    </TableCell>
                    <TableCell className="px-3 py-3.5">{entry.qtyBase}</TableCell>
                    <TableCell className="px-3 py-3.5">{entry.unitCost.toFixed(2)}</TableCell>
                    <TableCell className="px-3 py-3.5">{entry.value.toFixed(2)}</TableCell>
                    <TableCell className="px-3 py-3.5 font-medium">{entry.runningBalance}</TableCell>
                    <TableCell className="px-3 py-3.5 text-muted-foreground">
                      {entry.sourceDocType} #{entry.sourceDocId}
                    </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>
  )
}
