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 { format } from "date-fns"

interface Product {
  pid: number;
  sku: string;
  title: string;
  stock_quantity: number;
  daily_sales_avg: string;
  reorder_qty: number;
  last_purchase_date: string | null;
}

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 TopReplenishProducts() {
  const { data, isError, isLoading } = useQuery<Product[]>({
    queryKey: ["top-replenish-products"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/dashboard/replenish/products?limit=50`)
      if (!response.ok) throw new Error("Failed to fetch products to replenish");
      return response.json()
    },
  })

  return (
    <>
      <CardHeader>
        <CardTitle className="text-xl font-medium">Top Products To Replenish</CardTitle>
      </CardHeader>
      <CardContent>
        {isError ? (
          <p className="text-sm text-destructive">Failed to load replenish products</p>
        ) : isLoading ? (
          <TableSkeleton />
        ) : (
          <ScrollArea className="max-h-[630px] w-full overflow-y-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Product</TableHead>
                  <TableHead className="text-right">Stock</TableHead>
                  <TableHead className="text-right">Daily Sales</TableHead>
                  <TableHead className="text-right">Reorder Qty</TableHead>
                  <TableHead>Last Purchase</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">{Number(product.daily_sales_avg).toFixed(1)}</TableCell>
                    <TableCell className="text-right">{product.reorder_qty}</TableCell>
                    <TableCell className="whitespace-nowrap">{product.last_purchase_date ? format(new Date(product.last_purchase_date), 'M/dd/yyyy') : '-'}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </ScrollArea>
        )}
      </CardContent>
    </>
  )
}
