'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: 3,
    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-3xl font-bold text-white">🚀 DRIFT LEVERAGE AUTOMATION</h1>
          <p className="text-gray-400 mt-2">AI-powered automated trading with Drift Protocol leverage</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 Integration Banner */}
          <div className="bg-gradient-to-r from-green-600 to-blue-600 p-6 rounded-lg border border-green-500">
            <div className="text-center">
              <h2 className="text-2xl font-bold text-white mb-2">⚡ DRIFT PROTOCOL INTEGRATED</h2>
              <p className="text-white">Leverage trading up to 10x • Advanced risk management • Live trading ready</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-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 (Simulation)</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 DRIFT LEVERAGE TRADING</span>
                  </label>
                </div>
              </div>

              {/* DEX Provider */}
              <div className="space-y-3">
                <label className="block text-sm font-bold text-purple-400">🏦 DEX Provider</label>
                <div className="space-y-2">
                  <label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-green-500 bg-green-900/20 transition-colors">
                    <input
                      type="radio"
                      name="dex"
                      value="DRIFT"
                      checked={config.dexProvider === 'DRIFT'}
                      onChange={(e) => setConfig({...config, dexProvider: e.target.value})}
                      className="w-4 h-4 text-green-600"
                      disabled={status?.isActive}
                    />
                    <div>
                      <span className="text-white font-bold">⚡ Drift Protocol</span>
                      <p className="text-green-400 text-xs">✅ LEVERAGE TRADING • Up to 10x</p>
                    </div>
                  </label>
                  <label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-gray-600 hover:border-yellow-500 transition-colors">
                    <input
                      type="radio"
                      name="dex"
                      value="JUPITER"
                      checked={config.dexProvider === 'JUPITER'}
                      onChange={(e) => setConfig({...config, dexProvider: e.target.value})}
                      className="w-4 h-4 text-yellow-600"
                      disabled={status?.isActive}
                    />
                    <div>
                      <span className="text-white">🔄 Jupiter DEX</span>
                      <p className="text-yellow-400 text-xs">⚠️ Spot Trading Only • No leverage</p>
                    </div>
                  </label>
                </div>
              </div>

            </div>

            {/* Advanced Configuration */}
            <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>
                  {config.dexProvider === 'DRIFT' && (
                    <>
                      <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">Trading Amount ($)</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">
                  Max Leverage {config.dexProvider === 'DRIFT' && <span className="text-green-400">(Drift: up to 10x)</span>}
                </label>
                <select
                  value={config.maxLeverage}
                  onChange={(e) => setConfig({...config, maxLeverage: 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}
                >
                  <option value="1">1x (Spot)</option>
                  <option value="2">2x</option>
                  <option value="3">3x</option>
                  <option value="5">5x</option>
                  {config.dexProvider === 'DRIFT' && (
                    <>
                      <option value="10">10x (Drift Only)</option>
                    </>
                  )}
                </select>
              </div>

            </div>

            <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="1"
                  max="10"
                  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="2"
                  max="20"
                  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="20"
                />
              </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">DEX:</span>
                  <span className={`font-semibold ${
                    config.dexProvider === 'DRIFT' ? 'text-green-400' : 'text-yellow-400'
                  }`}>
                    {config.dexProvider}
                  </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">Amount:</span>
                  <span className="text-white font-semibold">${config.tradingAmount}</span>
                </div>
              </div>
            ) : (
              <p className="text-gray-400">Loading status...</p>
            )}
          </div>

          {/* Quick 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</div>
              </div>
            </div>
          </div>

          {/* Drift Benefits */}
          {config.dexProvider === 'DRIFT' && (
            <div className="bg-gradient-to-br from-green-900/50 to-blue-900/50 p-6 rounded-lg border border-green-500/50">
              <h3 className="text-lg font-bold text-green-400 mb-3">⚡ Drift Benefits</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">Leverage up to 10x</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">Perpetual futures</span>
                </li>
                <li className="flex items-center space-x-2">
                  <span className="text-green-400">✅</span>
                  <span className="text-white">Low fees</span>
                </li>
              </ul>
            </div>
          )}

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