import { useQuery } from "@tanstack/react-query"
import { CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Progress } from "@/components/ui/progress"
import config from "@/config"

interface VendorMetrics {
  vendor: string
  avg_lead_time: number
  on_time_delivery_rate: number
  avg_fill_rate: number
  total_orders: number
  active_orders: number
  overdue_orders: number
}

export function VendorPerformance() {
  const { data: vendors } = useQuery<VendorMetrics[]>({
    queryKey: ["vendor-metrics"],
    queryFn: async () => {
      const response = await fetch(`${config.apiUrl}/dashboard/vendor/performance`)
      if (!response.ok) {
        throw new Error("Failed to fetch vendor metrics")
      }
      return response.json()
    },
  })

  // Sort vendors by on-time delivery rate
  const sortedVendors = vendors
    ?.sort((a, b) => b.on_time_delivery_rate - a.on_time_delivery_rate)

  return (
    <>
      <CardHeader>
        <CardTitle className="text-lg font-medium">Top Vendor Performance</CardTitle>
      </CardHeader>
      <CardContent className="max-h-[400px] overflow-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Vendor</TableHead>
              <TableHead>On-Time</TableHead>
              <TableHead className="text-right">Fill Rate</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedVendors?.map((vendor) => (
              <TableRow key={vendor.vendor}>
                <TableCell className="font-medium">{vendor.vendor}</TableCell>
                <TableCell>
                  <div className="flex items-center gap-2">
                    <Progress
                      value={vendor.on_time_delivery_rate}
                      className="h-2"
                    />
                    <span className="w-10 text-sm">
                      {vendor.on_time_delivery_rate.toFixed(0)}%
                    </span>
                  </div>
                </TableCell>
                <TableCell className="text-right">
                  {vendor.avg_fill_rate.toFixed(0)}%
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </>
  )
} 