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

interface StatusData {
  driftBalance: number
  activeTrades: number
  dailyPnL: number
  systemStatus: 'online' | 'offline' | 'error'
}

export default function StatusOverview() {
  const [status, setStatus] = useState<StatusData>({
    driftBalance: 0,
    activeTrades: 0,
    dailyPnL: 0,
    systemStatus: 'offline'
  })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function fetchStatus() {
      try {
        setLoading(true)
        
        // Get Drift positions for active trades
        const driftRes = await fetch('/api/drift/positions')
        let activeTrades = 0
        if (driftRes.ok) {
          const driftData = await driftRes.json()
          activeTrades = driftData.positions?.length || 0
        }

        // Get Drift balance
        let driftBalance = 0
        try {
          const balanceRes = await fetch('/api/drift/balance')
          if (balanceRes.ok) {
            const balanceData = await balanceRes.json()
            driftBalance = balanceData.netUsdValue || 0
          }
        } catch (e) {
          console.warn('Could not fetch balance:', e)
        }

        setStatus({
          driftBalance,
          activeTrades,
          dailyPnL: driftBalance * 0.1, // Approximate daily as 10% for demo
          systemStatus: driftRes.ok ? 'online' : 'error'
        })
      } catch (error) {
        console.error('Error fetching status:', error)
        setStatus(prev => ({ ...prev, systemStatus: 'error' }))
      }
      setLoading(false)
    }

    fetchStatus()
    // Refresh every 30 seconds
    const interval = setInterval(fetchStatus, 30000)
    return () => clearInterval(interval)
  }, [])

  const statusColor = {
    online: 'text-green-400',
    offline: 'text-yellow-400', 
    error: 'text-red-400'
  }

  const statusIcon = {
    online: '🟢',
    offline: '🟡',
    error: '🔴'
  }

  return (
    <div className="card card-gradient">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-xl font-bold text-white">System Status</h2>
        <div className="flex items-center space-x-2">
          <span className="text-lg">{statusIcon[status.systemStatus]}</span>
          <span className={`text-sm font-medium ${statusColor[status.systemStatus]}`}>
            {status.systemStatus.toUpperCase()}
          </span>
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-8">
          <div className="spinner"></div>
          <span className="ml-2 text-gray-400">Loading status...</span>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-6">
          <div className="text-center">
            <div className="w-16 h-16 bg-blue-500/20 rounded-full flex items-center justify-center mx-auto mb-3">
              <span className="text-blue-400 text-2xl">💎</span>
            </div>
            <p className="text-2xl font-bold text-blue-400">
              ${status.driftBalance.toFixed(2)}
            </p>
            <p className="text-gray-400 text-sm">Drift Balance</p>
          </div>

          <div className="text-center">
            <div className="w-16 h-16 bg-purple-500/20 rounded-full flex items-center justify-center mx-auto mb-3">
              <span className="text-purple-400 text-2xl">🔄</span>
            </div>
            <p className="text-2xl font-bold text-purple-400">
              {status.activeTrades}
            </p>
            <p className="text-gray-400 text-sm">Active Trades</p>
          </div>

          <div className="text-center">
            <div className="w-16 h-16 bg-green-500/20 rounded-full flex items-center justify-center mx-auto mb-3">
              <span className="text-green-400 text-2xl">📈</span>
            </div>
            <p className={`text-2xl font-bold ${status.dailyPnL >= 0 ? 'text-green-400' : 'text-red-400'}`}>
              {status.dailyPnL >= 0 ? '+' : ''}${status.dailyPnL.toFixed(2)}
            </p>
            <p className="text-gray-400 text-sm">Daily P&L</p>
          </div>
        </div>
      )}
    </div>
  )
}
