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

export default function AutoTradingPanel() {
  const [status, setStatus] = useState<'idle'|'running'|'stopped'>('idle')
  const [message, setMessage] = useState<string>('')
  const [currentTime, setCurrentTime] = useState<string>('')

  // Set current time only on client to avoid hydration mismatch
  useEffect(() => {
    const updateTime = () => {
      setCurrentTime(new Date().toLocaleTimeString())
    }
    
    updateTime() // Set initial time
    const interval = setInterval(updateTime, 1000) // Update every second
    
    return () => clearInterval(interval)
  }, [])

  async function handleAction(action: 'start'|'stop') {
    setMessage('')
    setStatus('idle')
    const res = await fetch('/api/auto-trading', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action })
    })
    if (res.ok) {
      setStatus(action === 'start' ? 'running' : 'stopped')
      setMessage(`Auto-trading ${action}ed`)
    } else {
      setMessage('Error: ' + (await res.text()))
    }
  }

  const getStatusColor = () => {
    switch (status) {
      case 'running': return 'text-green-400'
      case 'stopped': return 'text-red-400'
      default: return 'text-gray-400'
    }
  }

  const getStatusIcon = () => {
    switch (status) {
      case 'running': return '🟢'
      case 'stopped': return '🔴'
      default: return '⚫'
    }
  }

  return (
    <div className="card card-gradient">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-lg font-bold text-white flex items-center">
          <span className="w-8 h-8 bg-gradient-to-br from-green-400 to-emerald-600 rounded-lg flex items-center justify-center mr-3">
            ⚡
          </span>
          Auto-Trading Control
        </h2>
        <div className={`flex items-center space-x-2 ${getStatusColor()}`}>
          <span>{getStatusIcon()}</span>
          <span className="text-sm font-medium capitalize">{status}</span>
        </div>
      </div>

      {/* Status Display */}
      <div className="mb-6 p-4 bg-gray-800/30 rounded-lg border border-gray-700">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-sm font-semibold text-gray-300 mb-1">Trading Status</h3>
            <p className={`text-lg font-bold ${getStatusColor()}`}>
              {status === 'running' ? 'ACTIVE' : status === 'stopped' ? 'STOPPED' : 'IDLE'}
            </p>
          </div>
          <div className="text-right">
            <div className="text-xs text-gray-400">Last Updated</div>
            <div className="text-sm text-gray-300">{currentTime || '--:--:--'}</div>
          </div>
        </div>
        
        {message && (
          <div className={`mt-3 p-3 rounded-lg text-sm ${
            message.includes('Error') 
              ? 'bg-red-500/10 border border-red-500/30 text-red-400'
              : 'bg-green-500/10 border border-green-500/30 text-green-400'
          }`}>
            {message}
          </div>
        )}
      </div>

      {/* Action Buttons */}
      <div className="grid grid-cols-2 gap-3">
        <button 
          className={`py-3 px-4 rounded-lg font-semibold transition-all duration-300 ${
            status === 'running' 
              ? 'bg-gray-700 text-gray-400 cursor-not-allowed'
              : 'btn-success transform hover:scale-105 active:scale-95'
          }`}
          onClick={() => handleAction('start')}
          disabled={status === 'running'}
        >
          <div className="flex items-center justify-center space-x-2">
            <span>▶️</span>
            <span>Start Trading</span>
          </div>
        </button>
        
        <button 
          className={`py-3 px-4 rounded-lg font-semibold transition-all duration-300 ${
            status !== 'running' 
              ? 'bg-gray-700 text-gray-400 cursor-not-allowed'
              : 'btn-danger transform hover:scale-105 active:scale-95'
          }`}
          onClick={() => handleAction('stop')}
          disabled={status !== 'running'}
        >
          <div className="flex items-center justify-center space-x-2">
            <span>⏹️</span>
            <span>Stop Trading</span>
          </div>
        </button>
      </div>

      {/* Trading Metrics (Mock Data) */}
      <div className="mt-6 grid grid-cols-2 gap-4">
        <div className="p-3 bg-gray-800/20 rounded-lg">
          <div className="text-xs text-gray-400">Today's Trades</div>
          <div className="text-lg font-bold text-white">12</div>
        </div>
        <div className="p-3 bg-gray-800/20 rounded-lg">
          <div className="text-xs text-gray-400">Success Rate</div>
          <div className="text-lg font-bold text-green-400">85%</div>
        </div>
      </div>
    </div>
  )
}
