import { useQuery } from '@tanstack/react-query'
import {
  ResponsiveContainer, LineChart, Line,
  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 OrderThroughputWidget() {
  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 throughput</p>
  if (!data || data.throughput.length === 0) {
    return <p className="text-xs text-content-muted text-center py-8">No data yet</p>
  }

  return (
    <ResponsiveContainer width="100%" height={200}>
      <LineChart data={data.throughput} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
        <XAxis dataKey="week" 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 }} />
        <Line type="monotone" dataKey="count" name="Created" stroke="#00893d" strokeWidth={2} dot={false} />
        <Line type="monotone" dataKey="completed" name="Completed" stroke="#6366f1" strokeWidth={2} dot={false} />
      </LineChart>
    </ResponsiveContainer>
  )
}
