/**
 * CandlestickChart Component
 * Lightweight Charts implementation for candlestick display
 */

import { useEffect, useRef, useCallback } from 'react';
import {
  createChart,
  IChartApi,
  ISeriesApi,
  CandlestickData,
  HistogramData,
  Time,
  ColorType,
  CrosshairMode,
  LineStyle,
} from 'lightweight-charts';
import type { Candle, CandlestickChartProps } from '../../../types/trading.types';

// ============================================================================
// Theme Configuration
// ============================================================================

interface ChartTheme {
  backgroundColor: string;
  textColor: string;
  gridColor: string;
  upColor: string;
  downColor: string;
  borderUpColor: string;
  borderDownColor: string;
  wickUpColor: string;
  wickDownColor: string;
  volumeUpColor: string;
  volumeDownColor: string;
}

const THEMES: Record<'dark' | 'light', ChartTheme> = {
  dark: {
    backgroundColor: '#1a1a2e',
    textColor: '#d1d4dc',
    gridColor: '#2B2B43',
    upColor: '#10b981',
    downColor: '#ef4444',
    borderUpColor: '#10b981',
    borderDownColor: '#ef4444',
    wickUpColor: '#10b981',
    wickDownColor: '#ef4444',
    volumeUpColor: 'rgba(16, 185, 129, 0.5)',
    volumeDownColor: 'rgba(239, 68, 68, 0.5)',
  },
  light: {
    backgroundColor: '#ffffff',
    textColor: '#131722',
    gridColor: '#e1e1e1',
    upColor: '#10b981',
    downColor: '#ef4444',
    borderUpColor: '#10b981',
    borderDownColor: '#ef4444',
    wickUpColor: '#10b981',
    wickDownColor: '#ef4444',
    volumeUpColor: 'rgba(16, 185, 129, 0.5)',
    volumeDownColor: 'rgba(239, 68, 68, 0.5)',
  },
};

// ============================================================================
// Component
// ============================================================================

export const CandlestickChart: React.FC<CandlestickChartProps> = ({
  symbol,
  interval = '1h',
  height = 500,
  theme = 'dark',
  showVolume = true,
  onCrosshairMove,
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  const candleSeriesRef = useRef<ISeriesApi<'Candlestick'> | null>(null);
  const volumeSeriesRef = useRef<ISeriesApi<'Histogram'> | null>(null);
  const resizeObserverRef = useRef<ResizeObserver | null>(null);

  const chartTheme = THEMES[theme];

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

    const chart = createChart(containerRef.current, {
      width: containerRef.current.clientWidth,
      height,
      layout: {
        background: { type: ColorType.Solid, color: chartTheme.backgroundColor },
        textColor: chartTheme.textColor,
      },
      grid: {
        vertLines: { color: chartTheme.gridColor },
        horzLines: { color: chartTheme.gridColor },
      },
      crosshair: {
        mode: CrosshairMode.Normal,
        vertLine: {
          width: 1,
          color: 'rgba(224, 227, 235, 0.4)',
          style: LineStyle.Solid,
          labelBackgroundColor: chartTheme.backgroundColor,
        },
        horzLine: {
          width: 1,
          color: 'rgba(224, 227, 235, 0.4)',
          style: LineStyle.Solid,
          labelBackgroundColor: chartTheme.backgroundColor,
        },
      },
      rightPriceScale: {
        borderColor: chartTheme.gridColor,
      },
      timeScale: {
        borderColor: chartTheme.gridColor,
        timeVisible: true,
        secondsVisible: false,
      },
    });

    // Add candlestick series
    const candleSeries = chart.addCandlestickSeries({
      upColor: chartTheme.upColor,
      downColor: chartTheme.downColor,
      borderUpColor: chartTheme.borderUpColor,
      borderDownColor: chartTheme.borderDownColor,
      wickUpColor: chartTheme.wickUpColor,
      wickDownColor: chartTheme.wickDownColor,
    });

    // Add volume series
    let volumeSeries: ISeriesApi<'Histogram'> | null = null;
    if (showVolume) {
      volumeSeries = chart.addHistogramSeries({
        color: chartTheme.volumeUpColor,
        priceFormat: {
          type: 'volume',
        },
        priceScaleId: '',
      });
      volumeSeries.priceScale().applyOptions({
        scaleMargins: {
          top: 0.8,
          bottom: 0,
        },
      });
    }

    // Handle crosshair movement
    chart.subscribeCrosshairMove((param) => {
      if (!param || !param.time || !param.seriesData) {
        onCrosshairMove?.(null);
        return;
      }

      const candleData = param.seriesData.get(candleSeries) as CandlestickData;
      if (candleData) {
        onCrosshairMove?.({
          time: param.time,
          price: candleData.close as number,
        });
      }
    });

    chartRef.current = chart;
    candleSeriesRef.current = candleSeries;
    volumeSeriesRef.current = volumeSeries;

    // Setup ResizeObserver for responsive behavior
    const resizeObserver = new ResizeObserver((entries) => {
      if (entries[0] && chartRef.current) {
        const { width } = entries[0].contentRect;
        chartRef.current.applyOptions({ width });
      }
    });

    resizeObserver.observe(containerRef.current);
    resizeObserverRef.current = resizeObserver;

    return () => {
      resizeObserver.disconnect();
      chart.remove();
    };
  }, [height, showVolume, chartTheme, onCrosshairMove]);

  // Update data method
  const updateData = useCallback(
    (candles: Candle[]) => {
      if (!candleSeriesRef.current || candles.length === 0) return;

      // Transform data for candlestick series
      const candleData: CandlestickData[] = candles.map((c) => ({
        time: (c.time / 1000) as Time,
        open: c.open,
        high: c.high,
        low: c.low,
        close: c.close,
      }));

      candleSeriesRef.current.setData(candleData);

      // Transform data for volume series
      if (volumeSeriesRef.current && showVolume) {
        const volumeData: HistogramData[] = candles.map((c) => ({
          time: (c.time / 1000) as Time,
          value: c.volume,
          color: c.close >= c.open ? chartTheme.volumeUpColor : chartTheme.volumeDownColor,
        }));
        volumeSeriesRef.current.setData(volumeData);
      }

      // Fit content
      chartRef.current?.timeScale().fitContent();
    },
    [showVolume, chartTheme]
  );

  // Expose updateData method through ref
  useEffect(() => {
    if (containerRef.current) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (containerRef.current as any).updateData = updateData;
    }
  }, [updateData]);

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

export default CandlestickChart;
