"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 { bundleApi } from "@/lib/api/bundles"
import { customersApi } from "@/lib/api/customers"
import { warehousesApi } from "@/lib/api/warehouses"
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { PaginationMeta } from "@/types/common"
import { Customer } from "@/types/customers"
import { Warehouse } from "@/types/master-data"
import { BundleSaleStatus, BundleSaleSummary } from "@/types/bundles"
import { cn } from "@/lib/utils"

type StatusFilter = BundleSaleStatus | "All"

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

function statusClass(status: BundleSaleStatus) {
  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 BundleSalesPage() {
  const [rows, setRows] = useState<BundleSaleSummary[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [status, setStatus] = useState<StatusFilter>("All")
  const [customerId, setCustomerId] = useState<number | null>(null)
  const [warehouseId, setWarehouseId] = useState<number | null>(null)
  const [searchInput, setSearchInput] = useState("")
  const [query, setQuery] = useState("")
  const [page, setPage] = useState(1)
  const [showFilters, setShowFilters] = useState(false)
  const [customers, setCustomers] = useState<Customer[]>([])
  const [warehouses, setWarehouses] = useState<Warehouse[]>([])

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

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

  useEffect(() => {
    Promise.all([customersApi.list({ pageSize: 200 }), warehousesApi.list({ pageSize: 200 })])
      .then(([cust, whRes]) => {
        setCustomers(cust.items)
        setWarehouses(whRes.items)
      })
      .catch((err) => setError(errorMessage(err)))
  }, [])

  useEffect(() => {
    setError(null)
    bundleApi
      .listBundles({
        page,
        pageSize: PAGE_SIZE,
        status: status === "All" ? undefined : status,
        q: query || undefined,
        customerId: customerId ?? undefined,
        warehouseId: warehouseId ?? undefined,
      })
      .then((res) => {
        setRows(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }, [page, status, query, customerId, warehouseId])

  const visibleRows = useMemo(
    () =>
      rows?.filter((row) => {
        const matchesStatus = status === "All" || row.status === status
        const matchesQuery =
          `${row.bundleNo} ${row.bundleName} ${row.customerSnapshotName} ${row.bundleCode}`
            .toLowerCase()
            .includes(query.toLowerCase())
        return matchesStatus && matchesQuery
      }) ?? [],
    [rows, query, status]
  )
  const hasFilters = status !== "All" || query.length > 0 || customerId !== null || warehouseId !== null
  const bundleTotal = visibleRows.reduce((sum, row) => sum + row.grandTotal, 0)
  const printHref = `/print/sales/bundles?status=${encodeURIComponent(status)}&q=${encodeURIComponent(query)}&customerId=${customerId ?? ""}&warehouseId=${warehouseId ?? ""}`

  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">Bundle Sales</h1>
          <p className="text-base text-muted-foreground">Fixed bundle register with draft, posted, and cancelled states.</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/bundles/new" className={cn(buttonVariants({ size: "lg" }))}>
            <Plus className="size-5" />
            New Bundle
          </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 bundle, code, or customer"
              className="h-12 w-full lg:max-w-sm"
            />
            <Button variant="outline" size="sm" className="lg:ml-auto" onClick={() => setShowFilters((v) => !v)}>
              <Filter className="size-4" />
              Advanced
            </Button>
          </div>
        </div>

        {showFilters && (
          <div className="grid gap-4 border-b px-4 py-4 md:grid-cols-3">
            <div className="space-y-1.5">
              <div className="text-xs font-medium text-muted-foreground">Customer</div>
              <Select value={customerId ? String(customerId) : "all"} onValueChange={(v) => setCustomerId(v === "all" ? null : Number(v))}>
                <SelectTrigger className="h-10">
                  <SelectValue placeholder="All customers" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All customers</SelectItem>
                  {customers.map((c) => (
                    <SelectItem key={c.customerId} value={String(c.customerId)}>
                      {c.customerCode} - {c.displayName ?? c.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <div className="text-xs font-medium text-muted-foreground">Warehouse</div>
              <Select value={warehouseId ? String(warehouseId) : "all"} onValueChange={(v) => setWarehouseId(v === "all" ? null : Number(v))}>
                <SelectTrigger className="h-10">
                  <SelectValue placeholder="All warehouses" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All warehouses</SelectItem>
                  {warehouses.map((w) => (
                    <SelectItem key={w.warehouseId} value={String(w.warehouseId)}>
                      {w.code} - {w.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-end gap-2">
              <Button
                type="button"
                variant="outline"
                className="flex-1"
                onClick={() => {
                  setCustomerId(null)
                  setWarehouseId(null)
                  setStatus("All")
                  setSearchInput("")
                  setQuery("")
                }}
              >
                Reset
              </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 bundle sales match your filters." : "No bundle sales 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">Bundle</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 text-right">Price</TableHead>
                    <TableHead className="h-12 px-4 text-sm text-right">Grand</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.bundleSaleId} className="hover:bg-muted/40">
                      <TableCell className="px-4 py-3.5 font-medium">
                        <Link href={`/dashboard/sales/bundles/${row.bundleSaleId}`} className="hover:underline">
                          {row.bundleNo}
                        </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-right font-mono tabular-nums">{row.bundlePrice.toFixed(2)}</TableCell>
                      <TableCell className="px-4 py-3.5 text-right font-mono font-semibold tabular-nums">{row.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">
                        <div className="inline-flex gap-2">
                          <Link href={`/dashboard/sales/bundles/${row.bundleSaleId}`} className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))} aria-label={`View bundle ${row.bundleNo}`}>
                            <Eye className="size-4" />
                          </Link>
                          <Link href={`/print/sales/bundles/${row.bundleSaleId}`} target="_blank" rel="noopener noreferrer" className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))} aria-label={`Print bundle ${row.bundleNo}`}>
                            <Printer className="size-4" />
                          </Link>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            <div className="border-t px-4 py-3">
              <div className="grid gap-3 text-sm md:grid-cols-2">
                <div className="rounded-lg border bg-muted/20 px-3 py-2">
                  <div className="text-muted-foreground">Rows loaded</div>
                  <div className="font-mono text-base font-semibold tabular-nums">{visibleRows.length}</div>
                </div>
                <div className="rounded-lg border bg-muted/20 px-3 py-2">
                  <div className="text-muted-foreground">Grand total</div>
                  <div className="font-mono text-base font-semibold tabular-nums">{bundleTotal.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>
  )
}
