import { useQuery } from "@tanstack/react-query"
import { CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import config from "@/config"
import { formatCurrency } from "@/lib/utils"

interface Product {
  pid: number;
  sku: string;
  title: string;
  stock_quantity: number;
  overstocked_amt: number;
  excess_cost: number;
  excess_retail: number;
}

export function TopOverstockedProducts() {
  const { data } = useQuery<Product[]>({
    queryKey: ["top-overstocked-products"],
    queryFn: async () => {
      const response = await fetch(`${config.apiUrl}/dashboard/overstock/products?limit=50`)
      if (!response.ok) {
        throw new Error("Failed to fetch overstocked products")
      }
      return response.json()
    },
  })

  return (
    <>
      <CardHeader>
        <CardTitle className="text-xl font-medium">Top Overstocked Products</CardTitle>
      </CardHeader>
      <CardContent>
        <ScrollArea className="h-[300px] w-full">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Product</TableHead>
                <TableHead className="text-right">Stock</TableHead>
                <TableHead className="text-right">Excess</TableHead>
                <TableHead className="text-right">Cost</TableHead>
                <TableHead className="text-right">Retail</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {data?.map((product) => (
                <TableRow key={product.pid}>
                  <TableCell>
                    <a
                      href={`https://backend.acherryontop.com/product/${product.pid}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="hover:underline"
                    >
                      {product.title}
                    </a>
                    <div className="text-sm text-muted-foreground">{product.sku}</div>
                  </TableCell>
                  <TableCell className="text-right">{product.stock_quantity}</TableCell>
                  <TableCell className="text-right">{product.overstocked_amt}</TableCell>
                  <TableCell className="text-right">{formatCurrency(product.excess_cost)}</TableCell>
                  <TableCell className="text-right">{formatCurrency(product.excess_retail)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </ScrollArea>
      </CardContent>
    </>
  )
} 