/**
 * Trade Execution Modal
 * Modal for confirming and executing trades based on ML signals
 */

import React, { useState, useEffect } from 'react';
import {
  XMarkIcon,
  ArrowTrendingUpIcon,
  ArrowTrendingDownIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  ArrowPathIcon,
} from '@heroicons/react/24/solid';
import {
  executeMLTrade,
  getMT4Account,
  calculatePositionSize,
  type MLTradeRequest,
  type MLTradeResult,
  type MT4Account,
} from '../../../services/trading.service';
import type { ICTAnalysis, EnsembleSignal } from '../../../services/mlService';

interface TradeExecutionModalProps {
  isOpen: boolean;
  onClose: () => void;
  direction: 'buy' | 'sell';
  symbol: string;
  source: 'ict' | 'ensemble' | 'manual';
  analysisData?: ICTAnalysis | EnsembleSignal | null;
  entryPrice?: number;
  stopLoss?: number;
  takeProfit?: number;
}

export const TradeExecutionModal: React.FC<TradeExecutionModalProps> = ({
  isOpen,
  onClose,
  direction,
  symbol,
  source,
  analysisData,
  entryPrice,
  stopLoss,
  takeProfit,
}) => {
  const [mt4Account, setMt4Account] = useState<MT4Account | null>(null);
  const [loading, setLoading] = useState(false);
  const [executing, setExecuting] = useState(false);
  const [result, setResult] = useState<MLTradeResult | null>(null);

  // Form state
  const [riskPercent, setRiskPercent] = useState(1);
  const [lotSize, setLotSize] = useState<number | undefined>();
  const [slPrice, setSlPrice] = useState(stopLoss);
  const [tpPrice, setTpPrice] = useState(takeProfit);
  const [calculatedSize, setCalculatedSize] = useState<{ lot_size: number; risk_amount: number } | null>(null);

  // Load MT4 account info
  useEffect(() => {
    if (isOpen) {
      loadAccountInfo();
    }
  }, [isOpen]);

  // Update SL/TP when props change
  useEffect(() => {
    setSlPrice(stopLoss);
    setTpPrice(takeProfit);
  }, [stopLoss, takeProfit]);

  const loadAccountInfo = async () => {
    setLoading(true);
    try {
      const account = await getMT4Account();
      setMt4Account(account);
    } catch (error) {
      console.error('Failed to load MT4 account:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCalculateSize = async () => {
    if (!slPrice || !entryPrice) return;

    const pipDiff = Math.abs(entryPrice - slPrice);
    const pips = symbol.includes('JPY') ? pipDiff * 100 : pipDiff * 10000;

    const result = await calculatePositionSize(symbol, pips, riskPercent);
    if (result) {
      setCalculatedSize(result);
      setLotSize(result.lot_size);
    }
  };

  const handleExecute = async () => {
    setExecuting(true);
    setResult(null);

    const request: MLTradeRequest = {
      symbol,
      direction,
      source,
      entry_price: entryPrice,
      stop_loss: slPrice,
      take_profit: tpPrice,
      risk_percent: riskPercent,
      lot_size: lotSize,
      analysis_data: analysisData ? JSON.parse(JSON.stringify(analysisData)) : undefined,
    };

    try {
      const tradeResult = await executeMLTrade(request);
      setResult(tradeResult);

      if (tradeResult.success) {
        setTimeout(() => {
          onClose();
        }, 2000);
      }
    } catch (error) {
      setResult({
        success: false,
        message: 'Trade execution failed',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    } finally {
      setExecuting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70">
      <div className="bg-gray-900 border border-gray-700 rounded-xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className={`flex items-center justify-between p-4 border-b border-gray-700 ${
          direction === 'buy' ? 'bg-green-900/20' : 'bg-red-900/20'
        }`}>
          <div className="flex items-center gap-3">
            {direction === 'buy' ? (
              <ArrowTrendingUpIcon className="w-6 h-6 text-green-400" />
            ) : (
              <ArrowTrendingDownIcon className="w-6 h-6 text-red-400" />
            )}
            <div>
              <h2 className="text-lg font-bold text-white">
                Execute {direction.toUpperCase()} Trade
              </h2>
              <p className="text-sm text-gray-400">{symbol} • Source: {source.toUpperCase()}</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-1 hover:bg-gray-700 rounded transition-colors"
          >
            <XMarkIcon className="w-5 h-5 text-gray-400" />
          </button>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {/* Account Info */}
          {loading ? (
            <div className="flex items-center justify-center p-4">
              <ArrowPathIcon className="w-5 h-5 animate-spin text-gray-400" />
              <span className="ml-2 text-gray-400">Loading account...</span>
            </div>
          ) : mt4Account ? (
            <div className="p-3 bg-gray-800 rounded-lg">
              <h3 className="text-sm font-semibold text-gray-400 mb-2">MT4 Account</h3>
              <div className="grid grid-cols-2 gap-2 text-sm">
                <div>
                  <span className="text-gray-500">Balance:</span>
                  <span className="ml-2 text-white">${mt4Account.balance.toFixed(2)}</span>
                </div>
                <div>
                  <span className="text-gray-500">Equity:</span>
                  <span className="ml-2 text-white">${mt4Account.equity.toFixed(2)}</span>
                </div>
                <div>
                  <span className="text-gray-500">Free Margin:</span>
                  <span className="ml-2 text-white">${mt4Account.free_margin.toFixed(2)}</span>
                </div>
                <div>
                  <span className="text-gray-500">Leverage:</span>
                  <span className="ml-2 text-white">1:{mt4Account.leverage}</span>
                </div>
              </div>
            </div>
          ) : (
            <div className="p-3 bg-yellow-900/20 border border-yellow-800 rounded-lg flex items-center gap-2">
              <ExclamationTriangleIcon className="w-5 h-5 text-yellow-400" />
              <span className="text-sm text-yellow-400">MT4 account not connected</span>
            </div>
          )}

          {/* Trade Parameters */}
          <div className="space-y-3">
            <h3 className="text-sm font-semibold text-gray-400">Trade Parameters</h3>

            {/* Entry Price */}
            <div className="flex items-center justify-between p-3 bg-gray-800 rounded-lg">
              <span className="text-sm text-gray-400">Entry Price</span>
              <span className="font-mono text-white">{entryPrice?.toFixed(5) || 'Market'}</span>
            </div>

            {/* Stop Loss */}
            <div className="p-3 bg-gray-800 rounded-lg">
              <label className="block text-sm text-gray-400 mb-1">Stop Loss</label>
              <input
                type="number"
                step="0.00001"
                value={slPrice || ''}
                onChange={(e) => setSlPrice(parseFloat(e.target.value) || undefined)}
                className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white font-mono focus:outline-none focus:border-red-500"
                placeholder="0.00000"
              />
            </div>

            {/* Take Profit */}
            <div className="p-3 bg-gray-800 rounded-lg">
              <label className="block text-sm text-gray-400 mb-1">Take Profit</label>
              <input
                type="number"
                step="0.00001"
                value={tpPrice || ''}
                onChange={(e) => setTpPrice(parseFloat(e.target.value) || undefined)}
                className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white font-mono focus:outline-none focus:border-green-500"
                placeholder="0.00000"
              />
            </div>

            {/* Risk Management */}
            <div className="p-3 bg-gray-800 rounded-lg">
              <div className="flex items-center justify-between mb-2">
                <label className="text-sm text-gray-400">Risk %</label>
                <button
                  onClick={handleCalculateSize}
                  className="text-xs px-2 py-1 bg-purple-600 hover:bg-purple-700 rounded transition-colors"
                >
                  Calculate Size
                </button>
              </div>
              <div className="flex gap-2">
                {[0.5, 1, 2, 3].map((risk) => (
                  <button
                    key={risk}
                    onClick={() => setRiskPercent(risk)}
                    className={`flex-1 py-2 text-sm rounded transition-colors ${
                      riskPercent === risk
                        ? 'bg-purple-600 text-white'
                        : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                    }`}
                  >
                    {risk}%
                  </button>
                ))}
              </div>
              {calculatedSize && (
                <div className="mt-2 text-sm">
                  <span className="text-gray-400">Lot Size:</span>
                  <span className="ml-2 text-white font-bold">{calculatedSize.lot_size}</span>
                  <span className="ml-4 text-gray-400">Risk:</span>
                  <span className="ml-2 text-red-400">${calculatedSize.risk_amount.toFixed(2)}</span>
                </div>
              )}
            </div>

            {/* Manual Lot Size */}
            <div className="p-3 bg-gray-800 rounded-lg">
              <label className="block text-sm text-gray-400 mb-1">Lot Size (Manual)</label>
              <input
                type="number"
                step="0.01"
                min="0.01"
                value={lotSize || ''}
                onChange={(e) => setLotSize(parseFloat(e.target.value) || undefined)}
                className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white font-mono focus:outline-none focus:border-purple-500"
                placeholder="0.01"
              />
            </div>
          </div>

          {/* Result Message */}
          {result && (
            <div className={`p-3 rounded-lg flex items-center gap-2 ${
              result.success
                ? 'bg-green-900/20 border border-green-800'
                : 'bg-red-900/20 border border-red-800'
            }`}>
              {result.success ? (
                <CheckCircleIcon className="w-5 h-5 text-green-400" />
              ) : (
                <ExclamationTriangleIcon className="w-5 h-5 text-red-400" />
              )}
              <div>
                <p className={result.success ? 'text-green-400' : 'text-red-400'}>
                  {result.message}
                </p>
                {result.error && (
                  <p className="text-sm text-red-300">{result.error}</p>
                )}
                {result.executed_price && (
                  <p className="text-sm text-green-300">
                    Executed at: {result.executed_price.toFixed(5)}
                  </p>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex gap-3 p-4 border-t border-gray-700">
          <button
            onClick={onClose}
            className="flex-1 py-3 bg-gray-700 hover:bg-gray-600 text-white rounded-lg font-semibold transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleExecute}
            disabled={executing || !lotSize}
            className={`flex-1 py-3 rounded-lg font-semibold transition-colors flex items-center justify-center gap-2 ${
              direction === 'buy'
                ? 'bg-green-600 hover:bg-green-700 text-white disabled:bg-green-800 disabled:opacity-50'
                : 'bg-red-600 hover:bg-red-700 text-white disabled:bg-red-800 disabled:opacity-50'
            }`}
          >
            {executing ? (
              <>
                <ArrowPathIcon className="w-4 h-4 animate-spin" />
                Executing...
              </>
            ) : (
              `Execute ${direction.toUpperCase()}`
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

export default TradeExecutionModal;
