import { useEffect, useRef } from "react";
import * as LightweightCharts from "lightweight-charts";

interface TradingViewChartProps {
  ticker: string;
  data?: Array<{ time: string; open: number; high: number; low: number; close: number }>;
}

export default function TradingViewChart({ ticker, data }: TradingViewChartProps) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!containerRef.current) {
      console.warn(`TradingViewChart: container not ready for ${ticker}`);
      return;
    }

    console.log(`TradingViewChart: creating chart for ${ticker} with ${data?.length ?? 0} bars`);
    
    const chart = LightweightCharts.createChart(containerRef.current, {
      height: 400,
      autoSize: true,
    });

    const candlestickSeries = chart.addSeries(LightweightCharts.CandlestickSeries, {
      upColor: "#26a69a",
      downColor: "#ef5350",
      borderUpColor: "#26a69a",
      borderDownColor: "#ef5350",
      wickUpColor: "#26a69a",
      wickDownColor: "#ef5350",
    });
    
    if (data && data.length > 0) {
      console.log(`TradingViewChart: setting data for ${ticker}`, data.slice(0, 3));
      try {
        candlestickSeries.setData(data);
        console.log(`TradingViewChart: data set successfully for ${ticker}`);
      } catch (err) {
        console.error(`TradingViewChart: error setting data for ${ticker}`, err);
      }
    } else {
      console.log(`TradingViewChart: no data to set for ${ticker}`);
    }

    return () => chart.remove();
  }, [data, ticker]);

  return (
    <div className="bg-white rounded-xl shadow-lg p-4">
      <h3 className="text-lg font-bold mb-3">{ticker} Price Chart</h3>
      <div ref={containerRef} className="w-full" />
    </div>
  );
}