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)',
}

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

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

  const rows = data.render_time_by_output_type
  const chartHeight = Math.max(160, rows.length * 44)

  return (
    <div className="space-y-4">
      <ResponsiveContainer width="100%" height={chartHeight}>
        <BarChart data={rows} layout="vertical" margin={{ top: 4, right: 40, left: 8, bottom: 4 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" horizontal={false} />
          <XAxis
            type="number"
            tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }}
            tickFormatter={(v: number) => v >= 60 ? `${(v / 60).toFixed(0)}m` : `${v.toFixed(0)}s`}
          />
          <YAxis type="category" dataKey="output_type" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} width={130} />
          <Tooltip
            contentStyle={TOOLTIP_STYLE}
            formatter={(v: unknown, name?: string) => {
              const n = typeof v === 'number' ? v : null
              return [n != null ? (n >= 60 ? `${(n / 60).toFixed(1)} min` : `${n.toFixed(0)} s`) : '—', name ?? '']
            }}
          />
          <Legend wrapperStyle={{ fontSize: 11 }} />
          <Bar dataKey="avg_render_s" name="Ø Renderzeit" fill="#6366f1" radius={[0, 3, 3, 0]} />
          <Bar dataKey="p50_render_s" name="Median (P50)" fill="#14b8a6" radius={[0, 3, 3, 0]} />
        </BarChart>
      </ResponsiveContainer>

      <div className="overflow-x-auto">
        <table className="w-full text-xs">
          <thead>
            <tr className="border-b border-border-default text-left text-content-muted">
              <th className="pb-2 pr-3 font-medium">Output-Typ</th>
              <th className="pb-2 px-2 font-medium text-right">Jobs</th>
              <th className="pb-2 px-2 font-medium text-right">Ø</th>
              <th className="pb-2 px-2 font-medium text-right">P50</th>
              <th className="pb-2 px-2 font-medium text-right">Min</th>
              <th className="pb-2 pl-2 font-medium text-right">Max</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border-light">
            {rows.map((r) => (
              <tr key={r.output_type} className="hover:bg-surface-hover">
                <td className="py-1.5 pr-3 font-medium text-content-secondary max-w-[160px] truncate" title={r.output_type}>{r.output_type}</td>
                <td className="py-1.5 px-2 text-right text-content-muted">{r.job_count}</td>
                <td className="py-1.5 px-2 text-right tabular-nums">{fmtSeconds(r.avg_render_s)}</td>
                <td className="py-1.5 px-2 text-right tabular-nums text-content-muted">{fmtSeconds(r.p50_render_s)}</td>
                <td className="py-1.5 px-2 text-right tabular-nums text-content-muted">{fmtSeconds(r.min_render_s)}</td>
                <td className="py-1.5 pl-2 text-right tabular-nums text-content-muted">{fmtSeconds(r.max_render_s)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
