import { useQuery } from '@tanstack/react-query'
import {
  ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Legend, Tooltip,
  XAxis, YAxis, CartesianGrid,
} 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)',
}

const COLORS = ['#00893d', '#6366f1', '#f59e0b', '#3b82f6', '#8b5cf6', '#14b8a6', '#f43f5e', '#06b6d4']

export default function OutputTypeUsageWidget() {
  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 usage data</p>
  if (!data) return null

  const rendererPie = data.renderer_usage.map((r, i) => ({
    name: r.renderer || 'unknown',
    value: r.count,
    color: COLORS[i % COLORS.length],
  }))

  return (
    <div className="space-y-4">
      <div>
        <p className="text-xs font-medium text-content-secondary mb-2">Output Type Usage</p>
        {data.output_type_usage.length === 0 ? (
          <p className="text-xs text-content-muted text-center py-4">No data yet</p>
        ) : (
          <ResponsiveContainer width="100%" height={160}>
            <BarChart data={data.output_type_usage} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
              <XAxis dataKey="output_type" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
              <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} allowDecimals={false} />
              <Tooltip contentStyle={TOOLTIP_STYLE} />
              <Bar dataKey="count" fill="#6366f1" radius={[3, 3, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        )}
      </div>

      <div>
        <p className="text-xs font-medium text-content-secondary mb-2">Renderer Usage</p>
        {rendererPie.length === 0 ? (
          <p className="text-xs text-content-muted text-center py-4">No data yet</p>
        ) : (
          <ResponsiveContainer width="100%" height={160}>
            <PieChart>
              <Pie data={rendererPie} dataKey="value" nameKey="name" cx="50%" cy="45%" outerRadius={55}
                label={({ name, value }) => `${name}: ${value}`} labelLine={false}>
                {rendererPie.map((e) => <Cell key={e.name} fill={e.color} />)}
              </Pie>
              <Legend wrapperStyle={{ fontSize: 11 }} />
              <Tooltip contentStyle={TOOLTIP_STYLE} />
            </PieChart>
          </ResponsiveContainer>
        )}
      </div>
    </div>
  )
}
