import { useQuery } from '@tanstack/react-query'
import {
  ResponsiveContainer, BarChart, Bar,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend,
} from 'recharts'
import { getDashboardKPIs } from '../../../api/analytics'
import { useDashboardTimeframe } from '../DashboardTimeframeContext'

const TOOLTIP_STYLE = {
  backgroundColor: 'var(--color-bg-surface)',
  border: '1px solid var(--color-border)',
  borderRadius: '8px',
  color: 'var(--color-text)',
}

export default function RenderBackendStatsWidget() {
  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-3"><div className="h-40 animate-pulse rounded-lg bg-surface-muted" /><div className="h-40 animate-pulse rounded-lg bg-surface-muted" /></div>
  if (error) return <p className="text-xs text-red-500">Failed to load backend stats</p>
  if (!data || data.render_backend_stats.length === 0) {
    return <p className="text-xs text-content-muted text-center py-8">No data yet</p>
  }

  return (
    <div className="space-y-4">
      <div>
        <p className="text-xs font-medium text-content-secondary mb-2">Job Count by Backend</p>
        <ResponsiveContainer width="100%" height={160}>
          <BarChart data={data.render_backend_stats} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
            <XAxis dataKey="backend" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
            <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} allowDecimals={false} />
            <Tooltip contentStyle={TOOLTIP_STYLE} />
            <Legend wrapperStyle={{ fontSize: 11 }} />
            <Bar dataKey="completed" name="Completed" fill="#22c55e" radius={[3, 3, 0, 0]} />
            <Bar dataKey="failed" name="Failed" fill="#ef4444" radius={[3, 3, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>

      <div>
        <p className="text-xs font-medium text-content-secondary mb-2">Avg Render Time (s)</p>
        <ResponsiveContainer width="100%" height={160}>
          <BarChart data={data.render_backend_stats} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
            <XAxis dataKey="backend" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
            <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
            <Tooltip
              contentStyle={TOOLTIP_STYLE}
              formatter={(v: number | undefined) => v != null ? [`${v.toFixed(1)} s`, ''] : ['—', '']}
            />
            <Legend wrapperStyle={{ fontSize: 11 }} />
            <Bar dataKey="avg_render_s" name="Avg" fill="#6366f1" radius={[3, 3, 0, 0]} />
            <Bar dataKey="p50_render_s" name="Median (P50)" fill="#14b8a6" radius={[3, 3, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  )
}
