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

function Skeleton() {
  return (
    <div className="animate-pulse grid grid-cols-2 gap-2">
      {[0, 1, 2, 3, 4, 5].map((i) => (
        <div key={i} className="h-16 rounded-lg bg-surface-muted" />
      ))}
    </div>
  )
}

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

  if (isLoading) return <Skeleton />
  if (error) return <p className="text-xs text-red-500">Failed to load KPIs</p>
  if (!data) return null

  const cards = [
    { label: 'Total Orders', value: data.summary.total_orders },
    { label: 'Completed', value: data.summary.completed_orders },
    { label: 'Rendering Items', value: data.summary.total_rendering_items },
    { label: 'Revenue', value: `€ ${data.summary.total_revenue.toFixed(2)}` },
    { label: 'Rendered Products', value: data.product_stats.unique_products_rendered },
    { label: 'CAD Coverage', value: `${data.product_stats.products_with_cad} / ${data.product_stats.total_products}` },
  ]

  return (
    <div className="grid grid-cols-2 gap-2">
      {cards.map(({ label, value }) => (
        <div
          key={label}
          className="rounded-lg border border-border-default p-3"
          style={{ backgroundColor: 'var(--color-bg-surface)' }}
        >
          <p className="text-lg font-bold text-content">{value}</p>
          <p className="text-xs text-content-muted mt-0.5">{label}</p>
        </div>
      ))}
    </div>
  )
}
