"use client"

import { useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { ChevronLeft, ChevronRight, Eye, Filter, FileText, Plus, Printer } from "lucide-react"

import { salesApi } from "@/lib/api/sales"
import { errorMessage } from "@/lib/error-map"
import { Button, buttonVariants } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { PaginationMeta } from "@/types/common"
import { SalesInvoiceStatus, SalesInvoiceSummary } from "@/types/sales"
import { cn } from "@/lib/utils"

type StatusFilter = SalesInvoiceStatus | "All"

const PAGE_SIZE = 10
const tabs = ["All", "Draft", "Posted", "Cancelled"] as const

function statusClass(status: SalesInvoiceStatus) {
  switch (status) {
    case "Draft":
      return "border-amber-200 bg-amber-50 text-amber-800"
    case "Posted":
      return "border-emerald-200 bg-emerald-50 text-emerald-800"
    case "Cancelled":
      return "border-rose-200 bg-rose-50 text-rose-800"
  }
}

export default function SalesInvoicesPage() {
  const [rows, setRows] = useState<SalesInvoiceSummary[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [status, setStatus] = useState<StatusFilter>("All")
  const [searchInput, setSearchInput] = useState("")
  const [query, setQuery] = useState("")
  const [page, setPage] = useState(1)

  useEffect(() => {
    const timeout = setTimeout(() => setQuery(searchInput.trim()), 300)
    return () => clearTimeout(timeout)
  }, [searchInput])

  useEffect(() => setPage(1), [query, status])

  useEffect(() => {
    setError(null)
    salesApi
      .listInvoices({ page, pageSize: PAGE_SIZE, status: status === "All" ? undefined : status })
      .then((res) => {
        setRows(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }, [page, status])

  const visibleRows = useMemo(
    () =>
      rows?.filter((row) =>
        `${row.invoiceNo} ${row.customerSnapshotName}`.toLowerCase().includes(query.toLowerCase())
      ) ?? [],
    [rows, query]
  )
  const hasFilters = status !== "All" || query.length > 0
  const grossTotal = visibleRows.reduce((sum, row) => sum + row.totals.subtotal, 0)
  const discountTotal = visibleRows.reduce((sum, row) => sum + row.totals.discountTotal, 0)
  const netTotal = visibleRows.reduce((sum, row) => sum + row.totals.grandTotal, 0)
  const printHref = `/print/sales/invoices?status=${encodeURIComponent(status)}&q=${encodeURIComponent(query)}`

  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>
          <h1 className="text-2xl font-bold text-foreground">Sales Invoices</h1>
          <p className="text-base text-muted-foreground">Invoice register with filters, posting flow, and settlement tracking.</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link
            href={printHref}
            target="_blank"
            rel="noopener noreferrer"
            className={cn(buttonVariants({ variant: "outline", size: "lg" }))}
          >
            <Printer className="size-5" />
            Print batch
          </Link>
          <Link href="/dashboard/sales/invoices/new" className={cn(buttonVariants({ size: "lg" }))}>
            <Plus className="size-5" />
            New Invoice
          </Link>
        </div>
      </div>

      <div className="rounded-2xl border bg-card shadow-sm">
        <div className="flex flex-col gap-3 border-b px-4 py-4 lg:flex-row lg:items-center">
          <div className="flex flex-wrap gap-2">
            {tabs.map((t) => (
              <button
                key={t}
                onClick={() => setStatus(t)}
                className={cn(
                  "rounded-full border px-3 py-1.5 text-xs font-medium transition-colors",
                  status === t ? "border-primary bg-primary text-primary-foreground" : "border-border text-muted-foreground hover:text-foreground"
                )}
              >
                {t}
              </button>
            ))}
          </div>

          <div className="flex flex-1 flex-col gap-3 lg:flex-row lg:items-center lg:justify-end">
            <Input
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              placeholder="Filter by customer or invoice number"
              className="h-12 w-full lg:max-w-sm"
            />
            <Button variant="outline" size="sm" className="lg:ml-auto">
              <Filter className="size-4" />
              Advanced
            </Button>
          </div>
        </div>

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

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

        {!error && rows !== null && visibleRows.length === 0 && (
          <div className="flex flex-col items-center gap-4 px-4 py-20 text-center">
            <FileText className="size-12 text-muted-foreground" />
            <p className="text-base text-muted-foreground">{hasFilters ? "No invoices match your filters." : "No invoices yet."}</p>
          </div>
        )}

        {!error && rows !== null && visibleRows.length > 0 && (
          <>
            <div className="overflow-x-auto">
              <Table className="text-base">
                <TableHeader>
                  <TableRow>
                    <TableHead className="h-12 px-4 text-sm">Invoice</TableHead>
                    <TableHead className="h-12 px-4 text-sm">Customer</TableHead>
                    <TableHead className="h-12 px-4 text-sm">Date</TableHead>
                    <TableHead className="h-12 px-4 text-sm">Due</TableHead>
                    <TableHead className="h-12 px-4 text-sm text-right">Lines</TableHead>
                    <TableHead className="h-12 px-4 text-sm text-right">Gross</TableHead>
                    <TableHead className="h-12 px-4 text-sm text-right">Discount</TableHead>
                    <TableHead className="h-12 px-4 text-sm text-right">Net</TableHead>
                    <TableHead className="h-12 px-4 text-sm">Status</TableHead>
                    <TableHead className="h-12 px-4 text-sm text-right">View</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {visibleRows.map((row) => (
                    <TableRow key={row.salesInvoiceId} className="hover:bg-muted/40">
                      <TableCell className="px-4 py-3.5 font-medium">
                        <Link href={`/dashboard/sales/invoices/${row.salesInvoiceId}`} className="hover:underline">
                          {row.invoiceNo}
                        </Link>
                      </TableCell>
                      <TableCell className="px-4 py-3.5">{row.customerSnapshotName}</TableCell>
                      <TableCell className="px-4 py-3.5 text-muted-foreground">{new Date(row.createdAt).toLocaleDateString()}</TableCell>
                      <TableCell className="px-4 py-3.5 text-muted-foreground">{new Date(row.invoiceDate).toLocaleDateString()}</TableCell>
                      <TableCell className="px-4 py-3.5 text-right font-mono tabular-nums">{row.totals.freeQtyTotal.toFixed(2)}</TableCell>
                      <TableCell className="px-4 py-3.5 text-right font-mono tabular-nums">{row.totals.subtotal.toFixed(2)}</TableCell>
                      <TableCell className="px-4 py-3.5 text-right font-mono tabular-nums text-muted-foreground">-{row.totals.discountTotal.toFixed(2)}</TableCell>
                      <TableCell className="px-4 py-3.5 text-right font-mono font-semibold tabular-nums">{row.totals.grandTotal.toFixed(2)}</TableCell>
                      <TableCell className="px-4 py-3.5">
                        <Badge variant="outline" className={statusClass(row.status)}>
                          {row.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="px-4 py-3.5 text-right">
                        <Link
                          href={`/dashboard/sales/invoices/${row.salesInvoiceId}`}
                          className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))}
                          aria-label={`View invoice ${row.invoiceNo}`}
                        >
                          <Eye className="size-4" />
                        </Link>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            <div className="border-t px-4 py-3">
              <div className="grid gap-3 text-sm md:grid-cols-3">
                <div className="rounded-lg border bg-muted/20 px-3 py-2">
                  <div className="text-muted-foreground">Gross total</div>
                  <div className="font-mono text-base font-semibold tabular-nums">{grossTotal.toFixed(2)}</div>
                </div>
                <div className="rounded-lg border bg-muted/20 px-3 py-2">
                  <div className="text-muted-foreground">Discount total</div>
                  <div className="font-mono text-base font-semibold tabular-nums">-{discountTotal.toFixed(2)}</div>
                </div>
                <div className="rounded-lg border bg-muted/20 px-3 py-2">
                  <div className="text-muted-foreground">Net total</div>
                  <div className="font-mono text-base font-semibold tabular-nums">{netTotal.toFixed(2)}</div>
                </div>
              </div>
            </div>

            {pagination && pagination.totalPages > 1 && (
              <div className="flex flex-col gap-3 border-t px-4 py-4 sm:flex-row sm:items-center sm: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>
    </div>
  )
}
