"use client"

import { use, useEffect, useMemo, useState } from "react"
import { Printer } from "lucide-react"

import { salesApi } from "@/lib/api/sales"
import { customersApi } from "@/lib/api/customers"
import { itemsApi } from "@/lib/api/items"
import { uomsApi } from "@/lib/api/uoms"
import { baseUomLabel } from "@/lib/uom-label"
import { warehousesApi } from "@/lib/api/warehouses"
import { usersApi } from "@/lib/api/users"
import { errorMessage } from "@/lib/error-map"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Customer } from "@/types/customers"
import { ItemListItem, Uom, Warehouse } from "@/types/master-data"
import { ManagedUser } from "@/types/users"
import { SalesSlip } from "@/types/sales"

export default function SalesSlipPrintPage({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = use(params)
  const slipId = Number(resolvedParams.id)
  const [slip, setSlip] = useState<SalesSlip | null>(null)
  const [customers, setCustomers] = useState<Customer[]>([])
  const [items, setItems] = useState<ItemListItem[]>([])
  const [uoms, setUoms] = useState<Uom[]>([])
  const [warehouses, setWarehouses] = useState<Warehouse[]>([])
  const [users, setUsers] = useState<ManagedUser[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!Number.isFinite(slipId)) {
      setError(`Invalid slip id '${resolvedParams.id}'.`)
      return
    }

    Promise.all([
      customersApi.list({ pageSize: 200 }),
      itemsApi.list({ pageSize: 200 }),
      uomsApi.list({ pageSize: 200 }),
      warehousesApi.list({ pageSize: 200 }),
      usersApi.list({ pageSize: 200 }),
      salesApi.getSlip(slipId),
    ])
      .then(([cust, itemRes, uomRes, whRes, userRes, doc]) => {
        setCustomers(cust.items)
        setItems(itemRes.items)
        setUoms(uomRes.items)
        setWarehouses(whRes.items)
        setUsers(userRes.items)
        setSlip(doc.data)
      })
      .catch((err) => setError(errorMessage(err)))
  }, [resolvedParams.id, slipId])

  const subtotal = useMemo(() => slip?.totals.subtotal ?? 0, [slip])

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

  if (!slip) {
    return <div className="rounded-2xl border border-dashed p-8 text-muted-foreground">{error ?? "Slip print data is loading or unavailable."}</div>
  }

  const customer = customers.find((c) => c.customerId === slip.customerId)
  const warehouse = warehouses.find((w) => w.warehouseId === slip.warehouseId)

  return (
    <div className="mx-auto flex w-full max-w-5xl flex-col gap-6 rounded-3xl border bg-white p-6 shadow-sm print:rounded-none print:border-0 print:p-0 print:shadow-none">
      <div className="flex items-center justify-end print:hidden">
        <Button variant="outline" onClick={() => window.print()}>
          <Printer className="size-4" />
          Print
        </Button>
      </div>

      <div className="border-b pb-5">
        <div className="text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">Sales Slip</div>
        <h1 className="mt-2 text-3xl font-semibold text-foreground">{slip.slipNo}</h1>
        <div className="mt-2 text-sm text-muted-foreground">Status: {slip.status} · Date: {new Date(slip.slipDate).toLocaleDateString()}</div>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <div className="rounded-2xl border bg-muted/20 p-4">
          <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Customer</div>
          <div className="mt-2 text-lg font-semibold text-foreground">{slip.customerSnapshotName}</div>
          <div className="mt-1 text-sm text-muted-foreground">Customer ID: {slip.customerId}</div>
          {customer?.displayName ? <div className="mt-1 text-sm text-muted-foreground">Customer: {customer.displayName}</div> : null}
        </div>
        <div className="rounded-2xl border bg-muted/20 p-4">
          <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Warehouse</div>
          <div className="mt-2 text-lg font-semibold text-foreground">{warehouse?.name ?? `#${slip.warehouseId}`}</div>
          <div className="mt-1 text-sm text-muted-foreground">Code: {warehouse?.code ?? slip.warehouseId}</div>
        </div>
        <div className="rounded-2xl border bg-muted/20 p-4">
          <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Totals</div>
          <div className="mt-2 grid grid-cols-2 gap-2 text-sm">
            <div className="text-muted-foreground">Subtotal</div><div className="text-right font-medium">{slip.totals.subtotal.toFixed(2)}</div>
            <div className="text-muted-foreground">Discount</div><div className="text-right font-medium">{slip.totals.discountTotal.toFixed(2)}</div>
            <div className="text-muted-foreground">Free qty</div><div className="text-right font-medium">{slip.totals.freeQtyTotal.toFixed(2)}</div>
            <div className="text-muted-foreground">Net total</div><div className="text-right font-semibold">{slip.totals.grandTotal.toFixed(2)}</div>
          </div>
        </div>
      </div>

      <div className="overflow-hidden rounded-2xl border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Item</TableHead>
              <TableHead>UOM</TableHead>
              <TableHead className="text-right">Qty</TableHead>
              <TableHead className="text-right">Free</TableHead>
              <TableHead className="text-right">Unit price</TableHead>
              <TableHead className="text-right">Line total</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {slip.lines.map((line) => (
              <TableRow key={line.salesSlipLineId}>
                <TableCell>
                  <div className="font-medium text-foreground">{line.description}</div>
                  <div className="text-xs text-muted-foreground">SKU {items.find((i) => i.itemId === line.itemId)?.sku ?? `#${line.itemId}`}</div>
                </TableCell>
                <TableCell>{baseUomLabel(items, uoms, line.itemId)}</TableCell>
                <TableCell className="text-right">{line.qty.toFixed(0)}</TableCell>
                <TableCell className="text-right">{line.freeQty > 0 ? line.freeQty.toFixed(0) : "—"}</TableCell>
                <TableCell className="text-right">{line.unitPrice.toFixed(2)}</TableCell>
                <TableCell className="text-right font-medium">{line.lineTotal.toFixed(2)}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      <div className="rounded-2xl border bg-muted/20 p-4">
        <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Cashier</div>
        <div className="mt-2 text-sm text-foreground">{users.find((u) => u.userId === slip.cashierUserId)?.displayName ?? `#${slip.cashierUserId}`}</div>
        <div className="mt-3 text-sm text-muted-foreground">Subtotal: {subtotal.toFixed(2)}</div>
      </div>
    </div>
  )
}
