import { useQuery } from "@tanstack/react-query"
import { apiFetch } from '@/utils/api';
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 "@/utils/formatCurrency"

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

function TableSkeleton() {
  return (
    <div className="space-y-3 p-4">
      {Array.from({ length: 5 }).map((_, i) => (
        <div key={i} className="h-8 animate-pulse rounded bg-muted" />
      ))}
    </div>
  );
}

export function TopOverstockedProducts() {
  const { data, isError, isLoading } = useQuery<Product[]>({
    queryKey: ["top-overstocked-products"],
    queryFn: async () => {
      const response = await apiFetch(`${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>
        {isError ? (
          <p className="text-sm text-destructive">Failed to load overstocked products</p>
        ) : isLoading ? (
          <TableSkeleton />
        ) : (
          <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(Number(product.excess_cost))}</TableCell>
                    <TableCell className="text-right">{formatCurrency(Number(product.excess_retail))}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </ScrollArea>
        )}
      </CardContent>
    </>
  )
}
