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

type ChartTime = string | number;

interface ChartDataPoint {
  time: ChartTime;
  open: number;
  high: number;
  low: number;
  close: number;
}

interface TradingViewChartProps {
  ticker: string;
  data?: ChartDataPoint[];
}

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

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

    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) {
      try {
        candlestickSeries.setData(data as any);
      } catch (err) {
        console.error(`TradingViewChart: error setting data for ${ticker}`, err);
      }
    }

    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>
  );
}