import { useQuery } from '@tanstack/react-query'
import { getDashboardKPIs } from '../../../api/analytics'
import { useDashboardTimeframe } from '../DashboardTimeframeContext'

export default function TopProductsWidget() {
  const { dateFrom, dateTo } = useDashboardTimeframe()
  const { data, isLoading, error } = useQuery({
    queryKey: ['analytics-kpis', dateFrom, dateTo],
    queryFn: () => getDashboardKPIs(dateFrom, dateTo),
    staleTime: 60_000,
  })

  if (isLoading) return <div className="h-52 animate-pulse rounded-lg bg-surface-muted" />
  if (error) return <p className="text-xs text-red-500">Failed to load top products</p>
  if (!data || data.top_products.length === 0) {
    return <p className="text-xs text-content-muted text-center py-8">No data yet</p>
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-border-light text-left">
            <th className="py-2 pr-3 text-content-secondary font-medium text-xs">PIM-ID</th>
            <th className="py-2 pr-3 text-content-secondary font-medium text-xs">Product</th>
            <th className="py-2 pr-3 text-content-secondary font-medium text-xs">Category</th>
            <th className="py-2 text-content-secondary font-medium text-right text-xs">Orders</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-border-light">
          {data.top_products.map((p, i) => (
            <tr key={`${p.pim_id}-${i}`} className="hover:bg-surface-hover">
              <td className="py-1.5 pr-3 font-mono text-xs text-content-muted">{p.pim_id}</td>
              <td className="py-1.5 pr-3 text-xs text-content truncate max-w-[140px]">{p.product_name || '—'}</td>
              <td className="py-1.5 pr-3 text-xs text-content-muted">{p.category}</td>
              <td className="py-1.5 font-medium text-xs text-content text-right">{p.order_count}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
