/**
 * PositionsList Component
 * Displays list of open paper trading positions
 */

import { useState } from 'react';

interface Position {
  id: string;
  symbol: string;
  direction: 'long' | 'short';
  lotSize: number;
  entryPrice: number;
  currentPrice?: number;
  stopLoss?: number;
  takeProfit?: number;
  unrealizedPnl?: number;
  unrealizedPnlPercent?: number;
  openedAt: Date;
}

interface PositionsListProps {
  positions: Position[];
  isLoading: boolean;
  onClosePosition: (positionId: string) => Promise<void>;
}

export default function PositionsList({
  positions,
  isLoading,
  onClosePosition,
}: PositionsListProps) {
  const [closingPositionId, setClosingPositionId] = useState<string | null>(null);

  const handleClosePosition = async (positionId: string) => {
    if (!confirm('Are you sure you want to close this position?')) {
      return;
    }

    setClosingPositionId(positionId);
    try {
      await onClosePosition(positionId);
    } catch (error) {
      console.error('Failed to close position:', error);
    } finally {
      setClosingPositionId(null);
    }
  };

  if (isLoading) {
    return (
      <div className="p-4 text-center">
        <div className="inline-block animate-spin rounded-full h-6 w-6 border-2 border-gray-600 border-t-blue-500"></div>
        <p className="text-sm text-gray-400 mt-2">Loading positions...</p>
      </div>
    );
  }

  if (positions.length === 0) {
    return (
      <div className="p-4 text-center">
        <p className="text-sm text-gray-400">No open positions</p>
      </div>
    );
  }

  return (
    <div className="divide-y divide-gray-700">
      {positions.map((position) => {
        const isProfitable = (position.unrealizedPnl || 0) >= 0;
        const isClosing = closingPositionId === position.id;

        return (
          <div key={position.id} className="p-3 hover:bg-gray-800/50 transition-colors">
            {/* Header: Symbol and Direction */}
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                <span className="text-white font-medium">{position.symbol}</span>
                <span
                  className={`text-xs px-2 py-0.5 rounded ${
                    position.direction === 'long'
                      ? 'bg-green-900/30 text-green-400'
                      : 'bg-red-900/30 text-red-400'
                  }`}
                >
                  {position.direction.toUpperCase()}
                </span>
              </div>
              <button
                onClick={() => handleClosePosition(position.id)}
                disabled={isClosing}
                className="text-xs px-2 py-1 bg-gray-700 hover:bg-gray-600 text-white rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isClosing ? 'Closing...' : 'Close'}
              </button>
            </div>

            {/* Position Details */}
            <div className="grid grid-cols-2 gap-2 text-xs">
              {/* Entry Price */}
              <div>
                <span className="text-gray-500">Entry:</span>
                <span className="ml-1 text-gray-300 font-mono">
                  ${position.entryPrice.toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 8,
                  })}
                </span>
              </div>

              {/* Current Price */}
              <div>
                <span className="text-gray-500">Current:</span>
                <span className="ml-1 text-gray-300 font-mono">
                  ${(position.currentPrice || position.entryPrice).toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 8,
                  })}
                </span>
              </div>

              {/* Quantity */}
              <div>
                <span className="text-gray-500">Quantity:</span>
                <span className="ml-1 text-gray-300 font-mono">{position.lotSize}</span>
              </div>

              {/* P&L */}
              <div>
                <span className="text-gray-500">P&L:</span>
                <span className={`ml-1 font-mono font-medium ${isProfitable ? 'text-green-400' : 'text-red-400'}`}>
                  {isProfitable ? '+' : ''}${(position.unrealizedPnl || 0).toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  })}
                  <span className="ml-0.5">
                    ({isProfitable ? '+' : ''}{(position.unrealizedPnlPercent || 0).toFixed(2)}%)
                  </span>
                </span>
              </div>

              {/* Stop Loss */}
              {position.stopLoss && (
                <div>
                  <span className="text-gray-500">SL:</span>
                  <span className="ml-1 text-red-400 font-mono">
                    ${position.stopLoss.toLocaleString(undefined, {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 8,
                    })}
                  </span>
                </div>
              )}

              {/* Take Profit */}
              {position.takeProfit && (
                <div>
                  <span className="text-gray-500">TP:</span>
                  <span className="ml-1 text-green-400 font-mono">
                    ${position.takeProfit.toLocaleString(undefined, {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 8,
                    })}
                  </span>
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}
