import {
  ResponsiveContainer,
  ComposedChart,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
} from 'recharts'
import { rechartsTheme } from '../../utils/rechartsTheme'
import { ChartTooltip } from './ChartTooltip'

interface ThemedChartProps {
  data: Record<string, any>[]
  height?: number
  xDataKey?: string
  xType?: 'number' | 'category'
  xTickFormatter?: (value: any) => string
  yTickFormatter?: (value: any) => string
  yLabel?: string
  children: React.ReactNode
  className?: string
}

export function ThemedChart({
  data,
  height = 200,
  xDataKey = 'time',
  xType = 'category',
  xTickFormatter,
  yTickFormatter,
  yLabel,
  children,
  className,
}: ThemedChartProps) {
  if (!data.length) {
    return null
  }

  // Show ~5-6 ticks max to avoid label overlap
  const maxTicks = 6
  const tickInterval = data.length > maxTicks
    ? Math.ceil(data.length / maxTicks) - 1
    : 0

  return (
    <div className={className} style={{ width: '100%', height }}>
      <ResponsiveContainer width="100%" height="100%">
        <ComposedChart data={data} margin={{ top: 4, right: 8, bottom: 0, left: 0 }}>
          <CartesianGrid {...rechartsTheme.cartesianGrid} />
          <XAxis
            dataKey={xDataKey}
            type={xType}
            {...rechartsTheme.xAxis}
            tickFormatter={xTickFormatter}
            interval={tickInterval}
            minTickGap={40}
          />
          <YAxis
            {...rechartsTheme.yAxis}
            tickFormatter={yTickFormatter}
            label={yLabel ? {
              value: yLabel,
              angle: -90,
              position: 'insideLeft',
              style: { fontSize: 11, fill: 'var(--text-muted)' },
            } : undefined}
          />
          <Tooltip content={<ChartTooltip />} cursor={rechartsTheme.tooltip.cursor} />
          {children}
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  )
}
