import { useEffect, useRef, useState } from 'react';
import { useTradingStore } from '../../../stores/tradingStore';
import { ChartToolbar } from '../components/ChartToolbar';
import CandlestickChart from '../components/CandlestickChart';
import WatchlistSidebar from '../components/WatchlistSidebar';
import PaperTradingPanel from '../components/PaperTradingPanel';
import MLSignalsPanel from '../components/MLSignalsPanel';
import type { Interval, CrosshairData } from '../../../types/trading.types';
import type { MLSignal } from '../../../services/mlService';

export default function Trading() {
  const chartRef = useRef<HTMLDivElement>(null);
  const [_crosshairData, setCrosshairData] = useState<CrosshairData | null>(null);
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);
  const [isMLSignalsOpen, setIsMLSignalsOpen] = useState(true);
  const [isPaperTradingOpen, setIsPaperTradingOpen] = useState(true);

  // Get state and actions from store
  const {
    selectedSymbol,
    timeframe,
    klines,
    currentTicker,
    loadingKlines,
    error,
    setSymbol,
    setTimeframe,
    fetchKlines,
    fetchTicker,
  } = useTradingStore();

  // Initial data fetch
  useEffect(() => {
    fetchKlines();
    fetchTicker();
  }, [fetchKlines, fetchTicker]);

  // Update chart data when klines change
  useEffect(() => {
    if (chartRef.current && klines.length > 0) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const updateData = (chartRef.current as any).updateData;
      if (updateData) {
        updateData(klines);
      }
    }
  }, [klines]);

  // Handle symbol change
  const handleSymbolChange = (symbol: string) => {
    setSymbol(symbol);
  };

  // Handle timeframe change
  const handleTimeframeChange = (interval: Interval) => {
    setTimeframe(interval);
  };

  // Handle indicator toggle
  const handleIndicatorToggle = (indicator: string) => {
    console.log('Toggle indicator:', indicator);
    // TODO: Implement indicator overlay logic
  };

  // Handle crosshair move
  const handleCrosshairMove = (data: CrosshairData | null) => {
    setCrosshairData(data);
  };

  // Handle ML signal trade
  const handleMLSignalTrade = (signal: MLSignal) => {
    // Navigate to paper trading with pre-filled order
    window.location.href = `/trading?symbol=${signal.symbol}&signal=${signal.signal_id}&direction=${signal.direction}&entry=${signal.entry_price}&sl=${signal.stop_loss}&tp=${signal.take_profit}`;
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Trading</h1>
        <p className="text-gray-400">Gráficos, predicciones ML y señales de trading</p>
      </div>

      {/* Main Trading Layout */}
      <div className="flex gap-6">
        {/* Watchlist Sidebar - Desktop */}
        <div className={`hidden lg:block transition-all duration-300 ${isSidebarOpen ? 'w-64' : 'w-0 overflow-hidden'}`}>
          {isSidebarOpen && (
            <div className="h-[600px] card p-0 overflow-hidden">
              <WatchlistSidebar
                selectedSymbol={selectedSymbol}
                onSymbolSelect={handleSymbolChange}
              />
            </div>
          )}
        </div>

        {/* Chart Section */}
        <div className="flex-1">
          <div className="card p-0 overflow-hidden" style={{ minHeight: '500px' }}>
            {/* Toolbar with sidebar toggle */}
            <div className="flex items-center gap-2 border-b border-gray-700 p-2">
              <button
                onClick={() => setIsSidebarOpen(!isSidebarOpen)}
                className="hidden lg:flex items-center justify-center w-8 h-8 text-gray-400 hover:text-white hover:bg-gray-800 rounded transition-colors"
                aria-label="Toggle watchlist"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d={isSidebarOpen ? "M11 19l-7-7 7-7m8 14l-7-7 7-7" : "M13 5l7 7-7 7M5 5l7 7-7 7"}
                  />
                </svg>
              </button>
              <div className="flex-1">
                <ChartToolbar
                  symbol={selectedSymbol}
                  interval={timeframe}
                  onSymbolChange={handleSymbolChange}
                  onIntervalChange={handleTimeframeChange}
                  onIndicatorToggle={handleIndicatorToggle}
                  theme="dark"
                />
              </div>
              <button
                onClick={() => setIsMLSignalsOpen(!isMLSignalsOpen)}
                className="hidden lg:flex items-center justify-center w-8 h-8 text-gray-400 hover:text-white hover:bg-gray-800 rounded transition-colors"
                aria-label="Toggle ML signals"
                title="Toggle ML Signals"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"
                  />
                </svg>
              </button>
              <button
                onClick={() => setIsPaperTradingOpen(!isPaperTradingOpen)}
                className="hidden lg:flex items-center justify-center w-8 h-8 text-gray-400 hover:text-white hover:bg-gray-800 rounded transition-colors"
                aria-label="Toggle paper trading"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d={isPaperTradingOpen ? "M13 5l7 7-7 7M5 5l7 7-7 7" : "M11 19l-7-7 7-7m8 14l-7-7 7-7"}
                  />
                </svg>
              </button>
            </div>

            {/* Chart */}
            <div className="relative">
              {loadingKlines && (
                <div className="absolute inset-0 flex items-center justify-center bg-gray-900/50 z-10">
                  <div className="flex items-center gap-2 text-white">
                    <svg
                      className="animate-spin h-6 w-6"
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      />
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      />
                    </svg>
                    <span>Loading chart...</span>
                  </div>
                </div>
              )}

              {error && !loadingKlines && (
                <div className="absolute inset-0 flex items-center justify-center bg-gray-900/50 z-10">
                  <div className="text-center text-white">
                    <p className="text-red-400 mb-2">{error}</p>
                    <button
                      onClick={() => fetchKlines()}
                      className="px-4 py-2 bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      Retry
                    </button>
                  </div>
                </div>
              )}

              <div ref={chartRef}>
                <CandlestickChart
                  symbol={selectedSymbol}
                  interval={timeframe}
                  height={500}
                  theme="dark"
                  showVolume={true}
                  onCrosshairMove={handleCrosshairMove}
                />
              </div>

              {/* Price Info Bar */}
              {currentTicker && (
                <div className="absolute top-4 left-4 bg-gray-900/80 backdrop-blur-sm rounded-lg px-4 py-2 border border-gray-700">
                  <div className="flex items-center gap-4 text-sm">
                    <div>
                      <span className="text-gray-400">Price:</span>
                      <span className="ml-2 text-white font-mono">
                        {currentTicker.price.toLocaleString(undefined, {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 8,
                        })}
                      </span>
                    </div>
                    <div>
                      <span className="text-gray-400">24h:</span>
                      <span
                        className={`ml-2 font-medium ${
                          currentTicker.changePercent >= 0 ? 'text-green-400' : 'text-red-400'
                        }`}
                      >
                        {currentTicker.changePercent >= 0 ? '+' : ''}
                        {currentTicker.changePercent.toFixed(2)}%
                      </span>
                    </div>
                    <div>
                      <span className="text-gray-400">Vol:</span>
                      <span className="ml-2 text-white font-mono">
                        {(currentTicker.volume24h / 1000000).toFixed(2)}M
                      </span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* ML Signals Panel - Desktop */}
        <div className={`hidden lg:block transition-all duration-300 ${isMLSignalsOpen ? 'w-80' : 'w-0 overflow-hidden'}`}>
          {isMLSignalsOpen && (
            <div className="h-[600px] overflow-y-auto">
              <MLSignalsPanel
                symbol={selectedSymbol}
                currentPrice={currentTicker?.price}
                onTradeSignal={handleMLSignalTrade}
              />
            </div>
          )}
        </div>

        {/* Paper Trading Panel - Desktop */}
        <div className={`hidden lg:block transition-all duration-300 ${isPaperTradingOpen ? 'w-80' : 'w-0 overflow-hidden'}`}>
          {isPaperTradingOpen && (
            <PaperTradingPanel />
          )}
        </div>
      </div>
    </div>
  );
}
