"use client"

import { useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { ArrowLeft, 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 { errorMessage } from "@/lib/error-map"
import { Button, buttonVariants } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { cn } from "@/lib/utils"
import { Customer } from "@/types/customers"
import { ItemListItem, Uom, Warehouse } from "@/types/master-data"
import { SalesInvoice } from "@/types/sales"

export default function SalesInvoicePrintPage({ params }: { params: { id: string } }) {
  const invoiceId = Number(params.id)
  const [invoice, setInvoice] = useState<SalesInvoice | null>(null)
  const [customers, setCustomers] = useState<Customer[]>([])
  const [items, setItems] = useState<ItemListItem[]>([])
  const [uoms, setUoms] = useState<Uom[]>([])
  const [warehouses, setWarehouses] = useState<Warehouse[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!Number.isFinite(invoiceId)) {
      setError(`Invalid invoice id '${params.id}'.`)
      return
    }
    Promise.all([
      customersApi.list({ pageSize: 200 }),
      itemsApi.list({ pageSize: 200 }),
      uomsApi.list({ pageSize: 200 }),
      warehousesApi.list({ pageSize: 200 }),
      salesApi.getInvoice(invoiceId),
    ])
      .then(([cust, itemRes, uomRes, whRes, doc]) => {
        setCustomers(cust.items)
        setItems(itemRes.items)
        setUoms(uomRes.items)
        setWarehouses(whRes.items)
        setInvoice(doc.data)
      })
      .catch((err) => setError(errorMessage(err)))
  }, [params.id, invoiceId])

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

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

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

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

  return (
    <div className="flex flex-col gap-6 print:block print:gap-0">
      <div className="flex items-center justify-between gap-3 print:hidden">
        <div className="flex items-center gap-3">
          <Link href={`/dashboard/sales/invoices/${invoice.salesInvoiceId}`} className={cn(buttonVariants({ variant: "outline", size: "icon" }))}>
            <ArrowLeft className="size-4" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-foreground">Invoice Print</h1>
            <p className="text-base text-muted-foreground">{invoice.invoiceNo}</p>
          </div>
        </div>
        <Button variant="outline" onClick={() => window.print()}>
          <Printer className="size-4" />
          Print
        </Button>
      </div>

      <div className="invoice-sheet rounded-3xl border bg-white p-6 shadow-sm print:rounded-none print:border-0 print:p-0 print:shadow-none">
        <div className="invoice-header mb-6 grid gap-4 border-b pb-5 md:grid-cols-[1.4fr_1fr]">
          <div>
            <div className="text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">Sales Invoice</div>
            <h1 className="mt-2 text-3xl font-semibold text-foreground">{invoice.invoiceNo}</h1>
            <div className="mt-2 text-sm text-muted-foreground">Status: {invoice.status} · Type: {invoice.invoiceType}</div>
          </div>
          <div className="grid gap-2 text-sm md:justify-items-end">
            <div className="font-semibold text-foreground">ERP Core Trading</div>
            <div className="text-muted-foreground">Company details are not configured for this print view.</div>
            <div className="text-muted-foreground">Invoice date: {new Date(invoice.invoiceDate).toLocaleDateString()}</div>
            <div className="text-muted-foreground">Printed: {new Date().toLocaleString()}</div>
            <div className="text-muted-foreground">Free qty total: {freeQtyTotal.toFixed(2)}</div>
          </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">{invoice.customerSnapshotName}</div>
            <div className="mt-1 text-sm text-muted-foreground">Customer ID: {invoice.customerId}</div>
            {invoice.customerSnapshotTaxNo ? <div className="mt-1 text-sm text-muted-foreground">Tax No: {invoice.customerSnapshotTaxNo}</div> : null}
            {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 ?? `#${invoice.warehouseId}`}</div>
            <div className="mt-1 text-sm text-muted-foreground">Code: {warehouse?.code ?? invoice.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">{invoice.totals.subtotal.toFixed(2)}</div>
              <div className="text-muted-foreground">Discount</div><div className="text-right font-medium">{invoice.totals.discountTotal.toFixed(2)}</div>
              <div className="text-muted-foreground">Free qty</div><div className="text-right font-medium">{freeQtyTotal.toFixed(2)}</div>
              <div className="text-muted-foreground">Tax</div><div className="text-right font-medium">{invoice.totals.taxTotal.toFixed(2)}</div>
              <div className="text-muted-foreground">Net payable</div><div className="text-right font-semibold">{invoice.totals.netPayable.toFixed(2)}</div>
            </div>
          </div>
        </div>

        <div className="mt-6 overflow-hidden rounded-2xl border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[34%]">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">Discount</TableHead>
                <TableHead className="text-right">Tax</TableHead>
                <TableHead className="text-right">Line total</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {invoice.lines.map((line) => (
                <TableRow key={line.salesInvoiceLineId}>
                  <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(2)}</TableCell>
                  <TableCell className="text-right">{line.freeQty > 0 ? line.freeQty.toFixed(2) : "—"}</TableCell>
                  <TableCell className="text-right">{line.unitPrice.toFixed(2)}</TableCell>
                  <TableCell className="text-right">{line.discountAmount.toFixed(2)}</TableCell>
                  <TableCell className="text-right">{line.taxAmount.toFixed(2)}</TableCell>
                  <TableCell className="text-right font-medium">{line.lineTotal.toFixed(2)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {invoice.lines.some((line) => line.freeQty > 0) ? (
          <div className="mt-6 rounded-2xl border border-dashed p-4 print:break-inside-avoid">
            <div className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">Free issue summary</div>
            <div className="mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              {invoice.lines.filter((line) => line.freeQty > 0).map((line) => (
                <div key={line.salesInvoiceLineId} className="rounded-xl border bg-emerald-500/5 p-3">
                  <div className="font-medium text-foreground">{line.description}</div>
                  <div className="mt-1 text-sm text-muted-foreground">Invoice qty: {line.qty.toFixed(2)}</div>
                  <div className="mt-1 text-sm text-foreground">Free qty: {line.freeQty.toFixed(2)}</div>
                </div>
              ))}
            </div>
          </div>
        ) : null}

        <div className="mt-6 grid gap-4 lg:grid-cols-[1fr_360px]">
          <div className="rounded-2xl border bg-muted/20 p-4">
            <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Notes</div>
            <p className="mt-2 text-sm text-muted-foreground">Standard invoice print view.</p>
          </div>
          <div className="rounded-2xl border p-4">
            <div className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">Totals</div>
            <div className="mt-3 space-y-2 text-sm">
              <div className="flex justify-between"><span className="text-muted-foreground">Subtotal</span><span>{invoice.totals.subtotal.toFixed(2)}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">Discount total</span><span>{invoice.totals.discountTotal.toFixed(2)}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">Free qty total</span><span>{invoice.totals.freeQtyTotal.toFixed(2)}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">Tax total</span><span>{invoice.totals.taxTotal.toFixed(2)}</span></div>
              <div className="flex justify-between border-t pt-2 text-base font-semibold"><span>Net payable</span><span>{invoice.totals.netPayable.toFixed(2)}</span></div>
              <div className="flex justify-between text-muted-foreground"><span>Paid</span><span>{invoice.totals.paidAmount.toFixed(2)}</span></div>
              <div className="flex justify-between text-muted-foreground"><span>Balance</span><span>{invoice.totals.balanceAmount.toFixed(2)}</span></div>
            </div>
          </div>
        </div>

      </div>
    </div>
  )
}
