import { useState, useCallback, useEffect } from 'react';
import { Zap, TrendingUp, Layers } from 'lucide-react';

export type StrategyMode = 'SCALP' | 'SWING' | 'HYBRID';

export interface StrategyPreset {
  mode: StrategyMode;
  riskPerTrade: number;        // % of capital per trade
  stopLossPercent: number;     // % stop loss
  takeProfitPercent: number;   // % take profit
  timeFrame: string;           // '1m', '5m', '4h', 'daily'
  maxHoldMinutes: number;      // Max hold time
  maxDailyTrades: number;      // Max trades per day
  r2rRatio: number;            // Risk to Reward ratio
  description: string;
  emoji: string;
}

export const STRATEGY_PRESETS: Record<StrategyMode, StrategyPreset> = {
  SCALP: {
    mode: 'SCALP',
    riskPerTrade: 0.25,
    stopLossPercent: 0.5,
    takeProfitPercent: 1,
    timeFrame: '1m',
    maxHoldMinutes: 5,
    maxDailyTrades: 20,
    r2rRatio: 1,
    description: 'Quick profits from micro price moves. High frequency, tight stops.',
    emoji: '⚡',
  },
  SWING: {
    mode: 'SWING',
    riskPerTrade: 2,
    stopLossPercent: 2,
    takeProfitPercent: 8,
    timeFrame: 'daily',
    maxHoldMinutes: 24 * 60, // 1 day minimum
    maxDailyTrades: 3,
    r2rRatio: 3,
    description: 'Trend capture over days. Lower frequency, larger targets.',
    emoji: '📈',
  },
  HYBRID: {
    mode: 'HYBRID',
    riskPerTrade: 1.25, // Average of both
    stopLossPercent: 1.25,
    takeProfitPercent: 4.5,
    timeFrame: 'mixed', // Both 5m and daily
    maxHoldMinutes: 120, // 2 hours balance
    maxDailyTrades: 10,
    r2rRatio: 2,
    description: '70% swing + 30% scalp. Best of both: trend capture + daily income.',
    emoji: '🎯',
  },
};

interface StrategyModeSelectorProps {
  onModeChange?: (mode: StrategyMode, preset: StrategyPreset) => void;
  defaultMode?: StrategyMode;
  variant?: 'full' | 'compact';
}

export default function StrategyModeSelector({
  onModeChange,
  defaultMode = 'SWING',
  variant = 'full',
}: StrategyModeSelectorProps) {
  const [selectedMode, setSelectedMode] = useState<StrategyMode>(defaultMode);
  const [showDetails, setShowDetails] = useState(false);

  // Load from localStorage on mount
  useEffect(() => {
    const saved = localStorage.getItem('trading-strategy-mode');
    if (saved && (saved === 'SCALP' || saved === 'SWING' || saved === 'HYBRID')) {
      setSelectedMode(saved);
    }
  }, []);

  const handleModeChange = useCallback(
    (mode: StrategyMode) => {
      setSelectedMode(mode);
      localStorage.setItem('trading-strategy-mode', mode);
      const preset = STRATEGY_PRESETS[mode];
      onModeChange?.(mode, preset);
    },
    [onModeChange]
  );

  const preset = STRATEGY_PRESETS[selectedMode];

  if (variant === 'compact') {
    return (
      <div className="flex gap-2">
        {(Object.keys(STRATEGY_PRESETS) as StrategyMode[]).map((mode) => (
          <button
            key={mode}
            onClick={() => handleModeChange(mode)}
            className={`px-3 py-1 text-xs font-semibold rounded transition ${
              selectedMode === mode
                ? 'bg-blue-600 text-white'
                : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
            }`}
          >
            {STRATEGY_PRESETS[mode].emoji} {mode}
          </button>
        ))}
      </div>
    );
  }

  return (
    <div className="card space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold flex items-center gap-2">
          <Layers className="w-5 h-5 text-blue-500" />
          Trading Strategy Mode
        </h3>
        <button
          onClick={() => setShowDetails(!showDetails)}
          className="text-xs text-blue-400 hover:text-blue-300 underline"
        >
          {showDetails ? 'Hide' : 'Show'} Details
        </button>
      </div>

      {/* Mode Selector Buttons */}
      <div className="grid grid-cols-3 gap-2">
        {(Object.keys(STRATEGY_PRESETS) as StrategyMode[]).map((mode) => {
          const modePreset = STRATEGY_PRESETS[mode];
          const isSelected = selectedMode === mode;

          return (
            <button
              key={mode}
              onClick={() => handleModeChange(mode)}
              className={`p-4 rounded-lg border-2 transition text-center ${
                isSelected
                  ? 'border-blue-500 bg-blue-500/10'
                  : 'border-gray-700 bg-gray-900/50 hover:border-gray-600'
              }`}
            >
              <div className="text-2xl mb-2">{modePreset.emoji}</div>
              <div className="font-semibold text-sm">{mode}</div>
              <div className="text-xs text-gray-400 mt-1">
                {mode === 'SCALP' && 'Quick Moves'}
                {mode === 'SWING' && 'Trend Capture'}
                {mode === 'HYBRID' && 'Balanced'}
              </div>
            </button>
          );
        })}
      </div>

      {/* Current Mode Info */}
      <div className="p-3 bg-blue-500/10 rounded-lg border border-blue-500/30">
        <p className="text-sm text-gray-300 mb-2">{preset.description}</p>
      </div>

      {/* Detailed Parameters (Toggle) */}
      {showDetails && (
        <div className="p-4 bg-dark-bg rounded-lg border border-dark-border space-y-3">
          <div className="grid grid-cols-2 gap-4 text-sm">
            {/* Scalp Parameters */}
            <div className="col-span-2">
              <h4 className="font-semibold text-xs text-gray-400 mb-2 uppercase">
                Risk Management
              </h4>
            </div>

            <div>
              <span className="text-gray-400">Risk per Trade:</span>
              <div className="font-medium text-blue-400">{preset.riskPerTrade}%</div>
            </div>

            <div>
              <span className="text-gray-400">Stop Loss:</span>
              <div className="font-medium text-red-400">{preset.stopLossPercent}%</div>
            </div>

            <div>
              <span className="text-gray-400">Take Profit:</span>
              <div className="font-medium text-green-400">{preset.takeProfitPercent}%</div>
            </div>

            <div>
              <span className="text-gray-400">R:R Ratio:</span>
              <div className="font-medium text-yellow-400">1:{preset.r2rRatio.toFixed(1)}</div>
            </div>

            {/* Time Parameters */}
            <div className="col-span-2 border-t border-dark-border pt-3 mt-3">
              <h4 className="font-semibold text-xs text-gray-400 mb-2 uppercase">
                Time & Frequency
              </h4>
            </div>

            <div>
              <span className="text-gray-400">Time Frame:</span>
              <div className="font-medium text-purple-400">{preset.timeFrame}</div>
            </div>

            <div>
              <span className="text-gray-400">Max Hold Time:</span>
              <div className="font-medium text-purple-400">
                {preset.maxHoldMinutes >= 60
                  ? `${(preset.maxHoldMinutes / 60).toFixed(1)}h`
                  : `${preset.maxHoldMinutes}m`}
              </div>
            </div>

            <div className="col-span-2">
              <span className="text-gray-400">Max Daily Trades:</span>
              <div className="font-medium text-purple-400">{preset.maxDailyTrades} trades</div>
            </div>
          </div>

          {/* Strategy Tips */}
          <div className="border-t border-dark-border pt-3 mt-3">
            <h4 className="font-semibold text-xs text-gray-400 mb-2 uppercase">
              💡 Strategy Tips
            </h4>
            <ul className="text-xs text-gray-400 space-y-1 list-disc list-inside">
              {selectedMode === 'SCALP' && (
                <>
                  <li>Use 1-5 min charts for entry signals</li>
                  <li>Close 50% at 0.5% profit, let 50% run to 1%</li>
                  <li>Avoid holding through market chop</li>
                  <li>Speed is critical - execute fast</li>
                  <li>Max 5-20 trades per day depending on volatility</li>
                </>
              )}
              {selectedMode === 'SWING' && (
                <>
                  <li>Confirm trends with EMA alignment</li>
                  <li>Use support/resistance for entries</li>
                  <li>Partial profit taking at 1:2, 1:3 levels</li>
                  <li>Use trailing stops to protect gains</li>
                  <li>Hold 1-5 days for trend capture</li>
                </>
              )}
              {selectedMode === 'HYBRID' && (
                <>
                  <li>Allocate 70% capital to swing trades</li>
                  <li>Allocate 30% capital to scalping</li>
                  <li>Scalping provides daily income buffer</li>
                  <li>Swings capture larger trends</li>
                  <li>Balance reduces psychological stress</li>
                </>
              )}
            </ul>
          </div>
        </div>
      )}

      {/* Action Buttons */}
      <div className="flex gap-2 pt-2">
        <button
          onClick={() => handleModeChange('SCALP')}
          className={`flex-1 py-2 px-3 rounded text-sm font-medium transition ${
            selectedMode === 'SCALP'
              ? 'bg-yellow-600 text-white'
              : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
          }`}
        >
          <Zap className="w-4 h-4 inline mr-1" />
          Scalping
        </button>
        <button
          onClick={() => handleModeChange('SWING')}
          className={`flex-1 py-2 px-3 rounded text-sm font-medium transition ${
            selectedMode === 'SWING'
              ? 'bg-blue-600 text-white'
              : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
          }`}
        >
          <TrendingUp className="w-4 h-4 inline mr-1" />
          Swing
        </button>
        <button
          onClick={() => handleModeChange('HYBRID')}
          className={`flex-1 py-2 px-3 rounded text-sm font-medium transition ${
            selectedMode === 'HYBRID'
              ? 'bg-purple-600 text-white'
              : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
          }`}
        >
          <Layers className="w-4 h-4 inline mr-1" />
          Hybrid
        </button>
      </div>
    </div>
  );
}
