/**
 * AdvancedOrderEntry Component
 * Professional order placement form for MT4 live trading
 */

import React, { useState, useMemo } from 'react';
import {
  TrendingUp,
  TrendingDown,
  Calculator,
  Shield,
  Target,
  AlertTriangle,
  Loader2,
  Info,
  Zap,
} from 'lucide-react';
import {
  executeMLTrade,
  calculatePositionSize,
  type MT4Account,
} from '../../../services/trading.service';

type OrderType = 'market' | 'limit' | 'stop';
type OrderSide = 'buy' | 'sell';

interface AdvancedOrderEntryProps {
  symbol: string;
  currentPrice: number;
  spread?: number;
  account: MT4Account | null;
  onOrderExecuted?: (ticket: number) => void;
  onError?: (error: string) => void;
}

const AdvancedOrderEntry: React.FC<AdvancedOrderEntryProps> = ({
  symbol,
  currentPrice,
  spread = 0,
  account,
  onOrderExecuted,
  onError,
}) => {
  const [orderType, setOrderType] = useState<OrderType>('market');
  const [side, setSide] = useState<OrderSide>('buy');
  const [volume, setVolume] = useState('0.01');
  const [limitPrice, setLimitPrice] = useState('');
  const [stopLossMode, setStopLossMode] = useState<'price' | 'pips' | 'percent'>('pips');
  const [stopLoss, setStopLoss] = useState('');
  const [takeProfitMode, setTakeProfitMode] = useState<'price' | 'pips' | 'rr'>('pips');
  const [takeProfit, setTakeProfit] = useState('');
  const [riskPercent, setRiskPercent] = useState('1');
  const [useRiskCalculator, setUseRiskCalculator] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showAdvanced, setShowAdvanced] = useState(false);

  // Calculate pip value based on symbol
  const pipValue = useMemo(() => {
    return symbol.includes('JPY') ? 0.01 : 0.0001;
  }, [symbol]);

  // Calculate SL price from different modes
  const calculateSLPrice = (): number | undefined => {
    if (!stopLoss) return undefined;
    const slValue = parseFloat(stopLoss);
    if (isNaN(slValue)) return undefined;

    switch (stopLossMode) {
      case 'price':
        return slValue;
      case 'pips':
        return side === 'buy'
          ? currentPrice - slValue * pipValue
          : currentPrice + slValue * pipValue;
      case 'percent':
        const percentLoss = (slValue / 100) * currentPrice;
        return side === 'buy'
          ? currentPrice - percentLoss
          : currentPrice + percentLoss;
      default:
        return undefined;
    }
  };

  // Calculate TP price from different modes
  const calculateTPPrice = (): number | undefined => {
    if (!takeProfit) return undefined;
    const tpValue = parseFloat(takeProfit);
    if (isNaN(tpValue)) return undefined;

    switch (takeProfitMode) {
      case 'price':
        return tpValue;
      case 'pips':
        return side === 'buy'
          ? currentPrice + tpValue * pipValue
          : currentPrice - tpValue * pipValue;
      case 'rr':
        const slPrice = calculateSLPrice();
        if (!slPrice) return undefined;
        const riskDistance = Math.abs(currentPrice - slPrice);
        return side === 'buy'
          ? currentPrice + riskDistance * tpValue
          : currentPrice - riskDistance * tpValue;
      default:
        return undefined;
    }
  };

  // Calculate position size based on risk
  const calculatedVolume = useMemo(() => {
    if (!useRiskCalculator || !account || !stopLoss) return null;
    const slPips = stopLossMode === 'pips' ? parseFloat(stopLoss) : null;
    if (!slPips) return null;

    const risk = parseFloat(riskPercent);
    if (isNaN(risk)) return null;

    // Simple calculation: risk amount / (sl_pips * pip_value_per_lot)
    const riskAmount = (account.balance * risk) / 100;
    const pipValuePerLot = symbol.includes('JPY') ? 1000 : 10; // Approximate
    const lots = riskAmount / (slPips * pipValuePerLot);
    return Math.max(0.01, Math.min(lots, 10)).toFixed(2);
  }, [useRiskCalculator, account, stopLoss, stopLossMode, riskPercent, symbol]);

  // Calculate estimated margin
  const estimatedMargin = useMemo(() => {
    if (!account) return null;
    const lots = parseFloat(useRiskCalculator && calculatedVolume ? calculatedVolume : volume);
    if (isNaN(lots)) return null;
    // Approximate margin calculation (100:1 leverage)
    const leverage = account.leverage || 100;
    return (lots * 100000 * currentPrice) / leverage;
  }, [account, volume, calculatedVolume, useRiskCalculator, currentPrice]);

  // Risk/Reward ratio
  const riskRewardRatio = useMemo(() => {
    const slPrice = calculateSLPrice();
    const tpPrice = calculateTPPrice();
    if (!slPrice || !tpPrice) return null;
    const risk = Math.abs(currentPrice - slPrice);
    const reward = Math.abs(tpPrice - currentPrice);
    if (risk === 0) return null;
    return (reward / risk).toFixed(2);
  }, [currentPrice, stopLoss, takeProfit, stopLossMode, takeProfitMode, side]);

  const handleSubmit = async () => {
    if (!account) {
      onError?.('No account connected');
      return;
    }

    setIsSubmitting(true);
    try {
      const finalVolume = useRiskCalculator && calculatedVolume ? calculatedVolume : volume;
      const slPrice = calculateSLPrice();
      const tpPrice = calculateTPPrice();

      const result = await executeMLTrade({
        symbol,
        direction: side,
        source: 'manual',
        entry_price: orderType === 'market' ? currentPrice : parseFloat(limitPrice),
        stop_loss: slPrice,
        take_profit: tpPrice,
        lot_size: parseFloat(finalVolume),
      });

      if (result.success && (result.trade_id || result.order_id)) {
        onOrderExecuted?.(Number(result.trade_id || result.order_id) || 0);
        // Reset form
        setVolume('0.01');
        setStopLoss('');
        setTakeProfit('');
        setLimitPrice('');
      }
    } catch (err) {
      onError?.(err instanceof Error ? err.message : 'Order execution failed');
    } finally {
      setIsSubmitting(false);
    }
  };

  const slPrice = calculateSLPrice();
  const tpPrice = calculateTPPrice();

  return (
    <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b border-gray-700">
        <div>
          <h3 className="font-medium text-white">Order Entry</h3>
          <p className="text-sm text-gray-400">{symbol}</p>
        </div>
        <div className="text-right">
          <p className="text-lg font-mono font-bold text-white">{currentPrice.toFixed(5)}</p>
          {spread > 0 && (
            <p className="text-xs text-gray-500">Spread: {spread.toFixed(1)} pips</p>
          )}
        </div>
      </div>

      <div className="p-4 space-y-4">
        {/* Buy/Sell Buttons */}
        <div className="grid grid-cols-2 gap-2">
          <button
            onClick={() => setSide('buy')}
            className={`flex items-center justify-center gap-2 py-3 rounded-lg font-medium transition-colors ${
              side === 'buy'
                ? 'bg-green-600 text-white'
                : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
            }`}
          >
            <TrendingUp className="w-5 h-5" />
            BUY
          </button>
          <button
            onClick={() => setSide('sell')}
            className={`flex items-center justify-center gap-2 py-3 rounded-lg font-medium transition-colors ${
              side === 'sell'
                ? 'bg-red-600 text-white'
                : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
            }`}
          >
            <TrendingDown className="w-5 h-5" />
            SELL
          </button>
        </div>

        {/* Order Type */}
        <div>
          <label className="block text-sm text-gray-400 mb-2">Order Type</label>
          <div className="grid grid-cols-3 gap-2">
            {(['market', 'limit', 'stop'] as OrderType[]).map((type) => (
              <button
                key={type}
                onClick={() => setOrderType(type)}
                className={`py-2 text-sm rounded-lg transition-colors ${
                  orderType === type
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                }`}
              >
                {type.charAt(0).toUpperCase() + type.slice(1)}
              </button>
            ))}
          </div>
        </div>

        {/* Limit/Stop Price */}
        {orderType !== 'market' && (
          <div>
            <label className="block text-sm text-gray-400 mb-2">
              {orderType === 'limit' ? 'Limit' : 'Stop'} Price
            </label>
            <input
              type="number"
              step="0.00001"
              value={limitPrice}
              onChange={(e) => setLimitPrice(e.target.value)}
              placeholder={currentPrice.toFixed(5)}
              className="w-full px-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white font-mono focus:outline-none focus:border-blue-500"
            />
          </div>
        )}

        {/* Volume / Risk Calculator Toggle */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="text-sm text-gray-400">Volume (lots)</label>
            <button
              onClick={() => setUseRiskCalculator(!useRiskCalculator)}
              className={`flex items-center gap-1 text-xs px-2 py-1 rounded transition-colors ${
                useRiskCalculator
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-700 text-gray-400 hover:text-white'
              }`}
            >
              <Calculator className="w-3 h-3" />
              Risk Calculator
            </button>
          </div>

          {useRiskCalculator ? (
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <input
                  type="number"
                  step="0.5"
                  min="0.1"
                  max="10"
                  value={riskPercent}
                  onChange={(e) => setRiskPercent(e.target.value)}
                  className="flex-1 px-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-blue-500"
                />
                <span className="text-gray-400">% Risk</span>
              </div>
              {calculatedVolume && (
                <p className="text-sm text-green-400">
                  Calculated: {calculatedVolume} lots
                </p>
              )}
            </div>
          ) : (
            <input
              type="number"
              step="0.01"
              min="0.01"
              max="10"
              value={volume}
              onChange={(e) => setVolume(e.target.value)}
              className="w-full px-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white font-mono focus:outline-none focus:border-blue-500"
            />
          )}
        </div>

        {/* Stop Loss */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="flex items-center gap-2 text-sm text-gray-400">
              <Shield className="w-4 h-4 text-red-400" />
              Stop Loss
            </label>
            <div className="flex gap-1">
              {(['pips', 'price', 'percent'] as const).map((mode) => (
                <button
                  key={mode}
                  onClick={() => setStopLossMode(mode)}
                  className={`px-2 py-0.5 text-xs rounded ${
                    stopLossMode === mode
                      ? 'bg-red-600 text-white'
                      : 'bg-gray-700 text-gray-400'
                  }`}
                >
                  {mode}
                </button>
              ))}
            </div>
          </div>
          <div className="flex items-center gap-2">
            <input
              type="number"
              step={stopLossMode === 'price' ? '0.00001' : '1'}
              value={stopLoss}
              onChange={(e) => setStopLoss(e.target.value)}
              placeholder={stopLossMode === 'price' ? currentPrice.toFixed(5) : '20'}
              className="flex-1 px-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white font-mono focus:outline-none focus:border-red-500"
            />
            {slPrice && (
              <span className="text-sm text-red-400 font-mono">{slPrice.toFixed(5)}</span>
            )}
          </div>
        </div>

        {/* Take Profit */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="flex items-center gap-2 text-sm text-gray-400">
              <Target className="w-4 h-4 text-green-400" />
              Take Profit
            </label>
            <div className="flex gap-1">
              {(['pips', 'price', 'rr'] as const).map((mode) => (
                <button
                  key={mode}
                  onClick={() => setTakeProfitMode(mode)}
                  className={`px-2 py-0.5 text-xs rounded ${
                    takeProfitMode === mode
                      ? 'bg-green-600 text-white'
                      : 'bg-gray-700 text-gray-400'
                  }`}
                >
                  {mode === 'rr' ? 'R:R' : mode}
                </button>
              ))}
            </div>
          </div>
          <div className="flex items-center gap-2">
            <input
              type="number"
              step={takeProfitMode === 'price' ? '0.00001' : takeProfitMode === 'rr' ? '0.5' : '1'}
              value={takeProfit}
              onChange={(e) => setTakeProfit(e.target.value)}
              placeholder={takeProfitMode === 'price' ? currentPrice.toFixed(5) : takeProfitMode === 'rr' ? '2' : '40'}
              className="flex-1 px-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white font-mono focus:outline-none focus:border-green-500"
            />
            {tpPrice && (
              <span className="text-sm text-green-400 font-mono">{tpPrice.toFixed(5)}</span>
            )}
          </div>
        </div>

        {/* Order Summary */}
        <div className="p-3 bg-gray-900/50 rounded-lg space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-400">Risk/Reward</span>
            <span className={`font-medium ${
              riskRewardRatio && parseFloat(riskRewardRatio) >= 2
                ? 'text-green-400'
                : riskRewardRatio && parseFloat(riskRewardRatio) >= 1
                ? 'text-yellow-400'
                : 'text-red-400'
            }`}>
              {riskRewardRatio ? `1:${riskRewardRatio}` : '-'}
            </span>
          </div>
          {estimatedMargin && (
            <div className="flex items-center justify-between text-sm">
              <span className="text-gray-400">Est. Margin</span>
              <span className="text-white">${estimatedMargin.toFixed(2)}</span>
            </div>
          )}
          {account && estimatedMargin && (
            <div className="flex items-center justify-between text-sm">
              <span className="text-gray-400">Free Margin After</span>
              <span className={`${
                account.free_margin - estimatedMargin > 0 ? 'text-green-400' : 'text-red-400'
              }`}>
                ${(account.free_margin - estimatedMargin).toFixed(2)}
              </span>
            </div>
          )}
        </div>

        {/* Warning */}
        {(!slPrice || !tpPrice) && (
          <div className="flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
            <AlertTriangle className="w-4 h-4 text-yellow-400 flex-shrink-0 mt-0.5" />
            <p className="text-sm text-yellow-400">
              {!slPrice && !tpPrice
                ? 'No SL or TP set. Consider adding risk management.'
                : !slPrice
                ? 'No Stop Loss set. Position has unlimited risk.'
                : 'No Take Profit set.'}
            </p>
          </div>
        )}

        {/* Submit Button */}
        <button
          onClick={handleSubmit}
          disabled={isSubmitting || !account}
          className={`w-full flex items-center justify-center gap-2 py-3 rounded-lg font-medium transition-colors disabled:opacity-50 ${
            side === 'buy'
              ? 'bg-green-600 hover:bg-green-500 text-white'
              : 'bg-red-600 hover:bg-red-500 text-white'
          }`}
        >
          {isSubmitting ? (
            <>
              <Loader2 className="w-5 h-5 animate-spin" />
              Executing...
            </>
          ) : (
            <>
              <Zap className="w-5 h-5" />
              {side === 'buy' ? 'Place Buy Order' : 'Place Sell Order'}
            </>
          )}
        </button>

        {!account && (
          <p className="text-center text-sm text-gray-500">
            Connect MT4 account to place orders
          </p>
        )}
      </div>
    </div>
  );
};

export default AdvancedOrderEntry;
