/**
 * LivePositionCard Component
 * Displays a single live MT4 position with real-time P&L and actions
 */

import React, { useState } from 'react';
import {
  TrendingUp,
  TrendingDown,
  X,
  Edit3,
  Target,
  Shield,
  Clock,
  Loader2,
  ChevronDown,
  ChevronUp,
} from 'lucide-react';
import type { MT4Position } from '../../../services/trading.service';

interface LivePositionCardProps {
  position: MT4Position;
  currentPrice?: number;
  onClose?: (ticket: number) => Promise<void>;
  onModify?: (ticket: number, stopLoss?: number, takeProfit?: number) => Promise<void>;
  loading?: boolean;
}

const LivePositionCard: React.FC<LivePositionCardProps> = ({
  position,
  currentPrice,
  onClose,
  onModify,
  loading = false,
}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [isClosing, setIsClosing] = useState(false);
  const [isModifying, setIsModifying] = useState(false);
  const [modifyMode, setModifyMode] = useState(false);
  const [newStopLoss, setNewStopLoss] = useState<string>(position.stop_loss?.toString() || '');
  const [newTakeProfit, setNewTakeProfit] = useState<string>(position.take_profit?.toString() || '');

  const isBuy = position.type === 'buy';
  const isProfit = position.profit >= 0;
  const displayPrice = currentPrice || position.current_price;

  // Calculate pips
  const pipMultiplier = position.symbol.includes('JPY') ? 100 : 10000;
  const priceDiff = isBuy
    ? (displayPrice - position.open_price)
    : (position.open_price - displayPrice);
  const pips = priceDiff * pipMultiplier;

  const formatTime = (timeString: string) => {
    const date = new Date(timeString);
    return date.toLocaleString('es-ES', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const handleClose = async () => {
    if (!onClose) return;
    setIsClosing(true);
    try {
      await onClose(position.ticket);
    } finally {
      setIsClosing(false);
    }
  };

  const handleModify = async () => {
    if (!onModify) return;
    setIsModifying(true);
    try {
      const sl = newStopLoss ? parseFloat(newStopLoss) : undefined;
      const tp = newTakeProfit ? parseFloat(newTakeProfit) : undefined;
      await onModify(position.ticket, sl, tp);
      setModifyMode(false);
    } finally {
      setIsModifying(false);
    }
  };

  const calculateRiskReward = () => {
    if (!position.stop_loss || !position.take_profit) return null;
    const risk = Math.abs(position.open_price - position.stop_loss);
    const reward = Math.abs(position.take_profit - position.open_price);
    if (risk === 0) return null;
    return (reward / risk).toFixed(2);
  };

  const riskReward = calculateRiskReward();

  return (
    <div className={`bg-gray-800 rounded-xl border ${
      isProfit ? 'border-green-500/30' : 'border-red-500/30'
    } overflow-hidden transition-all`}>
      {/* Main Content */}
      <div className="p-4">
        {/* Header Row */}
        <div className="flex items-start justify-between mb-3">
          <div className="flex items-center gap-3">
            {/* Direction Badge */}
            <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>
              <div className="flex items-center gap-2">
                <span className="font-bold text-white">{position.symbol}</span>
                <span className={`px-2 py-0.5 text-xs rounded font-medium ${
                  isBuy ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'
                }`}>
                  {isBuy ? 'BUY' : 'SELL'}
                </span>
              </div>
              <p className="text-sm text-gray-400">
                {position.volume} lots • #{position.ticket}
              </p>
            </div>
          </div>

          {/* P&L */}
          <div className="text-right">
            <p className={`text-lg font-bold ${isProfit ? 'text-green-400' : 'text-red-400'}`}>
              {isProfit ? '+' : ''}{position.profit.toFixed(2)} USD
            </p>
            <p className={`text-sm ${isProfit ? 'text-green-400/70' : 'text-red-400/70'}`}>
              {pips >= 0 ? '+' : ''}{pips.toFixed(1)} pips
            </p>
          </div>
        </div>

        {/* Price Info */}
        <div className="grid grid-cols-3 gap-4 text-sm mb-3">
          <div>
            <p className="text-gray-500 text-xs mb-0.5">Entry</p>
            <p className="text-white font-mono">{position.open_price.toFixed(5)}</p>
          </div>
          <div>
            <p className="text-gray-500 text-xs mb-0.5">Current</p>
            <p className={`font-mono ${isProfit ? 'text-green-400' : 'text-red-400'}`}>
              {displayPrice.toFixed(5)}
            </p>
          </div>
          <div className="text-right">
            <p className="text-gray-500 text-xs mb-0.5">Open Time</p>
            <p className="text-gray-300 text-xs">{formatTime(position.open_time)}</p>
          </div>
        </div>

        {/* SL/TP Indicators */}
        <div className="flex items-center gap-4 text-sm">
          {position.stop_loss ? (
            <div className="flex items-center gap-1.5">
              <Shield className="w-4 h-4 text-red-400" />
              <span className="text-gray-400">SL:</span>
              <span className="text-red-400 font-mono">{position.stop_loss.toFixed(5)}</span>
            </div>
          ) : (
            <div className="flex items-center gap-1.5 text-gray-500">
              <Shield className="w-4 h-4" />
              <span>No SL</span>
            </div>
          )}
          {position.take_profit ? (
            <div className="flex items-center gap-1.5">
              <Target className="w-4 h-4 text-green-400" />
              <span className="text-gray-400">TP:</span>
              <span className="text-green-400 font-mono">{position.take_profit.toFixed(5)}</span>
            </div>
          ) : (
            <div className="flex items-center gap-1.5 text-gray-500">
              <Target className="w-4 h-4" />
              <span>No TP</span>
            </div>
          )}
          {riskReward && (
            <div className="ml-auto text-gray-400">
              R:R <span className="text-white font-medium">1:{riskReward}</span>
            </div>
          )}
        </div>

        {/* Expand/Collapse Button */}
        <button
          onClick={() => setIsExpanded(!isExpanded)}
          className="w-full mt-3 pt-3 border-t border-gray-700 flex items-center justify-center gap-1 text-sm text-gray-400 hover:text-white transition-colors"
        >
          {isExpanded ? (
            <>
              <ChevronUp className="w-4 h-4" />
              Less
            </>
          ) : (
            <>
              <ChevronDown className="w-4 h-4" />
              More
            </>
          )}
        </button>
      </div>

      {/* Expanded Content */}
      {isExpanded && (
        <div className="px-4 pb-4 space-y-4">
          {/* Comment */}
          {position.comment && (
            <div className="p-3 bg-gray-900/50 rounded-lg">
              <p className="text-xs text-gray-500 mb-1">Comment</p>
              <p className="text-sm text-gray-300">{position.comment}</p>
            </div>
          )}

          {/* Modify Mode */}
          {modifyMode ? (
            <div className="space-y-3">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Stop Loss</label>
                  <input
                    type="number"
                    step="0.00001"
                    value={newStopLoss}
                    onChange={(e) => setNewStopLoss(e.target.value)}
                    placeholder="0.00000"
                    className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-red-500"
                  />
                </div>
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Take Profit</label>
                  <input
                    type="number"
                    step="0.00001"
                    value={newTakeProfit}
                    onChange={(e) => setNewTakeProfit(e.target.value)}
                    placeholder="0.00000"
                    className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-green-500"
                  />
                </div>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setModifyMode(false)}
                  className="flex-1 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleModify}
                  disabled={isModifying}
                  className="flex-1 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {isModifying ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    'Save Changes'
                  )}
                </button>
              </div>
            </div>
          ) : (
            /* Action Buttons */
            <div className="flex items-center gap-2">
              {onModify && (
                <button
                  onClick={() => setModifyMode(true)}
                  disabled={loading}
                  className="flex-1 flex items-center justify-center gap-2 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm transition-colors disabled:opacity-50"
                >
                  <Edit3 className="w-4 h-4" />
                  Modify
                </button>
              )}
              {onClose && (
                <button
                  onClick={handleClose}
                  disabled={isClosing || loading}
                  className="flex-1 flex items-center justify-center gap-2 py-2 bg-red-600 hover:bg-red-500 text-white rounded-lg text-sm transition-colors disabled:opacity-50"
                >
                  {isClosing ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <>
                      <X className="w-4 h-4" />
                      Close Position
                    </>
                  )}
                </button>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default LivePositionCard;
