"use client"
import React, { useState, useEffect } from 'react'

interface TradeModalProps {
  isOpen: boolean
  onClose: () => void
  tradeData: {
    symbol: string
    timeframe: string
    entry: string
    tp: string
    sl: string
  } | null
  onExecute: (data: any) => void
}

interface FormData {
  entry: string
  tp1: string
  tp2: string
  sl: string
  positionValue: string
  leverage: number
  tradingCoin: string
  tp1Percentage: number
  tp2Percentage: number
}

const supportedCoins = [
  { symbol: 'SOL', name: 'Solana', icon: '◎', price: 159.5 },
  { symbol: 'USDC', name: 'USD Coin', icon: '$', price: 1.0 }
]

export default function TradeModal({ isOpen, onClose, tradeData, onExecute }: TradeModalProps) {
  console.log('🚀 TradeModal loaded with enhanced features - Version 2.0')
  const [loading, setLoading] = useState(false)
  const [walletBalance, setWalletBalance] = useState<any>(null)
  const [formData, setFormData] = useState<FormData>({
    entry: tradeData?.entry || '',
    tp1: tradeData?.tp || '',
    tp2: '',
    sl: tradeData?.sl || '',
    positionValue: '1000', // Position size in chosen coin
    leverage: 3,
    tradingCoin: 'SOL',
    tp1Percentage: 50, // % of position to close at TP1
    tp2Percentage: 50  // % of position to close at TP2
  })

  // Fetch wallet balance when modal opens
  useEffect(() => {
    if (isOpen) {
      fetchWalletBalance()
    }
  }, [isOpen])

  const fetchWalletBalance = async () => {
    try {
      const response = await fetch('/api/wallet/balance')
      const data = await response.json()
      if (data.success) {
        setWalletBalance(data.balance)
      }
    } catch (error) {
      console.error('Failed to fetch wallet balance:', error)
    }
  }

  // Helper function to safely format numbers
  const formatNumber = (value: number, decimals: number = 2): string => {
    if (isNaN(value) || !isFinite(value)) return '0.00'
    return value.toFixed(decimals)
  }

  // Calculate derived values with proper error handling
  const currentCoin = supportedCoins.find(coin => coin.symbol === formData.tradingCoin)
  const coinPrice = currentCoin?.price || 159.5 // Default to SOL price
  
  // Safe number parsing - position size in chosen coin
  const positionSize = parseFloat(formData.positionValue) || 0
  const positionValueUSD = positionSize * coinPrice
  const leverageNum = formData.leverage || 1
  const entryPrice = parseFloat(formData.entry) || 0
  const tp1Price = parseFloat(formData.tp1) || 0
  const tp2Price = parseFloat(formData.tp2) || 0
  const slPrice = parseFloat(formData.sl) || 0
  
  // Calculations with fallbacks
  const leveragedValue = positionValueUSD * leverageNum
  
  // P&L calculations with proper validation
  const profitTP1 = (entryPrice > 0 && tp1Price > 0 && leveragedValue > 0) ? 
    ((tp1Price - entryPrice) / entryPrice) * leveragedValue * (formData.tp1Percentage / 100) : 0
  const profitTP2 = (entryPrice > 0 && tp2Price > 0 && leveragedValue > 0) ? 
    ((tp2Price - entryPrice) / entryPrice) * leveragedValue * (formData.tp2Percentage / 100) : 0
  const lossAtSL = (entryPrice > 0 && slPrice > 0 && leveragedValue > 0) ? 
    ((slPrice - entryPrice) / entryPrice) * leveragedValue : 0

  useEffect(() => {
    if (tradeData) {
      setFormData((prev: FormData) => ({
        ...prev,
        entry: tradeData.entry || '',
        tp1: tradeData.tp || '',
        sl: tradeData.sl || ''
      }))
    }
  }, [tradeData])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    
    try {
      await onExecute({
        symbol: tradeData?.symbol,
        timeframe: tradeData?.timeframe,
        ...formData,
        positionSize,
        leveragedValue
      })
    } catch (error) {
      console.error('Trade execution failed:', error)
    } finally {
      setLoading(false)
    }
  }

  if (!isOpen || !tradeData) return null

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50">
      <div className="bg-gray-900 border border-gray-700 rounded-xl p-6 max-w-lg w-full max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-xl font-bold text-white flex items-center">
            <span className="w-8 h-8 bg-gradient-to-br from-green-400 to-green-600 rounded-lg flex items-center justify-center mr-3">
              💰
            </span>
            Execute Trade
          </h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-white transition-colors"
          >
            ✕
          </button>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Trade Details Section */}
          <div className="bg-gray-800/50 rounded-lg p-4 border border-gray-700">
            <h4 className="text-sm font-medium text-gray-300 mb-3 flex items-center">
              📊 Trade Setup
            </h4>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs text-gray-400 mb-1">Symbol</label>
                <div className="text-white font-medium">{tradeData?.symbol}</div>
              </div>
              <div>
                <label className="block text-xs text-gray-400 mb-1">Timeframe</label>
                <div className="text-white font-medium">{tradeData?.timeframe}</div>
              </div>
            </div>
          </div>

          {/* Trading Coin Selection - Enhanced Visual Cards */}
          <div>
            <label className="block text-xs text-gray-400 mb-2">Trading Coin</label>
            <div className="grid grid-cols-2 gap-3">
              {supportedCoins.map(coin => (
                <button
                  key={coin.symbol}
                  type="button"
                  onClick={() => setFormData(prev => ({...prev, tradingCoin: coin.symbol}))}
                  className={`p-3 rounded-lg border text-left transition-all ${
                    formData.tradingCoin === coin.symbol
                      ? 'border-blue-500 bg-blue-500/10'
                      : 'border-gray-600 bg-gray-800 hover:border-gray-500'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <span className="text-lg">{coin.icon}</span>
                      <span className={`font-medium ${
                        formData.tradingCoin === coin.symbol ? 'text-blue-400' : 'text-white'
                      }`}>
                        {coin.symbol}
                      </span>
                    </div>
                    <div className="text-right">
                      <div className={`text-sm ${
                        formData.tradingCoin === coin.symbol ? 'text-blue-400' : 'text-gray-300'
                      }`}>
                        ${coin.price}
                      </div>
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Enhanced Position Size Section */}
          <div className="bg-gray-800/50 rounded-lg p-4 border border-gray-700">
            <h4 className="text-sm font-medium text-gray-300 mb-3 flex items-center">
              💵 Position Size ({formData.tradingCoin})
            </h4>
            
            {/* Position Size Input */}
            <div className="mb-3">
              <label className="block text-xs text-gray-400 mb-1">Position Size ({formData.tradingCoin})</label>
              <input
                type="number"
                step="0.001"
                value={formData.positionValue}
                onChange={(e) => setFormData(prev => ({...prev, positionValue: e.target.value}))}
                className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white focus:border-blue-500 focus:outline-none"
                placeholder="1,000"
              />
              <div className="text-xs text-gray-400 mt-1">
                ≈ ${formatNumber(positionValueUSD)} USD
              </div>
            </div>

            {/* Percentage Buttons */}
            <div className="grid grid-cols-4 gap-2 mb-3">
              {[25, 50, 75, 100].map(percentage => (
                <button
                  key={percentage}
                  type="button"
                  onClick={() => {
                    if (walletBalance?.sol && formData.tradingCoin === 'SOL') {
                      const coinAmount = (walletBalance.sol * percentage) / 100
                      setFormData(prev => ({...prev, positionValue: coinAmount.toFixed(3)}))
                    }
                  }}
                  className="py-2 px-3 text-sm bg-gray-600 hover:bg-gray-500 text-white rounded transition-colors"
                >
                  {percentage}%
                </button>
              ))}
            </div>

            {/* Leverage Section */}
            <div className="mb-4">
              <label className="block text-xs text-gray-400 mb-2">Leverage: {formData.leverage}x</label>
              <div className="relative">
                <input
                  type="range"
                  min="1"
                  max="10"
                  step="1"
                  value={formData.leverage}
                  onChange={(e) => setFormData(prev => ({...prev, leverage: parseInt(e.target.value)}))}
                  className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer slider"
                />
                <div className="flex justify-between text-xs text-gray-500 mt-1">
                  <span>1x</span>
                  <span>5x</span>
                  <span>10x</span>
                </div>
              </div>
              <div className="text-xs text-gray-400 mt-2">
                Leveraged Value: ${formatNumber(leveragedValue)}
              </div>
            </div>
          </div>

          {/* Enhanced Price Levels */}
          <div>
            <label className="block text-xs text-gray-400 mb-2">Entry Price</label>
            <input
              type="number"
              step="0.01"
              value={formData.entry}
              onChange={(e) => setFormData(prev => ({...prev, entry: e.target.value}))}
              className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white text-sm focus:border-blue-500 focus:outline-none mb-4"
              placeholder="159.5"
            />
          </div>

          {/* Take Profit 1 with Profit Display */}
          <div className="mb-4">
            <label className="block text-xs text-gray-400 mb-1">Take Profit 1 (50% of position)</label>
            <input
              type="number"
              step="0.01"
              value={formData.tp1}
              onChange={(e) => setFormData(prev => ({...prev, tp1: e.target.value}))}
              className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white text-sm focus:border-green-500 focus:outline-none"
              placeholder="160.5"
            />
            
            {/* Profit Percentage Slider for TP1 */}
            <div className="mt-2">
              <div className="flex justify-between items-center mb-1">
                <span className="text-xs text-gray-400">Profit %</span>
                <span className="text-xs text-green-400 font-medium">
                  Profit: $1.50
                </span>
              </div>
              <div className="relative">
                <input
                  type="range"
                  min="10"
                  max="90"
                  step="10"
                  value={formData.tp1Percentage}
                  onChange={(e) => setFormData(prev => ({...prev, tp1Percentage: parseInt(e.target.value)}))}
                  className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer"
                  style={{
                    background: `linear-gradient(to right, #10b981 0%, #10b981 ${formData.tp1Percentage}%, #374151 ${formData.tp1Percentage}%, #374151 100%)`
                  }}
                />
                <div className="flex justify-between text-xs text-gray-500 mt-1">
                  <span>10%</span>
                  <span>90%</span>
                </div>
              </div>
            </div>
          </div>

          {/* Take Profit 2 */}
          <div className="mb-4">
            <label className="block text-xs text-gray-400 mb-1">Take Profit 2 (50% of position)</label>
            <input
              type="number"
              step="0.01"
              value={formData.tp2}
              onChange={(e) => setFormData(prev => ({...prev, tp2: e.target.value}))}
              className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white text-sm focus:border-green-500 focus:outline-none"
              placeholder="162"
            />
          </div>

          {/* Stop Loss */}
          <div className="mb-4">
            <label className="block text-xs text-gray-400 mb-1">Stop Loss</label>
            <input
              type="number"
              step="0.01"
              value={formData.sl}
              onChange={(e) => setFormData(prev => ({...prev, sl: e.target.value}))}
              className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white text-sm focus:border-red-500 focus:outline-none"
              placeholder="158.5"
            />
          </div>

          {/* Submit Buttons */}
          <div className="flex space-x-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 py-2 px-4 bg-gray-700 text-gray-300 rounded-lg hover:bg-gray-600 transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading}
              className={`flex-1 py-2 px-4 rounded-lg font-medium transition-all ${
                loading
                  ? 'bg-gray-700 text-gray-400 cursor-not-allowed'
                  : 'bg-gradient-to-r from-green-500 to-green-600 text-white hover:from-green-600 hover:to-green-700 transform hover:scale-[1.02]'
              }`}
            >
              {loading ? (
                <div className="flex items-center justify-center space-x-2">
                  <div className="w-4 h-4 border-2 border-gray-400 border-t-transparent rounded-full animate-spin"></div>
                  <span>Executing...</span>
                </div>
              ) : (
                'Execute Trade'
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
