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

function fmtSeconds(s: number | null | undefined): string {
  if (s == null) return '—'
  if (s >= 60) return `${(s / 60).toFixed(1)} min`
  return `${s.toFixed(1)} s`
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <tr>
      <td className="py-1.5 pr-3 text-content-secondary text-xs">{label}</td>
      <td className="py-1.5 font-medium text-content text-right text-xs tabular-nums">{value}</td>
    </tr>
  )
}

export default function ProcessingTimesWidget() {
  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="space-y-2"><div className="h-24 animate-pulse rounded-lg bg-surface-muted" /><div className="h-16 animate-pulse rounded-lg bg-surface-muted" /></div>
  if (error) return <p className="text-xs text-red-500">Failed to load timing data</p>
  if (!data) return null

  const { processing_times: pt, render_times: rt } = data

  return (
    <div className="space-y-4">
      <div>
        <p className="text-xs font-semibold text-content-secondary mb-2">Processing Times</p>
        <table className="w-full">
          <tbody className="divide-y divide-border-light">
            <Row label="Avg submit → complete" value={fmtSeconds(pt.avg_submit_to_complete_s)} />
            <Row label="Avg submit → processing" value={fmtSeconds(pt.avg_submit_to_processing_s)} />
            <Row label="P50 (median)" value={fmtSeconds(pt.p50_s)} />
            <Row label="P95" value={fmtSeconds(pt.p95_s)} />
          </tbody>
        </table>
      </div>

      <div>
        <p className="text-xs font-semibold text-content-secondary mb-2">Render Time Summary</p>
        <table className="w-full">
          <tbody className="divide-y divide-border-light">
            <Row label="Avg render time" value={fmtSeconds(rt.avg_render_s)} />
            <Row label="Completed renders" value={String(rt.sample_count)} />
          </tbody>
        </table>
      </div>
    </div>
  )
}
