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

export default function AutomationPage() {
  const [config, setConfig] = useState({
    mode: 'SIMULATION',
    dexProvider: 'DRIFT',
    symbol: 'SOLUSD',
    timeframe: '1h',
    tradingAmount: 100,
    maxLeverage: 5,
    stopLossPercent: 2,
    takeProfitPercent: 6,
    riskPercentage: 2
  })

  const [status, setStatus] = useState(null)
  const [balance, setBalance] = useState(null)
  const [positions, setPositions] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const [balanceLoading, setBalanceLoading] = useState(false)

  useEffect(() => {
    fetchStatus()
    fetchBalance()
    fetchPositions()
    const interval = setInterval(() => {
      fetchStatus()
      fetchBalance()
      fetchPositions()
    }, 30000)
    return () => clearInterval(interval)
  }, [])

  const fetchStatus = async () => {
    try {
      const response = await fetch('/api/automation/status')
      const data = await response.json()
      if (data.success) {
        setStatus(data.status)
      }
    } catch (error) {
      console.error('Failed to fetch status:', error)
    }
  }

  const fetchBalance = async () => {
    if (config.dexProvider !== 'DRIFT') return
    
    setBalanceLoading(true)
    try {
      const response = await fetch('/api/drift/balance')
      const data = await response.json()
      if (data.success) {
        setBalance(data)
        // Auto-calculate position size based on available balance and leverage
        const maxPositionSize = (data.availableBalance * config.maxLeverage) * 0.9 // Use 90% of max
        const suggestedSize = Math.max(10, Math.min(maxPositionSize, config.tradingAmount))
        
        setConfig(prev => ({
          ...prev,
          tradingAmount: Math.round(suggestedSize)
        }))
      }
    } catch (error) {
      console.error('Failed to fetch balance:', error)
    } finally {
      setBalanceLoading(false)
    }
  }

  const fetchPositions = async () => {
    if (config.dexProvider !== 'DRIFT') return
    
    try {
      const response = await fetch('/api/drift/positions')
      const data = await response.json()
      if (data.success) {
        setPositions(data.positions || [])
      }
    } catch (error) {
      console.error('Failed to fetch positions:', error)
    }
  }

  const handleLeverageChange = (newLeverage) => {
    const leverage = parseFloat(newLeverage)
    
    // Auto-calculate position size when leverage changes
    if (balance?.availableBalance) {
      const maxPositionSize = (balance.availableBalance * leverage) * 0.9 // Use 90% of max
      const suggestedSize = Math.max(10, maxPositionSize)
      
      setConfig(prev => ({
        ...prev,
        maxLeverage: leverage,
        tradingAmount: Math.round(suggestedSize)
      }))
    } else {
      setConfig(prev => ({
        ...prev,
        maxLeverage: leverage
      }))
    }
  }

  const hasOpenPosition = positions.some(pos => 
    pos.symbol.includes(config.symbol.replace('USD', '')) && pos.size > 0.001
  )

  const handleStart = async () => {
    setIsLoading(true)
    try {
      const response = await fetch('/api/automation/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config)
      })
      const data = await response.json()
      if (data.success) {
        fetchStatus()
      } else {
        alert('Failed to start automation: ' + data.error)
      }
    } catch (error) {
      console.error('Failed to start automation:', error)
      alert('Failed to start automation')
    } finally {
      setIsLoading(false)
    }
  }

  const handleStop = async () => {
    setIsLoading(true)
    try {
      const response = await fetch('/api/automation/stop', { method: 'POST' })
      const data = await response.json()
      if (data.success) {
        fetchStatus()
      } else {
        alert('Failed to stop automation: ' + data.error)
      }
    } catch (error) {
      console.error('Failed to stop automation:', error)
      alert('Failed to stop automation')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white">Automated Trading</h1>
          <p className="text-gray-400 mt-1">Drift Protocol</p>
        </div>
        <div className="flex space-x-4">
          {status?.isActive ? (
            <button
              onClick={handleStop}
              disabled={isLoading}
              className="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 font-semibold"
            >
              {isLoading ? 'Stopping...' : 'STOP'}
            </button>
          ) : (
            <button
              onClick={handleStart}
              disabled={isLoading}
              className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 font-semibold"
            >
              {isLoading ? 'Starting...' : 'START'}
            </button>
          )}
        </div>
      </div>

      {/* Main Grid */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
        
        {/* Configuration */}
        <div className="xl:col-span-2 space-y-6">
          
          <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
            <h3 className="text-xl font-bold text-white mb-6">Configuration</h3>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              
              {/* Trading Mode */}
              <div className="space-y-3">
                <label className="block text-sm font-bold text-blue-400">Trading Mode</label>
                <div className="space-y-2">
                  <label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-gray-600 hover:border-blue-500 transition-colors">
                    <input
                      type="radio"
                      name="mode"
                      value="SIMULATION"
                      checked={config.mode === 'SIMULATION'}
                      onChange={(e) => setConfig({...config, mode: e.target.value})}
                      className="w-4 h-4 text-blue-600"
                      disabled={status?.isActive}
                    />
                    <span className="text-white">Paper Trading</span>
                  </label>
                  <label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-gray-600 hover:border-green-500 transition-colors">
                    <input
                      type="radio"
                      name="mode"
                      value="LIVE"
                      checked={config.mode === 'LIVE'}
                      onChange={(e) => setConfig({...config, mode: e.target.value})}
                      className="w-4 h-4 text-green-600"
                      disabled={status?.isActive}
                    />
                    <span className="text-white font-semibold">Live Trading</span>
                  </label>
                </div>
              </div>

              {/* Leverage */}
              <div className="space-y-3">
                <label className="block text-sm font-bold text-purple-400">
                  Leverage
                  {balance && (
                    <span className="ml-2 text-xs text-gray-400">
                      (Max position: ${(balance.availableBalance * config.maxLeverage * 0.9).toFixed(0)})
                    </span>
                  )}
                </label>
                <select
                  value={config.maxLeverage}
                  onChange={(e) => handleLeverageChange(e.target.value)}
                  className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-purple-400"
                  disabled={status?.isActive}
                >
                  <option value="1">1x - Spot</option>
                  <option value="2">2x</option>
                  <option value="3">3x</option>
                  <option value="5">5x</option>
                  <option value="10">10x</option>
                  <option value="20">20x</option>
                  <option value="50">50x</option>
                  <option value="100">100x</option>
                </select>
              </div>

            </div>

            {/* Parameters */}
            <div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
              
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Symbol</label>
                <select
                  value={config.symbol}
                  onChange={(e) => setConfig({...config, symbol: e.target.value})}
                  className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
                  disabled={status?.isActive}
                >
                  <option value="SOLUSD">SOL/USD</option>
                  <option value="BTCUSD">BTC/USD</option>
                  <option value="ETHUSD">ETH/USD</option>
                  <option value="APTUSD">APT/USD</option>
                  <option value="AVAXUSD">AVAX/USD</option>
                  <option value="DOGEUSD">DOGE/USD</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Position Size ($)
                  {balanceLoading && <span className="ml-2 text-xs text-blue-400">Syncing...</span>}
                  {balance && !balanceLoading && (
                    <span className="ml-2 text-xs text-green-400">Auto-calculated</span>
                  )}
                </label>
                <input
                  type="number"
                  value={config.tradingAmount}
                  onChange={(e) => setConfig({...config, tradingAmount: parseFloat(e.target.value)})}
                  className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
                  disabled={status?.isActive}
                  min="10"
                  step="10"
                />
                {balance && (
                  <div className="mt-1 text-xs text-gray-400">
                    Available: ${balance.availableBalance?.toFixed(2)} • 
                    Using {((config.tradingAmount / balance.availableBalance) * 100).toFixed(0)}% of balance
                  </div>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Timeframe</label>
                <select
                  value={config.timeframe}
                  onChange={(e) => setConfig({...config, timeframe: e.target.value})}
                  className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
                  disabled={status?.isActive}
                >
                  <option value="1m">1 Minute</option>
                  <option value="5m">5 Minutes</option>
                  <option value="15m">15 Minutes</option>
                  <option value="1h">1 Hour</option>
                  <option value="4h">4 Hours</option>
                  <option value="1d">1 Day</option>
                </select>
              </div>

            </div>

            {/* Risk Management */}
            <div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
              
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Stop Loss (%)</label>
                <input
                  type="number"
                  value={config.stopLossPercent}
                  onChange={(e) => setConfig({...config, stopLossPercent: parseFloat(e.target.value)})}
                  className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
                  disabled={status?.isActive}
                  min="0.5"
                  max="20"
                  step="0.5"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Take Profit (%)</label>
                <input
                  type="number"
                  value={config.takeProfitPercent}
                  onChange={(e) => setConfig({...config, takeProfitPercent: parseFloat(e.target.value)})}
                  className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
                  disabled={status?.isActive}
                  min="1"
                  max="50"
                  step="1"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Automation Mode
                  {hasOpenPosition && (
                    <span className="ml-2 text-xs text-yellow-400">Position Open</span>
                  )}
                </label>
                <div className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white">
                  <div className="flex items-center justify-between">
                    <span>AI-Driven Trading</span>
                    <div className="flex items-center space-x-2">
                      <div className={`w-2 h-2 rounded-full ${hasOpenPosition ? 'bg-yellow-400' : 'bg-green-400'}`}></div>
                      <span className="text-sm text-gray-300">
                        {hasOpenPosition ? 'Monitoring Position' : 'Ready to Trade'}
                      </span>
                    </div>
                  </div>
                  <div className="mt-2 text-xs text-gray-400">
                    Bot will enter trades based on AI analysis when no position is open
                  </div>
                </div>
              </div>

            </div>

          </div>
        </div>

        {/* Status */}
        <div className="space-y-6">
          
          <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-xl font-bold text-white">Account Status</h3>
              <button
                onClick={fetchBalance}
                disabled={balanceLoading}
                className="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors disabled:opacity-50 text-sm"
              >
                {balanceLoading ? 'Syncing...' : 'Sync'}
              </button>
            </div>
            
            {balance ? (
              <div className="space-y-3">
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">Available Balance:</span>
                  <span className="text-green-400 font-semibold">${balance.availableBalance?.toFixed(2)}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">Account Value:</span>
                  <span className="text-blue-400 font-semibold">${balance.accountValue?.toFixed(2)}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">Unrealized P&L:</span>
                  <span className={`font-semibold ${balance.unrealizedPnl >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                    {balance.unrealizedPnl >= 0 ? '+' : ''}${balance.unrealizedPnl?.toFixed(2)}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">Open Positions:</span>
                  <span className="text-yellow-400 font-semibold">{positions.length}</span>
                </div>
                {positions.length > 0 && (
                  <div className="mt-3 p-3 bg-gray-700 rounded-lg">
                    <div className="text-sm text-gray-300 mb-2">Active Positions:</div>
                    {positions.map((pos, idx) => (
                      <div key={idx} className="flex justify-between items-center text-xs">
                        <span className="text-gray-400">{pos.symbol}</span>
                        <span className={`font-semibold ${pos.side === 'long' ? 'text-green-400' : 'text-red-400'}`}>
                          {pos.side.toUpperCase()} {pos.size?.toFixed(4)}
                        </span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ) : (
              <div className="text-center py-4">
                {balanceLoading ? (
                  <div className="text-gray-400">Loading account data...</div>
                ) : (
                  <div className="text-gray-400">No account data available</div>
                )}
              </div>
            )}
          </div>

          <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
            <h3 className="text-xl font-bold text-white mb-4">Bot Status</h3>
            {status ? (
              <div className="space-y-3">
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">Status:</span>
                  <span className={`px-3 py-1 rounded-full text-sm font-bold ${
                    status.isActive ? 'bg-green-600 text-white' : 'bg-red-600 text-white'
                  }`}>
                    {status.isActive ? 'ACTIVE' : 'STOPPED'}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-300">Mode:</span>
                  <span className={`font-semibold ${
                    status.mode === 'LIVE' ? 'text-red-400' : 'text-blue-400'
                  }`}>
                    {status.mode}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-300">Protocol:</span>
                  <span className="font-semibold text-green-400">DRIFT</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-300">Symbol:</span>
                  <span className="text-white font-semibold">{config.symbol}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-300">Leverage:</span>
                  <span className="text-yellow-400 font-semibold">{config.maxLeverage}x</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-300">Position Size:</span>
                  <span className="text-white font-semibold">${config.tradingAmount}</span>
                </div>
              </div>
            ) : (
              <p className="text-gray-400">Loading...</p>
            )}
          </div>

          <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
            <h3 className="text-xl font-bold text-white mb-4">Trading Metrics</h3>
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-green-400">
                  {balance?.accountValue ? `$${balance.accountValue.toFixed(0)}` : '$0'}
                </div>
                <div className="text-xs text-gray-400">Portfolio</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-400">
                  {balance?.leverage ? `${(balance.leverage * 100).toFixed(1)}%` : '0%'}
                </div>
                <div className="text-xs text-gray-400">Leverage Used</div>
              </div>
              <div className="text-center">
                <div className={`text-2xl font-bold ${balance?.unrealizedPnl >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                  {balance?.unrealizedPnl ? `$${balance.unrealizedPnl.toFixed(2)}` : '$0.00'}
                </div>
                <div className="text-xs text-gray-400">Unrealized P&L</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-yellow-400">{positions.length}</div>
                <div className="text-xs text-gray-400">Open Positions</div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  )
}
