"use client";

import { useEffect, useRef, useState, useMemo } from "react";
import {
  createChart,
  CandlestickSeries,
  HistogramSeries,
  type IChartApi,
  type ISeriesApi,
  type CandlestickData,
  type Time,
  ColorType,
} from "lightweight-charts";
import type { Kline } from "@/types/models";
import { cn } from "@/lib/utils";

type TimeInterval = "1m" | "5m" | "15m" | "1h" | "4h" | "1d";

interface CandlestickChartProps {
  data: Kline[];
  symbol: string;
  height?: number;
  onIntervalChange?: (interval: TimeInterval) => void;
}

const intervalConfig: Record<
  TimeInterval,
  { label: string; value: TimeInterval }
> = {
  "1m": { label: "1M", value: "1m" },
  "5m": { label: "5M", value: "5m" },
  "15m": { label: "15M", value: "15m" },
  "1h": { label: "1H", value: "1h" },
  "4h": { label: "4H", value: "4h" },
  "1d": { label: "1D", value: "1d" },
};

const THEME = {
  background: "#1e1e1e",
  grid: "#2c2c2c",
  text: "#a0a0a0",
  up: "#00ffcc",
  down: "#ff5252",
  crosshair: "#00ffcc",
  border: "#2c2c2c",
};

export function CandlestickChart({
  data,
  symbol,
  height = 400,
  onIntervalChange,
}: CandlestickChartProps) {
  const chartContainerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  const candlestickSeriesRef = useRef<ISeriesApi<"Candlestick"> | null>(null);
  const volumeSeriesRef = useRef<ISeriesApi<"Histogram"> | null>(null);
  const [selectedInterval, setSelectedInterval] = useState<TimeInterval>("1h");

  const stats = useMemo(() => {
    if (data.length === 0) {
      return {
        currentPrice: 0,
        priceChange: 0,
        priceChangePercent: 0,
        high24h: 0,
        low24h: 0,
        volume24h: 0,
      };
    }

    const latest = data[data.length - 1];
    const first = data[0];
    const prices = data.flatMap((d) => [d.high, d.low]);

    return {
      currentPrice: latest.close,
      priceChange: latest.close - first.open,
      priceChangePercent: ((latest.close - first.open) / first.open) * 100,
      high24h: Math.max(...prices),
      low24h: Math.min(...prices),
      volume24h: data.reduce((sum, d) => sum + d.volume, 0),
    };
  }, [data]);

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

    const chart = createChart(chartContainerRef.current, {
      layout: {
        background: { type: ColorType.Solid, color: THEME.background },
        textColor: THEME.text,
        fontFamily: "Inter, sans-serif",
      },
      grid: {
        vertLines: { color: THEME.grid, style: 1 },
        horzLines: { color: THEME.grid, style: 1 },
      },
      crosshair: {
        mode: 1,
        vertLine: {
          color: THEME.crosshair,
          width: 1,
          style: 2,
          labelBackgroundColor: THEME.crosshair,
        },
        horzLine: {
          color: THEME.crosshair,
          width: 1,
          style: 2,
          labelBackgroundColor: THEME.crosshair,
        },
      },
      rightPriceScale: {
        borderColor: THEME.border,
        scaleMargins: { top: 0.1, bottom: 0.2 },
      },
      timeScale: {
        borderColor: THEME.border,
        timeVisible: true,
        secondsVisible: false,
      },
      height,
    });

    chartRef.current = chart;

    const candlestickSeries = chart.addSeries(CandlestickSeries, {
      upColor: THEME.up,
      downColor: THEME.down,
      borderUpColor: THEME.up,
      borderDownColor: THEME.down,
      wickUpColor: THEME.up,
      wickDownColor: THEME.down,
    });

    candlestickSeriesRef.current = candlestickSeries;

    const volumeSeries = chart.addSeries(HistogramSeries, {
      priceFormat: { type: "volume" },
      priceScaleId: "",
    });

    volumeSeries.priceScale().applyOptions({
      scaleMargins: { top: 0.85, bottom: 0 },
    });

    volumeSeriesRef.current = volumeSeries;

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

    window.addEventListener("resize", handleResize);
    handleResize();

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

  useEffect(() => {
    if (!candlestickSeriesRef.current || !volumeSeriesRef.current || data.length === 0) return;

    const candleData: CandlestickData[] = data.map((k) => ({
      time: (new Date(k.timestamp).getTime() / 1000) as Time,
      open: k.open,
      high: Math.max(k.high, k.open, k.close),
      low: Math.min(k.low, k.open, k.close),
      close: k.close,
    }));

    const volumeData = data.map((k) => ({
      time: (new Date(k.timestamp).getTime() / 1000) as Time,
      value: k.volume,
      color: k.close >= k.open ? THEME.up : THEME.down,
    }));

    candlestickSeriesRef.current.setData(candleData);
    volumeSeriesRef.current.setData(volumeData);
    chartRef.current?.timeScale().fitContent();
  }, [data]);

  const formatPrice = (value: number) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: 2,
    }).format(value);
  };

  return (
    <div className="bg-[#1e1e1e] p-6 rounded-2xl border border-[#2c2c2c] shadow-2xl h-full">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
        <div>
          <h3 className="text-sm font-black text-[#e1e1e1] uppercase tracking-widest flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-[#00ffcc] animate-pulse" />
            {symbol} LIVE CHART
          </h3>
          <div className="flex items-baseline gap-3 mt-2">
            <span className="text-3xl font-black text-[#e1e1e1] tracking-tighter">
              {formatPrice(stats.currentPrice)}
            </span>
            <span className={cn("text-xs font-black uppercase italic tracking-widest", stats.priceChange >= 0 ? "text-[#00ffcc]" : "text-[#ff5252]")}>
              {stats.priceChange >= 0 ? "↑" : "↓"} {Math.abs(stats.priceChangePercent).toFixed(2)}%
            </span>
          </div>
        </div>

        <div className="flex gap-1 bg-[#121212] p-1 rounded-xl border border-[#2c2c2c]">
          {(Object.keys(intervalConfig) as TimeInterval[]).map((interval) => (
            <button
              key={interval}
              onClick={() => { setSelectedInterval(interval); onIntervalChange?.(interval); }}
              className={cn(
                "px-3 py-1.5 rounded-lg text-[10px] font-black uppercase tracking-widest transition-all",
                selectedInterval === interval 
                  ? "bg-[#00ffcc] text-[#121212] shadow-lg" 
                  : "text-[#666666] hover:text-[#e1e1e1] hover:bg-[#1e1e1e]"
              )}
            >
              {intervalConfig[interval].label}
            </button>
          ))}
        </div>
      </div>

      <div className="grid grid-cols-3 gap-4 mb-6 bg-[#121212] p-4 rounded-xl border border-[#2c2c2c]">
        {[
          { label: "24H HIGH", value: formatPrice(stats.high24h), color: "text-[#00ffcc]" },
          { label: "24H LOW", value: formatPrice(stats.low24h), color: "text-[#ff5252]" },
          { label: "24H VOLUME", value: stats.volume24h.toFixed(2), color: "text-[#e1e1e1]" },
        ].map((s, i) => (
          <div key={i} className="text-center">
            <p className="text-[9px] font-black text-[#666666] uppercase tracking-widest mb-1">{s.label}</p>
            <p className={cn("text-xs font-black tracking-tight", s.color)}>{s.value}</p>
          </div>
        ))}
      </div>

      <div ref={chartContainerRef} className="w-full" style={{ height: `${height}px` }} />
    </div>
  );
}

export default CandlestickChart;
