/**
 * SignalExecutionPanel Component
 * Execute and validate trading signals from assistant recommendations
 */

import React, { useState, useMemo } from 'react';
import {
  TrendingUp,
  TrendingDown,
  Shield,
  Target,
  AlertTriangle,
  CheckCircle,
  XCircle,
  Loader2,
  Calculator,
  Zap,
  Info,
  ChevronDown,
  ChevronUp,
} from 'lucide-react';
import type { TradingSignal } from './SignalCard';

interface SignalExecutionPanelProps {
  signal: TradingSignal;
  accountBalance?: number;
  onExecute?: (params: ExecutionParams) => Promise<ExecutionResult>;
  onCancel?: () => void;
}

export interface ExecutionParams {
  symbol: string;
  direction: 'BUY' | 'SELL';
  volume: number;
  entry: number;
  stopLoss?: number;
  takeProfit?: number;
  riskPercent: number;
}

export interface ExecutionResult {
  success: boolean;
  ticket?: number;
  error?: string;
  executedPrice?: number;
  executedVolume?: number;
}

interface ValidationResult {
  isValid: boolean;
  warnings: string[];
  errors: string[];
  riskAssessment: 'low' | 'medium' | 'high' | 'extreme';
}

const SignalExecutionPanel: React.FC<SignalExecutionPanelProps> = ({
  signal,
  accountBalance = 10000,
  onExecute,
  onCancel,
}) => {
  const [volume, setVolume] = useState('0.01');
  const [riskPercent, setRiskPercent] = useState('1');
  const [useAutoSize, setUseAutoSize] = useState(true);
  const [showDetails, setShowDetails] = useState(false);
  const [isExecuting, setIsExecuting] = useState(false);
  const [executionResult, setExecutionResult] = useState<ExecutionResult | null>(null);
  const [confirmStep, setConfirmStep] = useState(false);

  const isBuy = signal.direction === 'BUY' || signal.direction === 'LONG';

  // Get entry price with fallback to entry_price
  const entryPrice = signal.entry ?? signal.entry_price ?? 0;
  const stopLossPrice = signal.stopLoss ?? signal.stop_loss;
  const takeProfitPrice = signal.takeProfit ?? signal.take_profit;

  // Calculate position size based on risk
  const calculatedVolume = useMemo(() => {
    if (!stopLossPrice || !useAutoSize) return parseFloat(volume) || 0.01;

    const risk = parseFloat(riskPercent) || 1;
    const riskAmount = (accountBalance * risk) / 100;
    const slPips = Math.abs(entryPrice - stopLossPrice) * (signal.symbol.includes('JPY') ? 100 : 10000);
    const pipValue = signal.symbol.includes('JPY') ? 1000 : 10; // Approximate per standard lot

    if (slPips === 0) return 0.01;

    const lots = riskAmount / (slPips * pipValue);
    return Math.max(0.01, Math.min(parseFloat(lots.toFixed(2)), 10));
  }, [signal, accountBalance, riskPercent, useAutoSize, volume, entryPrice, stopLossPrice]);

  // Calculate risk/reward
  const riskReward = useMemo(() => {
    if (!stopLossPrice || !takeProfitPrice) return null;
    const risk = Math.abs(entryPrice - stopLossPrice);
    const reward = Math.abs(takeProfitPrice - entryPrice);
    if (risk === 0) return null;
    return reward / risk;
  }, [entryPrice, stopLossPrice, takeProfitPrice]);

  // Calculate potential outcomes
  const potentialLoss = useMemo(() => {
    if (!stopLossPrice) return null;
    const pips = Math.abs(entryPrice - stopLossPrice) * (signal.symbol.includes('JPY') ? 100 : 10000);
    const pipValue = signal.symbol.includes('JPY') ? 1000 : 10;
    return calculatedVolume * pips * pipValue;
  }, [signal.symbol, calculatedVolume, entryPrice, stopLossPrice]);

  const potentialProfit = useMemo(() => {
    if (!takeProfitPrice) return null;
    const pips = Math.abs(takeProfitPrice - entryPrice) * (signal.symbol.includes('JPY') ? 100 : 10000);
    const pipValue = signal.symbol.includes('JPY') ? 1000 : 10;
    return calculatedVolume * pips * pipValue;
  }, [signal.symbol, calculatedVolume, entryPrice, takeProfitPrice]);

  // Validate the signal
  const validation = useMemo((): ValidationResult => {
    const warnings: string[] = [];
    const errors: string[] = [];

    // Check for stop loss
    if (!signal.stopLoss) {
      warnings.push('No stop loss defined - unlimited risk');
    }

    // Check for take profit
    if (!signal.takeProfit) {
      warnings.push('No take profit defined');
    }

    // Check confidence
    if (signal.confidence && signal.confidence < 60) {
      warnings.push(`Low confidence signal (${signal.confidence}%)`);
    }

    // Check risk/reward
    if (riskReward && riskReward < 1) {
      warnings.push(`Poor risk/reward ratio (1:${riskReward.toFixed(2)})`);
    }

    // Check position size vs account
    const riskAmount = potentialLoss || 0;
    const riskPct = (riskAmount / accountBalance) * 100;

    if (riskPct > 5) {
      errors.push(`Risk exceeds 5% of account (${riskPct.toFixed(1)}%)`);
    } else if (riskPct > 2) {
      warnings.push(`High risk position (${riskPct.toFixed(1)}% of account)`);
    }

    // Determine risk assessment
    let riskAssessment: ValidationResult['riskAssessment'] = 'low';
    if (errors.length > 0) riskAssessment = 'extreme';
    else if (warnings.length > 2) riskAssessment = 'high';
    else if (warnings.length > 0) riskAssessment = 'medium';

    return {
      isValid: errors.length === 0,
      warnings,
      errors,
      riskAssessment,
    };
  }, [signal, riskReward, potentialLoss, accountBalance]);

  const riskColors = {
    low: 'text-green-400 bg-green-500/20',
    medium: 'text-yellow-400 bg-yellow-500/20',
    high: 'text-orange-400 bg-orange-500/20',
    extreme: 'text-red-400 bg-red-500/20',
  };

  const handleExecute = async () => {
    if (!onExecute || !validation.isValid) return;

    setIsExecuting(true);
    setExecutionResult(null);

    try {
      const result = await onExecute({
        symbol: signal.symbol,
        direction: isBuy ? 'BUY' : 'SELL',
        volume: calculatedVolume,
        entry: entryPrice,
        stopLoss: stopLossPrice,
        takeProfit: takeProfitPrice,
        riskPercent: parseFloat(riskPercent),
      });

      setExecutionResult(result);

      if (result.success) {
        setConfirmStep(false);
      }
    } catch (err) {
      setExecutionResult({
        success: false,
        error: err instanceof Error ? err.message : 'Execution failed',
      });
    } finally {
      setIsExecuting(false);
    }
  };

  // Already executed successfully
  if (executionResult?.success) {
    return (
      <div className="bg-gray-800 rounded-xl border border-green-500/30 p-6 text-center">
        <CheckCircle className="w-12 h-12 text-green-400 mx-auto mb-3" />
        <h4 className="font-medium text-white mb-1">Order Executed</h4>
        <p className="text-sm text-gray-400 mb-2">
          Ticket #{executionResult.ticket}
        </p>
        <div className="text-sm text-gray-300">
          <p>{signal.symbol} {isBuy ? 'BUY' : 'SELL'} @ {executionResult.executedPrice?.toFixed(5)}</p>
          <p>Volume: {executionResult.executedVolume} lots</p>
        </div>
      </div>
    );
  }

  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 ${
        isBuy ? 'bg-green-500/10 border-green-500/30' : 'bg-red-500/10 border-red-500/30'
      }`}>
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${isBuy ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
            {isBuy ? (
              <TrendingUp className="w-5 h-5 text-green-400" />
            ) : (
              <TrendingDown className="w-5 h-5 text-red-400" />
            )}
          </div>
          <div>
            <h3 className="font-medium text-white">Execute Signal</h3>
            <p className="text-sm text-gray-400">
              {signal.symbol} • {isBuy ? 'BUY' : 'SELL'}
            </p>
          </div>
        </div>
        <div className={`px-3 py-1 rounded-full text-sm font-medium ${riskColors[validation.riskAssessment]}`}>
          {validation.riskAssessment.charAt(0).toUpperCase() + validation.riskAssessment.slice(1)} Risk
        </div>
      </div>

      <div className="p-4 space-y-4">
        {/* Signal Details */}
        <div className="grid grid-cols-3 gap-4 text-sm">
          <div className="text-center p-3 bg-gray-900/50 rounded-lg">
            <p className="text-gray-500 text-xs mb-1">Entry</p>
            <p className="text-white font-mono font-medium">{entryPrice.toFixed(5)}</p>
          </div>
          <div className="text-center p-3 bg-gray-900/50 rounded-lg">
            <p className="text-gray-500 text-xs mb-1">Stop Loss</p>
            <p className={`font-mono font-medium ${stopLossPrice ? 'text-red-400' : 'text-gray-500'}`}>
              {stopLossPrice?.toFixed(5) || 'Not set'}
            </p>
          </div>
          <div className="text-center p-3 bg-gray-900/50 rounded-lg">
            <p className="text-gray-500 text-xs mb-1">Take Profit</p>
            <p className={`font-mono font-medium ${takeProfitPrice ? 'text-green-400' : 'text-gray-500'}`}>
              {takeProfitPrice?.toFixed(5) || 'Not set'}
            </p>
          </div>
        </div>

        {/* Position Sizing */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="text-sm text-gray-400">Position Size</label>
            <button
              onClick={() => setUseAutoSize(!useAutoSize)}
              className={`flex items-center gap-1 text-xs px-2 py-1 rounded transition-colors ${
                useAutoSize
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-700 text-gray-400 hover:text-white'
              }`}
            >
              <Calculator className="w-3 h-3" />
              Auto-size
            </button>
          </div>

          {useAutoSize ? (
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <span className="text-sm text-gray-400">Risk:</span>
                <input
                  type="number"
                  step="0.5"
                  min="0.1"
                  max="5"
                  value={riskPercent}
                  onChange={(e) => setRiskPercent(e.target.value)}
                  className="w-20 px-2 py-1 bg-gray-900 border border-gray-700 rounded text-white text-sm focus:outline-none focus:border-blue-500"
                />
                <span className="text-sm text-gray-400">% of account</span>
              </div>
              <p className="text-sm text-green-400">
                Calculated: <span className="font-medium">{calculatedVolume.toFixed(2)}</span> 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-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-blue-500"
            />
          )}
        </div>

        {/* Potential Outcomes */}
        <div className="grid grid-cols-2 gap-3">
          <div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
            <div className="flex items-center gap-2 text-red-400 text-sm mb-1">
              <Shield className="w-4 h-4" />
              <span>Potential Loss</span>
            </div>
            <p className="text-lg font-bold text-red-400">
              ${potentialLoss?.toFixed(2) || '—'}
            </p>
          </div>
          <div className="p-3 bg-green-500/10 border border-green-500/30 rounded-lg">
            <div className="flex items-center gap-2 text-green-400 text-sm mb-1">
              <Target className="w-4 h-4" />
              <span>Potential Profit</span>
            </div>
            <p className="text-lg font-bold text-green-400">
              ${potentialProfit?.toFixed(2) || '—'}
            </p>
          </div>
        </div>

        {/* Risk/Reward & Confidence */}
        <div className="flex items-center justify-between text-sm">
          <div className="flex items-center gap-2">
            <span className="text-gray-400">R:R Ratio:</span>
            <span className={`font-medium ${
              riskReward && riskReward >= 2 ? 'text-green-400' :
              riskReward && riskReward >= 1 ? 'text-yellow-400' : 'text-red-400'
            }`}>
              {riskReward ? `1:${riskReward.toFixed(2)}` : '—'}
            </span>
          </div>
          {signal.confidence && (
            <div className="flex items-center gap-2">
              <span className="text-gray-400">Confidence:</span>
              <span className={`font-medium ${
                signal.confidence >= 70 ? 'text-green-400' :
                signal.confidence >= 50 ? 'text-yellow-400' : 'text-red-400'
              }`}>
                {signal.confidence}%
              </span>
            </div>
          )}
        </div>

        {/* Validation Warnings */}
        {(validation.warnings.length > 0 || validation.errors.length > 0) && (
          <div>
            <button
              onClick={() => setShowDetails(!showDetails)}
              className="flex items-center gap-2 text-sm text-yellow-400 hover:text-yellow-300"
            >
              <AlertTriangle className="w-4 h-4" />
              {validation.errors.length + validation.warnings.length} issue(s) found
              {showDetails ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
            </button>

            {showDetails && (
              <div className="mt-2 p-3 bg-gray-900/50 rounded-lg space-y-2">
                {validation.errors.map((error, i) => (
                  <div key={i} className="flex items-start gap-2 text-sm text-red-400">
                    <XCircle className="w-4 h-4 flex-shrink-0 mt-0.5" />
                    <span>{error}</span>
                  </div>
                ))}
                {validation.warnings.map((warning, i) => (
                  <div key={i} className="flex items-start gap-2 text-sm text-yellow-400">
                    <AlertTriangle className="w-4 h-4 flex-shrink-0 mt-0.5" />
                    <span>{warning}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Execution Error */}
        {executionResult?.error && (
          <div className="flex items-start gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
            <XCircle className="w-5 h-5 text-red-400 flex-shrink-0" />
            <div>
              <p className="font-medium text-red-400">Execution Failed</p>
              <p className="text-sm text-gray-300">{executionResult.error}</p>
            </div>
          </div>
        )}

        {/* Action Buttons */}
        {!confirmStep ? (
          <div className="flex items-center gap-2">
            {onCancel && (
              <button
                onClick={onCancel}
                className="flex-1 py-2.5 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm transition-colors"
              >
                Cancel
              </button>
            )}
            <button
              onClick={() => setConfirmStep(true)}
              disabled={!validation.isValid || !onExecute}
              className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
                isBuy
                  ? 'bg-green-600 hover:bg-green-500 text-white'
                  : 'bg-red-600 hover:bg-red-500 text-white'
              }`}
            >
              <Zap className="w-4 h-4" />
              Review Order
            </button>
          </div>
        ) : (
          <div className="space-y-3">
            <div className="p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
              <div className="flex items-center gap-2 text-yellow-400">
                <Info className="w-4 h-4" />
                <span className="font-medium">Confirm Execution</span>
              </div>
              <p className="text-sm text-gray-300 mt-1">
                {isBuy ? 'Buy' : 'Sell'} {calculatedVolume.toFixed(2)} lots of {signal.symbol} at market price
              </p>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setConfirmStep(false)}
                className="flex-1 py-2.5 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm transition-colors"
              >
                Back
              </button>
              <button
                onClick={handleExecute}
                disabled={isExecuting}
                className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 ${
                  isBuy
                    ? 'bg-green-600 hover:bg-green-500 text-white'
                    : 'bg-red-600 hover:bg-red-500 text-white'
                }`}
              >
                {isExecuting ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Executing...
                  </>
                ) : (
                  <>
                    <CheckCircle className="w-4 h-4" />
                    Confirm {isBuy ? 'Buy' : 'Sell'}
                  </>
                )}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default SignalExecutionPanel;
