import { useEffect, useRef, useState } from 'react';
import { useTradingStore } from '../../../stores/tradingStore';
import { ChartToolbar } from '../components/ChartToolbar';
import CandlestickChartWithML from '../components/CandlestickChartWithML';
import WatchlistSidebar from '../components/WatchlistSidebar';
import PaperTradingPanel from '../components/PaperTradingPanel';
import MLSignalsPanel from '../components/MLSignalsPanel';
import AlertsPanel from '../components/AlertsPanel';
import TradingStatsPanel from '../components/TradingStatsPanel';
import OrderBookPanel from '../components/OrderBookPanel';
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);
  const [isAlertsOpen, setIsAlertsOpen] = useState(false);
  const [isStatsOpen, setIsStatsOpen] = useState(false);
  const [isOrderBookOpen, setIsOrderBookOpen] = useState(false);

  // Active indicators state
  const [activeIndicators, setActiveIndicators] = useState<Set<string>>(new Set());

  // ML Overlay states
  const [enableMLOverlays, setEnableMLOverlays] = useState(true);
  const [showSignalLevels, setShowSignalLevels] = useState(true);
  const [showRangePrediction, setShowRangePrediction] = useState(true);
  const [showOrderBlocks, setShowOrderBlocks] = useState(false);
  const [showFairValueGaps, setShowFairValueGaps] = useState(false);
  const [showAMDPhase, setShowAMDPhase] = 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) => {
    setActiveIndicators((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(indicator)) {
        newSet.delete(indicator);
      } else {
        newSet.add(indicator);
      }
      return newSet;
    });
  };

  // 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}`;
  };

  // ML overlay control dropdown state
  const [showMLControls, setShowMLControls] = useState(false);

  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>
              {/* ML Overlays Control Button */}
              <div className="relative">
                <button
                  onClick={() => setShowMLControls(!showMLControls)}
                  className={`flex items-center gap-1 px-2 py-1.5 text-sm rounded transition-colors ${
                    enableMLOverlays
                      ? 'bg-purple-600/20 text-purple-400 border border-purple-600/50'
                      : 'text-gray-400 hover:text-white hover:bg-gray-800'
                  }`}
                  title="ML Overlays"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                  </svg>
                  <span className="hidden xl:inline">ML</span>
                  <svg className={`w-3 h-3 transition-transform ${showMLControls ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </button>

                {/* ML Controls Dropdown */}
                {showMLControls && (
                  <div className="absolute top-full right-0 mt-2 w-56 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-50 py-2">
                    <div className="px-3 py-2 border-b border-gray-700">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={enableMLOverlays}
                          onChange={(e) => setEnableMLOverlays(e.target.checked)}
                          className="w-4 h-4 rounded bg-gray-700 border-gray-600 text-purple-500 focus:ring-purple-500"
                        />
                        <span className="text-white font-medium">Enable ML Overlays</span>
                      </label>
                    </div>
                    <div className="px-3 py-2 space-y-2">
                      <label className={`flex items-center gap-2 cursor-pointer ${!enableMLOverlays ? 'opacity-50' : ''}`}>
                        <input
                          type="checkbox"
                          checked={showSignalLevels}
                          onChange={(e) => setShowSignalLevels(e.target.checked)}
                          disabled={!enableMLOverlays}
                          className="w-4 h-4 rounded bg-gray-700 border-gray-600 text-green-500 focus:ring-green-500"
                        />
                        <span className="text-gray-300 text-sm">Signal Levels (Entry/SL/TP)</span>
                      </label>
                      <label className={`flex items-center gap-2 cursor-pointer ${!enableMLOverlays ? 'opacity-50' : ''}`}>
                        <input
                          type="checkbox"
                          checked={showRangePrediction}
                          onChange={(e) => setShowRangePrediction(e.target.checked)}
                          disabled={!enableMLOverlays}
                          className="w-4 h-4 rounded bg-gray-700 border-gray-600 text-blue-500 focus:ring-blue-500"
                        />
                        <span className="text-gray-300 text-sm">Range Prediction</span>
                      </label>
                      <label className={`flex items-center gap-2 cursor-pointer ${!enableMLOverlays ? 'opacity-50' : ''}`}>
                        <input
                          type="checkbox"
                          checked={showAMDPhase}
                          onChange={(e) => setShowAMDPhase(e.target.checked)}
                          disabled={!enableMLOverlays}
                          className="w-4 h-4 rounded bg-gray-700 border-gray-600 text-amber-500 focus:ring-amber-500"
                        />
                        <span className="text-gray-300 text-sm">AMD Phase Indicator</span>
                      </label>
                      <label className={`flex items-center gap-2 cursor-pointer ${!enableMLOverlays ? 'opacity-50' : ''}`}>
                        <input
                          type="checkbox"
                          checked={showOrderBlocks}
                          onChange={(e) => setShowOrderBlocks(e.target.checked)}
                          disabled={!enableMLOverlays}
                          className="w-4 h-4 rounded bg-gray-700 border-gray-600 text-cyan-500 focus:ring-cyan-500"
                        />
                        <span className="text-gray-300 text-sm">Order Blocks</span>
                      </label>
                      <label className={`flex items-center gap-2 cursor-pointer ${!enableMLOverlays ? 'opacity-50' : ''}`}>
                        <input
                          type="checkbox"
                          checked={showFairValueGaps}
                          onChange={(e) => setShowFairValueGaps(e.target.checked)}
                          disabled={!enableMLOverlays}
                          className="w-4 h-4 rounded bg-gray-700 border-gray-600 text-pink-500 focus:ring-pink-500"
                        />
                        <span className="text-gray-300 text-sm">Fair Value Gaps (FVG)</span>
                      </label>
                    </div>
                  </div>
                )}
              </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={() => setIsAlertsOpen(!isAlertsOpen)}
                className={`hidden lg:flex items-center justify-center w-8 h-8 rounded transition-colors ${
                  isAlertsOpen
                    ? 'text-yellow-400 bg-yellow-900/30'
                    : 'text-gray-400 hover:text-white hover:bg-gray-800'
                }`}
                aria-label="Toggle alerts"
                title="Toggle Price Alerts"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
                  />
                </svg>
              </button>
              <button
                onClick={() => setIsStatsOpen(!isStatsOpen)}
                className={`hidden lg:flex items-center justify-center w-8 h-8 rounded transition-colors ${
                  isStatsOpen
                    ? 'text-blue-400 bg-blue-900/30'
                    : 'text-gray-400 hover:text-white hover:bg-gray-800'
                }`}
                aria-label="Toggle stats"
                title="Trading Statistics"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
                  />
                </svg>
              </button>
              <button
                onClick={() => setIsOrderBookOpen(!isOrderBookOpen)}
                className={`hidden lg:flex items-center justify-center w-8 h-8 rounded transition-colors ${
                  isOrderBookOpen
                    ? 'text-purple-400 bg-purple-900/30'
                    : 'text-gray-400 hover:text-white hover:bg-gray-800'
                }`}
                aria-label="Toggle order book"
                title="Order Book"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M4 6h16M4 10h16M4 14h16M4 18h16"
                  />
                </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}>
                <CandlestickChartWithML
                  symbol={selectedSymbol}
                  interval={timeframe}
                  height={500}
                  theme="dark"
                  showVolume={true}
                  onCrosshairMove={handleCrosshairMove}
                  enableMLOverlays={enableMLOverlays}
                  showSignalLevels={showSignalLevels}
                  showRangePrediction={showRangePrediction}
                  showOrderBlocks={showOrderBlocks}
                  showFairValueGaps={showFairValueGaps}
                  showAMDPhase={showAMDPhase}
                  autoRefreshML={true}
                  refreshInterval={30000}
                />
              </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>

        {/* Price Alerts Panel - Desktop */}
        <div className={`hidden lg:block transition-all duration-300 ${isAlertsOpen ? 'w-80' : 'w-0 overflow-hidden'}`}>
          {isAlertsOpen && (
            <div className="h-[600px]">
              <AlertsPanel
                symbol={selectedSymbol}
                currentPrice={currentTicker?.price}
              />
            </div>
          )}
        </div>

        {/* Trading Stats Panel - Desktop */}
        <div className={`hidden lg:block transition-all duration-300 ${isStatsOpen ? 'w-80' : 'w-0 overflow-hidden'}`}>
          {isStatsOpen && (
            <div className="h-[600px]">
              <TradingStatsPanel />
            </div>
          )}
        </div>

        {/* Order Book Panel - Desktop */}
        <div className={`hidden lg:block transition-all duration-300 ${isOrderBookOpen ? 'w-64' : 'w-0 overflow-hidden'}`}>
          {isOrderBookOpen && (
            <div className="h-[600px]">
              <OrderBookPanel symbol={selectedSymbol} />
            </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>
  );
}
