/**
 * PositionModifierDialog Component
 * Modal for modifying SL/TP on open positions with preview
 */

import React, { useState, useEffect, useMemo } from 'react';
import {
  X,
  TrendingUp,
  TrendingDown,
  Target,
  Shield,
  Calculator,
  Loader2,
  AlertCircle,
  Check,
  RefreshCw,
} from 'lucide-react';
import { modifyMT4Position } from '../../../services/trading.service';
import { MT4Position } from '../hooks/useMT4WebSocket';

interface PositionModifierDialogProps {
  position: MT4Position;
  onClose: () => void;
  onSuccess?: (ticket: number) => void;
}

type InputMode = 'price' | 'pips' | 'percent';

const PositionModifierDialog: React.FC<PositionModifierDialogProps> = ({
  position,
  onClose,
  onSuccess,
}) => {
  const [slPrice, setSlPrice] = useState<string>(position.stopLoss?.toString() || '');
  const [tpPrice, setTpPrice] = useState<string>(position.takeProfit?.toString() || '');
  const [inputMode, setInputMode] = useState<InputMode>('price');
  const [slPips, setSlPips] = useState<string>('');
  const [tpPips, setTpPips] = useState<string>('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const isBuy = position.type === 'BUY';
  const pipValue = position.symbol.includes('JPY') ? 0.01 : 0.0001;

  // Calculate SL/TP from pips
  useEffect(() => {
    if (inputMode === 'pips') {
      if (slPips) {
        const pips = parseFloat(slPips);
        const price = isBuy
          ? position.currentPrice - pips * pipValue
          : position.currentPrice + pips * pipValue;
        setSlPrice(price.toFixed(5));
      }
      if (tpPips) {
        const pips = parseFloat(tpPips);
        const price = isBuy
          ? position.currentPrice + pips * pipValue
          : position.currentPrice - pips * pipValue;
        setTpPrice(price.toFixed(5));
      }
    }
  }, [slPips, tpPips, inputMode, position.currentPrice, isBuy, pipValue]);

  // Calculate potential loss/profit
  const calculations = useMemo(() => {
    const sl = parseFloat(slPrice) || 0;
    const tp = parseFloat(tpPrice) || 0;
    const current = position.currentPrice;
    const entry = position.openPrice;

    // Pips calculation
    const slPipsValue = sl ? Math.abs(current - sl) / pipValue : 0;
    const tpPipsValue = tp ? Math.abs(tp - current) / pipValue : 0;

    // Approximate P&L (simplified - assumes $10/pip per lot for majors)
    const pipValueUsd = 10 * position.lots;
    const maxLoss = sl ? slPipsValue * pipValueUsd : null;
    const maxProfit = tp ? tpPipsValue * pipValueUsd : null;

    // Risk/Reward ratio
    const riskReward = maxLoss && maxProfit ? maxProfit / maxLoss : null;

    // Breakeven price
    const breakeven = entry;

    return {
      slPips: slPipsValue,
      tpPips: tpPipsValue,
      maxLoss,
      maxProfit,
      riskReward,
      breakeven,
    };
  }, [slPrice, tpPrice, position, pipValue]);

  const handleSetBreakeven = () => {
    setSlPrice(position.openPrice.toFixed(5));
    setInputMode('price');
  };

  const handleSetTrailingPreset = (pips: number) => {
    const price = isBuy
      ? position.currentPrice - pips * pipValue
      : position.currentPrice + pips * pipValue;
    setSlPrice(price.toFixed(5));
    setInputMode('price');
  };

  const handleSubmit = async () => {
    setIsSubmitting(true);
    setError(null);

    try {
      await modifyMT4Position(
        position.ticket,
        slPrice ? parseFloat(slPrice) : undefined,
        tpPrice ? parseFloat(tpPrice) : undefined
      );

      setSuccess(true);
      onSuccess?.(position.ticket);

      // Close after brief success display
      setTimeout(() => onClose(), 1500);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to modify position');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleRemoveSL = () => setSlPrice('');
  const handleRemoveTP = () => setTpPrice('');

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70">
      <div className="w-full max-w-md bg-gray-800 rounded-xl shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-700">
          <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>
              <h2 className="font-semibold text-white">Modify Position</h2>
              <p className="text-sm text-gray-400">
                {position.symbol} • #{position.ticket}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {/* Position Info */}
          <div className="grid grid-cols-3 gap-3 p-3 bg-gray-900/50 rounded-lg">
            <div className="text-center">
              <div className="text-xs text-gray-500">Entry</div>
              <div className="font-mono text-white">{position.openPrice.toFixed(5)}</div>
            </div>
            <div className="text-center">
              <div className="text-xs text-gray-500">Current</div>
              <div className="font-mono text-white">{position.currentPrice.toFixed(5)}</div>
            </div>
            <div className="text-center">
              <div className="text-xs text-gray-500">P&L</div>
              <div className={`font-mono ${position.profit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                {position.profit >= 0 ? '+' : ''}{position.profit.toFixed(2)}
              </div>
            </div>
          </div>

          {/* Input Mode Toggle */}
          <div className="flex items-center gap-2">
            <span className="text-xs text-gray-500">Input:</span>
            {(['price', 'pips'] as InputMode[]).map((mode) => (
              <button
                key={mode}
                onClick={() => setInputMode(mode)}
                className={`px-3 py-1 text-xs rounded ${
                  inputMode === mode
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                }`}
              >
                {mode.charAt(0).toUpperCase() + mode.slice(1)}
              </button>
            ))}
          </div>

          {/* Stop Loss */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <Shield className="w-4 h-4 text-red-400" />
                Stop Loss
              </label>
              {slPrice && (
                <button
                  onClick={handleRemoveSL}
                  className="text-xs text-red-400 hover:text-red-300"
                >
                  Remove
                </button>
              )}
            </div>
            {inputMode === 'price' ? (
              <input
                type="number"
                value={slPrice}
                onChange={(e) => setSlPrice(e.target.value)}
                step="0.00001"
                placeholder="Stop Loss Price"
                className="w-full px-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white font-mono focus:outline-none focus:border-red-500"
              />
            ) : (
              <input
                type="number"
                value={slPips}
                onChange={(e) => setSlPips(e.target.value)}
                placeholder="Pips from current price"
                className="w-full px-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-red-500"
              />
            )}
            {slPrice && (
              <div className="mt-1 text-xs text-gray-500">
                {calculations.slPips.toFixed(1)} pips • Max loss: ${calculations.maxLoss?.toFixed(2) || '—'}
              </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-300">
                <Target className="w-4 h-4 text-green-400" />
                Take Profit
              </label>
              {tpPrice && (
                <button
                  onClick={handleRemoveTP}
                  className="text-xs text-green-400 hover:text-green-300"
                >
                  Remove
                </button>
              )}
            </div>
            {inputMode === 'price' ? (
              <input
                type="number"
                value={tpPrice}
                onChange={(e) => setTpPrice(e.target.value)}
                step="0.00001"
                placeholder="Take Profit Price"
                className="w-full px-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white font-mono focus:outline-none focus:border-green-500"
              />
            ) : (
              <input
                type="number"
                value={tpPips}
                onChange={(e) => setTpPips(e.target.value)}
                placeholder="Pips from current price"
                className="w-full px-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-green-500"
              />
            )}
            {tpPrice && (
              <div className="mt-1 text-xs text-gray-500">
                {calculations.tpPips.toFixed(1)} pips • Max profit: ${calculations.maxProfit?.toFixed(2) || '—'}
              </div>
            )}
          </div>

          {/* Quick Actions */}
          <div className="flex flex-wrap gap-2">
            <button
              onClick={handleSetBreakeven}
              className="flex items-center gap-1 px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded text-xs"
            >
              <RefreshCw className="w-3 h-3" />
              Breakeven
            </button>
            <button
              onClick={() => handleSetTrailingPreset(20)}
              className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded text-xs"
            >
              SL -20 pips
            </button>
            <button
              onClick={() => handleSetTrailingPreset(50)}
              className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded text-xs"
            >
              SL -50 pips
            </button>
          </div>

          {/* Risk/Reward Preview */}
          {calculations.riskReward && (
            <div className="flex items-center justify-between p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg">
              <div className="flex items-center gap-2">
                <Calculator className="w-4 h-4 text-blue-400" />
                <span className="text-sm text-blue-400">Risk/Reward</span>
              </div>
              <span className="text-white font-bold">1:{calculations.riskReward.toFixed(2)}</span>
            </div>
          )}

          {/* Error Message */}
          {error && (
            <div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
              <AlertCircle className="w-5 h-5 text-red-400" />
              <span className="text-sm text-red-400">{error}</span>
            </div>
          )}

          {/* Success Message */}
          {success && (
            <div className="flex items-center gap-2 p-3 bg-green-500/10 border border-green-500/30 rounded-lg">
              <Check className="w-5 h-5 text-green-400" />
              <span className="text-sm text-green-400">Position modified successfully</span>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center gap-3 p-4 border-t border-gray-700">
          <button
            onClick={onClose}
            disabled={isSubmitting}
            className="flex-1 py-2.5 bg-gray-700 hover:bg-gray-600 text-white rounded-lg font-medium disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={isSubmitting || (!slPrice && !tpPrice)}
            className="flex-1 flex items-center justify-center gap-2 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium disabled:opacity-50"
          >
            {isSubmitting ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Modifying...
              </>
            ) : (
              'Apply Changes'
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

export default PositionModifierDialog;
