import { useQuery } from '@tanstack/react-query'
import { PackageCheck, Clock, CheckCircle2 } from 'lucide-react'
import { getDashboardKPIs } from '../../../api/analytics'
import { useDashboardTimeframe } from '../DashboardTimeframeContext'

function Skeleton() {
  return (
    <div className="animate-pulse space-y-3">
      {[0, 1, 2].map((i) => (
        <div key={i} className="h-10 rounded-lg bg-surface-muted" />
      ))}
    </div>
  )
}

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

  if (isLoading) return <Skeleton />
  if (error) {
    return (
      <p className="text-xs text-red-500">Failed to load production stats</p>
    )
  }

  const s = data?.summary
  const stats = [
    { label: 'Open Orders', value: (s?.total_orders ?? 0) - (s?.completed_orders ?? 0), icon: <Clock size={16} className="text-amber-500" /> },
    { label: 'Completed Orders', value: s?.completed_orders ?? 0, icon: <CheckCircle2 size={16} className="text-green-500" /> },
    { label: 'Rendering Items', value: s?.total_rendering_items ?? 0, icon: <PackageCheck size={16} className="text-blue-500" /> },
  ]

  return (
    <div className="space-y-2">
      {stats.map(({ label, value, icon }) => (
        <div
          key={label}
          className="flex items-center justify-between rounded-lg border border-border-default p-3"
          style={{ backgroundColor: 'var(--color-bg-surface)' }}
        >
          <div className="flex items-center gap-2">
            {icon}
            <span className="text-sm text-content-secondary">{label}</span>
          </div>
          <span className="text-lg font-bold text-content">{value}</span>
        </div>
      ))}
    </div>
  )
}
