import { useEffect, useRef, useState } from 'react';
import { createChart, IChartApi, ISeriesApi, CandlestickData } from 'lightweight-charts';
import type { PriceData } from '@/types';

interface GoldChartProps {
  data: PriceData[];
  smaData?: { time: number; value: number }[];
  onCrosshairMove?: (price: number | null) => void;
  liveUpdate?: PriceData | null;
}

export default function GoldChart({ data, smaData, onCrosshairMove, liveUpdate }: GoldChartProps) {
  const chartContainerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  const candleSeriesRef = useRef<ISeriesApi<'Candlestick'> | null>(null);
  const smaSeriesRef = useRef<ISeriesApi<'Line'> | null>(null);
  const [currentPrice, setCurrentPrice] = useState<number | null>(null);

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

    // Create chart
    const chart = createChart(chartContainerRef.current, {
      layout: {
        background: { color: '#1a1f2e' },
        textColor: '#d1d4dc',
      },
      grid: {
        vertLines: { color: '#2a3142' },
        horzLines: { color: '#2a3142' },
      },
      width: chartContainerRef.current.clientWidth,
      height: 500,
      timeScale: {
        timeVisible: true,
        secondsVisible: false,
        borderColor: '#2a3142',
      },
      rightPriceScale: {
        borderColor: '#2a3142',
      },
      crosshair: {
        mode: 1,
        vertLine: {
          color: '#758696',
          width: 1,
          style: 3,
          labelBackgroundColor: '#4682B4',
        },
        horzLine: {
          color: '#758696',
          width: 1,
          style: 3,
          labelBackgroundColor: '#4682B4',
        },
      },
    });

    chartRef.current = chart;

    // Add candlestick series
    const candleSeries = chart.addCandlestickSeries({
      upColor: '#10b981',
      downColor: '#ef4444',
      borderUpColor: '#10b981',
      borderDownColor: '#ef4444',
      wickUpColor: '#10b981',
      wickDownColor: '#ef4444',
    });

    candleSeriesRef.current = candleSeries;

    // Add SMA series
    const smaSeries = chart.addLineSeries({
      color: '#FFD700',
      lineWidth: 2,
      title: 'SMA',
    });

    smaSeriesRef.current = smaSeries;

    // Handle resize
    const handleResize = () => {
      if (chartContainerRef.current && chartRef.current) {
        chartRef.current.applyOptions({
          width: chartContainerRef.current.clientWidth,
        });
      }
    };

    window.addEventListener('resize', handleResize);

    // Handle crosshair move
    chart.subscribeCrosshairMove((param) => {
      if (param.time) {
        const data = param.seriesData.get(candleSeries) as CandlestickData | undefined;
        if (data) {
          setCurrentPrice(data.close);
          onCrosshairMove?.(data.close);
        }
      } else {
        setCurrentPrice(null);
        onCrosshairMove?.(null);
      }
    });

    return () => {
      window.removeEventListener('resize', handleResize);
      chart.remove();
    };
  }, [onCrosshairMove]);

  // Update data
  useEffect(() => {
    if (candleSeriesRef.current && data.length > 0) {
      const formattedData = data.map((d) => ({
        time: d.time as any,
        open: d.open,
        high: d.high,
        low: d.low,
        close: d.close,
      }));
      candleSeriesRef.current.setData(formattedData);
      setCurrentPrice(data[data.length - 1].close);
    }
  }, [data]);

  // Update SMA
  useEffect(() => {
    if (smaSeriesRef.current && smaData && smaData.length > 0) {
      const formattedSMA = smaData.map((d) => ({
        time: d.time as any,
        value: d.value,
      }));
      smaSeriesRef.current.setData(formattedSMA);
    }
  }, [smaData]);

  // Handle live price updates
  useEffect(() => {
    if (!liveUpdate || !candleSeriesRef.current || data.length === 0) return;

    // Get the last candle timestamp from historical data
    const lastHistoricalTime = data[data.length - 1].time;
    
    // Only update if the new time is newer than or equal to the last historical time
    // This prevents the "Cannot update oldest data" error
    if (liveUpdate.time < lastHistoricalTime) {
      console.log('Skipping live update: timestamp is older than historical data');
      return;
    }

    const newCandle = {
      time: liveUpdate.time as any,
      open: liveUpdate.open,
      high: liveUpdate.high,
      low: liveUpdate.low,
      close: liveUpdate.close,
    };

    // Update the chart with the new candle
    candleSeriesRef.current.update(newCandle);
    setCurrentPrice(liveUpdate.close);

  }, [liveUpdate, data]);

  return (
    <div className="card">
      <div className="flex justify-between items-center mb-4">
        <div>
          <h2 className="text-xl font-bold text-gold-500">XAU/USD - Gold Trading</h2>
          {currentPrice && (
            <p className="text-sm text-gray-400">
              Current: ${currentPrice.toFixed(2)}
            </p>
          )}
        </div>
        <div className="flex gap-2">
          <span className="px-3 py-1 bg-dark-bg rounded-md text-sm">
            <span className="text-gold-500">●</span> SMA(50)
          </span>
        </div>
      </div>
      <div ref={chartContainerRef} className="w-full" />
    </div>
  );
}
