import { useEffect, useRef } from 'react';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
} from 'echarts/components';
import type { EChartsType } from 'echarts/core';
import { buildEChartsTheme } from './buildEChartsTheme';
import { useThemeEpoch } from './useThemeEpoch';

echarts.use([LineChart, CanvasRenderer, GridComponent, TooltipComponent, LegendComponent, DataZoomComponent]);

interface PerfSeries {
  name: string;
  data: number[];
  color: string;
}

interface PerfChartProps {
  series: PerfSeries[];
  timestamps: string[];
  height?: number;
}

export function PerfChart({ series, timestamps, height = 200 }: PerfChartProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<EChartsType | null>(null);
  const themeEpoch = useThemeEpoch();

  useEffect(() => {
    if (!containerRef.current) return;

    if (!chartRef.current) {
      const theme = buildEChartsTheme();
      chartRef.current = echarts.init(containerRef.current, theme);
    }

    const chart = chartRef.current;
    const root = getComputedStyle(document.documentElement);
    const get = (prop: string) => root.getPropertyValue(prop).trim();

    chart.setOption({
      backgroundColor: 'transparent',
      textStyle: { color: get('--foreground') },
      tooltip: {
        trigger: 'axis',
        backgroundColor: get('--muted'),
        borderColor: get('--border'),
        textStyle: { color: get('--foreground') },
      },
      legend: {
        top: 0,
        textStyle: { color: get('--foreground'), fontSize: 11 },
      },
      grid: {
        left: 48,
        right: 16,
        top: 36,
        bottom: 24,
      },
      xAxis: {
        type: 'category',
        data: timestamps,
        axisLine: { lineStyle: { color: get('--border') } },
        axisLabel: { color: get('--muted-foreground'), fontSize: 10 },
        axisTick: { show: false },
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        splitLine: { lineStyle: { color: get('--border'), type: 'dashed' } },
        axisLabel: { color: get('--muted-foreground'), fontSize: 10 },
      },
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: 0,
          start: 80,
          end: 100,
        },
      ],
      series: series.map((s) => ({
        name: s.name,
        type: 'line',
        data: s.data,
        smooth: true,
        lineStyle: { width: 1.5, color: s.color },
        symbol: 'none',
        sampling: 'lttb',
      })),
    });

    const observer = new ResizeObserver(() => {
      chartRef.current?.resize();
    });
    observer.observe(containerRef.current);

    return () => {
      observer.disconnect();
      chart.dispose();
      chartRef.current = null;
    };
  }, [series, timestamps, themeEpoch]);

  return (
    <div ref={containerRef} className="w-full" style={{ height }} />
  );
}
