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

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

  const [status, setStatus] = useState(null)
  const [isLoading, setIsLoading] = useState(false)
  const [recentTrades, setRecentTrades] = useState([])

  useEffect(() => {
    fetchStatus()
    const interval = setInterval(fetchStatus, 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 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-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-4xl font-bold text-white">⚡ DRIFT PROTOCOL TRADING</h1>
          <p className="text-gray-400 mt-2">AI-powered automated trading • Up to 100x leverage • Perpetual futures</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 AUTOMATION'}
            </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 AUTOMATION'}
            </button>
          )}
        </div>
      </div>

      {/* Main Grid */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-8">
        
        {/* Configuration Column */}
        <div className="xl:col-span-2 space-y-6">
          
          {/* Drift Protocol Banner */}
          <div className="bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 p-6 rounded-lg border border-blue-500">
            <div className="text-center">
              <h2 className="text-3xl font-bold text-white mb-2">⚡ DRIFT PROTOCOL ONLY</h2>
              <p className="text-white text-lg">🚀 Up to 100x Leverage • 💎 Perpetual Futures • 💰 Spot Trading (1x) • 🎯 Advanced Risk Management</p>
            </div>
          </div>

          {/* Configuration Panel */}
          <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
            <h3 className="text-xl font-bold text-white mb-6">Trading 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-4 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 (Simulation)</span>
                  </label>
                  <label className="flex items-center space-x-3 cursor-pointer p-4 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 DRIFT TRADING</span>
                  </label>
                </div>
              </div>

              {/* Leverage Settings */}
              <div className="space-y-3">
                <label className="block text-sm font-bold text-purple-400">⚡ Leverage (Drift Protocol)</label>
                <select
                  value={config.maxLeverage}
                  onChange={(e) => setConfig({...config, maxLeverage: parseFloat(e.target.value)})}
                  className="w-full p-4 bg-gray-700 border border-purple-500 rounded-lg text-white focus:border-purple-400 text-lg font-semibold"
                  disabled={status?.isActive}
                >
                  <option value="1">1x - Spot Trading</option>
                  <option value="2">2x - Conservative</option>
                  <option value="3">3x - Moderate</option>
                  <option value="5">5x - Aggressive</option>
                  <option value="10">10x - High Risk</option>
                  <option value="20">20x - Very High Risk</option>
                  <option value="50">50x - Extreme Risk</option>
                  <option value="100">100x - MAXIMUM LEVERAGE 🔥</option>
                </select>
                <p className="text-sm text-purple-400">
                  {config.maxLeverage === 1 && "✅ Spot trading - No liquidation risk"}
                  {config.maxLeverage <= 5 && config.maxLeverage > 1 && "🟢 Conservative leverage - Lower risk"}
                  {config.maxLeverage <= 10 && config.maxLeverage > 5 && "🟡 Moderate leverage - Balanced risk/reward"}
                  {config.maxLeverage <= 50 && config.maxLeverage > 10 && "🟠 High leverage - Significant risk"}
                  {config.maxLeverage > 50 && "🔴 EXTREME LEVERAGE - Maximum risk! Use with caution!"}
                </p>
              </div>

            </div>

            {/* Trading Parameters */}
            <div className="mt-8 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>
                  <option value="ADAUSD">ADA/USD</option>
                  <option value="MATICUSD">MATIC/USD</option>
                  <option value="LINKUSD">LINK/USD</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Position Size ($)</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"
                />
              </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="2h">2 Hours</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">Max Daily Trades</label>
                <input
                  type="number"
                  value={config.maxDailyTrades}
                  onChange={(e) => setConfig({...config, maxDailyTrades: parseInt(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="100"
                />
              </div>

            </div>

            {/* Leverage Warning */}
            {config.maxLeverage > 10 && (
              <div className="mt-6 p-4 bg-red-900/30 border border-red-500 rounded-lg">
                <div className="flex items-start space-x-3">
                  <span className="text-red-400 text-xl">⚠️</span>
                  <div>
                    <h4 className="text-red-400 font-bold">HIGH LEVERAGE WARNING</h4>
                    <p className="text-red-300 text-sm mt-1">
                      You selected {config.maxLeverage}x leverage. This multiplies both profits AND losses. 
                      A {(100/config.maxLeverage).toFixed(1)}% price move against your position will result in liquidation.
                      Only use high leverage if you understand the risks!
                    </p>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Status Column */}
        <div className="space-y-6">
          
          {/* Current Status */}
          <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
            <h3 className="text-xl font-bold text-white mb-4">📊 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={`font-bold ${
                    config.maxLeverage === 1 ? 'text-green-400' :
                    config.maxLeverage <= 5 ? 'text-yellow-400' :
                    config.maxLeverage <= 10 ? 'text-orange-400' : 'text-red-400'
                  }`}>
                    {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 status...</p>
            )}
          </div>

          {/* Performance Stats */}
          <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
            <h3 className="text-xl font-bold text-white mb-4">📈 Performance</h3>
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-green-400">0</div>
                <div className="text-xs text-gray-400">Total Trades</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-400">0%</div>
                <div className="text-xs text-gray-400">Win Rate</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-purple-400">$0.00</div>
                <div className="text-xs text-gray-400">Total P&L</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-yellow-400">0</div>
                <div className="text-xs text-gray-400">Active Positions</div>
              </div>
            </div>
          </div>

          {/* Drift Protocol Benefits */}
          <div className="bg-gradient-to-br from-purple-900/50 to-pink-900/50 p-6 rounded-lg border border-purple-500/50">
            <h3 className="text-lg font-bold text-purple-400 mb-3">⚡ Drift Protocol Features</h3>
            <ul className="space-y-2 text-sm">
              <li className="flex items-center space-x-2">
                <span className="text-green-400">✅</span>
                <span className="text-white">Up to 100x leverage</span>
              </li>
              <li className="flex items-center space-x-2">
                <span className="text-green-400">✅</span>
                <span className="text-white">Perpetual futures</span>
              </li>
              <li className="flex items-center space-x-2">
                <span className="text-green-400">✅</span>
                <span className="text-white">Spot trading (1x leverage)</span>
              </li>
              <li className="flex items-center space-x-2">
                <span className="text-green-400">✅</span>
                <span className="text-white">Advanced risk management</span>
              </li>
              <li className="flex items-center space-x-2">
                <span className="text-green-400">✅</span>
                <span className="text-white">Low fees & slippage</span>
              </li>
              <li className="flex items-center space-x-2">
                <span className="text-green-400">✅</span>
                <span className="text-white">Multiple trading pairs</span>
              </li>
            </ul>
          </div>

          {/* Risk Warning */}
          <div className="bg-gradient-to-br from-red-900/30 to-orange-900/30 p-4 rounded-lg border border-red-500/50">
            <h4 className="text-red-400 font-bold mb-2">⚠️ Risk Disclosure</h4>
            <p className="text-red-300 text-xs">
              High leverage trading carries substantial risk of loss. Never trade with money you cannot afford to lose. 
              Past performance does not guarantee future results.
            </p>
          </div>

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