import { useEffect, useRef } from 'react';
import { createChart, CandlestickSeries, type IChartApi, type CandlestickData, type Time } from 'lightweight-charts';

function getCssVar(name: string): string {
  return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}

interface Props {
  symbol: string;
  data?: CandlestickData<Time>[];
}

export function CandlestickChart({ symbol, data = [] }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const seriesRef = useRef<any>(null);

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

    const bgCard = getCssVar('--color-bg-card');
    const textSecondary = getCssVar('--color-text-secondary');
    const border = getCssVar('--color-border');
    const green = getCssVar('--color-green');
    const red = getCssVar('--color-red');

    const chart = createChart(containerRef.current, {
      layout: {
        background: { color: bgCard },
        textColor: textSecondary,
      },
      grid: {
        vertLines: { color: border },
        horzLines: { color: border },
      },
      crosshair: {
        mode: 0, // Normal
      },
      timeScale: {
        borderColor: border,
        timeVisible: true,
      },
      rightPriceScale: {
        borderColor: border,
      },
    });

    const series = chart.addSeries(CandlestickSeries, {
      upColor: green,
      downColor: red,
      borderUpColor: green,
      borderDownColor: red,
      wickUpColor: green,
      wickDownColor: red,
    });

    chartRef.current = chart;
    seriesRef.current = series;

    // Handle resize
    const observer = new ResizeObserver((entries) => {
      const { width, height } = entries[0].contentRect;
      chart.applyOptions({ width, height });
    });
    observer.observe(containerRef.current);

    return () => {
      observer.disconnect();
      chart.remove();
      chartRef.current = null;
      seriesRef.current = null;
    };
  }, []);

  // Update data
  useEffect(() => {
    if (seriesRef.current && data.length > 0) {
      seriesRef.current.setData(data);
    }
  }, [data]);

  return (
    <div className="flex flex-col h-full">
      <div className="flex items-center justify-between px-3 py-1.5 border-b border-[var(--color-border)]">
        <span className="text-sm font-medium">{symbol}</span>
        <span className="text-xs text-[var(--color-text-secondary)]">1m</span>
      </div>
      <div className="relative flex-1 min-h-0">
        <div ref={containerRef} className="absolute inset-0" />
        {data.length === 0 && (
          <div className="absolute inset-0 flex items-center justify-center bg-[var(--color-bg-card)]/80">
            <div className="text-center">
              <div className="flex gap-1 mb-2 justify-center">
                {Array.from({ length: 8 }, (_, i) => (
                  <div
                    key={i}
                    className="w-2 rounded-sm bg-[var(--color-border)] animate-pulse"
                    style={{ height: `${16 + i * 4}px`, animationDelay: `${i * 100}ms` }}
                  />
                ))}
              </div>
              <span className="text-xs text-[var(--color-text-secondary)]">Awaiting market data...</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
