import {
  LineChart as RechartsLineChart, Line, XAxis, YAxis, CartesianGrid,
  Tooltip, Legend, Brush, ReferenceLine,
} from 'recharts'
import { ChartContainer, ChartTooltipContent, type Series, getSeriesColor } from './chart_container'

type CurveType = 'linear' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter'

interface LineChartProps {
  data: Record<string, unknown>[]
  xKey: string
  yKey?: string
  series?: Series[]
  curveType?: CurveType
  showGrid?: boolean
  showLegend?: boolean
  showDots?: boolean
  zoomable?: boolean
  height?: number | string
  className?: string
  xAxisFormatter?: (value: unknown) => string
  yAxisFormatter?: (value: unknown) => string
  valueFormatter?: (value: number) => string
  referenceLines?: Array<{ y: number; label?: string; color?: string }>
}

function LineChartComponent({
  data, xKey, yKey, series, curveType = 'monotone', showGrid = true, showLegend = false,
  showDots = true, zoomable = false, height = 300, className, xAxisFormatter, yAxisFormatter,
  valueFormatter = (v) => v.toLocaleString(), referenceLines = [],
}: LineChartProps) {
  const lines = series
    ? series.map((s, i) => ({ dataKey: s.key, name: s.name, stroke: getSeriesColor(i, s.color) }))
    : yKey ? [{ dataKey: yKey, name: yKey, stroke: getSeriesColor(0) }] : []

  return (
    <ChartContainer className={className} height={height}>
      <RechartsLineChart data={data} margin={{ top: 10, right: 10, left: 10, bottom: zoomable ? 30 : 10 }}>
        {showGrid && <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />}
        <XAxis dataKey={xKey} tickFormatter={xAxisFormatter} className="text-xs fill-muted-foreground" />
        <YAxis tickFormatter={yAxisFormatter} className="text-xs fill-muted-foreground" />
        <Tooltip content={<ChartTooltipContent valueFormatter={valueFormatter} />} cursor={{ stroke: 'hsl(var(--muted-foreground))', strokeDasharray: '3 3' }} />
        {showLegend && <Legend />}
        {referenceLines.map((ref, i) => (
          <ReferenceLine key={i} y={ref.y} stroke={ref.color || 'hsl(var(--muted-foreground))'} strokeDasharray="3 3" label={ref.label ? { value: ref.label, position: 'right' } : undefined} />
        ))}
        {lines.map((line) => (
          <Line key={line.dataKey} type={curveType} dataKey={line.dataKey} name={line.name} stroke={line.stroke} strokeWidth={2} dot={showDots ? { r: 3, fill: line.stroke } : false} activeDot={{ r: 5, fill: line.stroke }} />
        ))}
        {zoomable && <Brush dataKey={xKey} height={20} stroke="hsl(var(--primary))" fill="hsl(var(--muted))" tickFormatter={xAxisFormatter} />}
      </RechartsLineChart>
    </ChartContainer>
  )
}

export const LineChart = LineChartComponent
export type { LineChartProps, CurveType }
