"use client"

import { useState, useMemo } from "react"
import { usePaginatedQuery } from "convex/react"
import { useRouter } from "next/navigation"
import { api } from "../../../../../../convex/_generated/api"
import { formatPrice } from "@repo/utils"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { HugeiconsIcon } from "@hugeicons/react"
import {
  Search01Icon,
  Cancel01Icon,
  ArrowRight01Icon,
} from "@hugeicons/core-free-icons"
import { OrderStatusBadge } from "@/components/orders/shared/OrderStatusBadge"
import { OrderPaymentBadge } from "@/components/orders/shared/OrderPaymentBadge"
import {
  ORDER_STATUS_CONFIG,
  type OrderStatus,
} from "@/components/orders/shared/statusConfig"

// ─── Status filter options ────────────────────────────────────────────────────

const STATUS_OPTIONS = [
  { value: "all", label: "All statuses" },
  ...Object.entries(ORDER_STATUS_CONFIG).map(([value, config]) => ({
    value,
    label: config.label,
  })),
]

// ─── Skeleton ─────────────────────────────────────────────────────────────────

function TableSkeleton() {
  return (
    <>
      {Array.from({ length: 10 }).map((_, i) => (
        <TableRow key={i}>
          <TableCell>
            <Skeleton className="h-4 w-24" />
          </TableCell>
          <TableCell>
            <Skeleton className="h-4 w-40" />
          </TableCell>
          <TableCell>
            <Skeleton className="h-4 w-24" />
          </TableCell>
          <TableCell>
            <Skeleton className="h-5 w-20 rounded-full" />
          </TableCell>
          <TableCell>
            <Skeleton className="h-5 w-16 rounded-full" />
          </TableCell>
          <TableCell>
            <Skeleton className="h-4 w-16" />
          </TableCell>
          <TableCell>
            <Skeleton className="size-4" />
          </TableCell>
        </TableRow>
      ))}
    </>
  )
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function OrdersPage() {
  const router = useRouter()
  const [searchInput, setSearchInput] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")

  const {
    results,
    status,
    loadMore,
  } = usePaginatedQuery(
    api.orders.listAll,
    statusFilter !== "all" ? { status: statusFilter } : {},
    { initialNumItems: 25 },
  )

  const isLoading = status === "LoadingFirstPage"

  // Client-side search over loaded results.
  // NOTE: filtered to the currently loaded page only — no server-side search
  // index exists yet. Add api.orders.searchByOrderNumberOrEmail when needed.
  const orders = useMemo(() => {
    const q = searchInput.trim().toLowerCase()
    if (!q) return results
    return results.filter(
      (o) =>
        o.orderNumber.toLowerCase().includes(q) ||
        o.email.toLowerCase().includes(q),
    )
  }, [results, searchInput])

  const isSearching = searchInput.trim().length > 0

  function emptyMessage() {
    if (isSearching) return `No orders match "${searchInput.trim()}".`
    if (statusFilter !== "all") {
      const label =
        ORDER_STATUS_CONFIG[statusFilter as OrderStatus]?.label ?? statusFilter
      return `No orders with status "${label}".`
    }
    return "No orders yet."
  }

  return (
    <main className="flex flex-1 flex-col gap-4 p-4 pt-0">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">Orders</h1>
      </div>

      {/* Toolbar */}
      <div className="flex items-center gap-2">
        <div className="relative max-w-sm flex-1">
          <HugeiconsIcon
            icon={Search01Icon}
            strokeWidth={2}
            className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
          />
          <Input
            placeholder="Search by order # or email…"
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            className="pl-8 pr-8"
          />
          {searchInput && (
            <button
              type="button"
              className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              onClick={() => setSearchInput("")}
              aria-label="Clear search"
            >
              <HugeiconsIcon
                icon={Cancel01Icon}
                strokeWidth={2}
                className="size-4"
              />
            </button>
          )}
        </div>

        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger size="default" className="w-40">
            <SelectValue placeholder="All statuses" />
          </SelectTrigger>
          <SelectContent>
            {STATUS_OPTIONS.map((opt) => (
              <SelectItem key={opt.value} value={opt.value}>
                {opt.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Table */}
      <div className="rounded-lg border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead scope="col">Order #</TableHead>
              <TableHead scope="col">Customer</TableHead>
              <TableHead scope="col">Date</TableHead>
              <TableHead scope="col">Status</TableHead>
              <TableHead scope="col">Payment</TableHead>
              <TableHead scope="col" className="text-right">
                Total
              </TableHead>
              <TableHead scope="col" className="w-8" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableSkeleton />
            ) : orders.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={7}
                  className="py-16 text-center text-sm text-muted-foreground"
                >
                  {emptyMessage()}
                </TableCell>
              </TableRow>
            ) : (
              orders.map((order) => (
                <TableRow
                  key={order._id}
                  className="cursor-pointer"
                  onClick={() => router.push(`/orders/${order._id}`)}
                >
                  <TableCell className="font-mono text-xs">
                    {order.orderNumber}
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {order.email}
                  </TableCell>
                  <TableCell className="whitespace-nowrap text-xs text-muted-foreground">
                    {new Date(order.createdAt).toLocaleDateString("en-GB", {
                      day: "numeric",
                      month: "short",
                      year: "numeric",
                    })}
                  </TableCell>
                  <TableCell>
                    <OrderStatusBadge status={order.status} />
                  </TableCell>
                  <TableCell>
                    <OrderPaymentBadge status={order.paymentStatus} />
                  </TableCell>
                  <TableCell className="text-right font-medium">
                    {formatPrice(order.total, order.currency.toUpperCase())}
                  </TableCell>
                  <TableCell>
                    <HugeiconsIcon
                      icon={ArrowRight01Icon}
                      strokeWidth={2}
                      className="size-4 text-muted-foreground"
                      aria-hidden="true"
                    />
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination footer — list mode only (not shown during client-side search) */}
      {!isSearching && (
        <div className="flex items-center justify-between text-sm text-muted-foreground">
          <span>
            {status === "Exhausted"
              ? `${results.length} order${results.length !== 1 ? "s" : ""} total`
              : `${results.length} loaded`}
          </span>
          {status === "CanLoadMore" && (
            <Button variant="outline" size="sm" onClick={() => loadMore(25)}>
              Load more
            </Button>
          )}
        </div>
      )}
    </main>
  )
}
