'use client'

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

interface ApiStatus {
  status: string
  service: string
  health: string
}

interface Balance {
  totalBalance: number
  availableBalance: number
  positions: Array<{
    symbol: string
    amount: number
    value: number
    price: number
  }>
}

interface PriceData {
  prices: Array<{
    symbol: string
    price: number
    change24h: number
    volume24h: number
  }>
}

export default function HomePage() {
  const [apiStatus, setApiStatus] = useState<ApiStatus | null>(null)
  const [balance, setBalance] = useState<Balance | null>(null)
  const [prices, setPrices] = useState<PriceData | null>(null)
  const [loading, setLoading] = useState(true)
  const [tradeAmount, setTradeAmount] = useState('1.0')
  const [selectedSymbol, setSelectedSymbol] = useState('SOL')

  // Fetch data on component mount
  useEffect(() => {
    fetchData()
  }, [])

  const fetchData = async () => {
    try {
      setLoading(true)
      
      // Fetch API status
      const statusRes = await fetch('/api/status')
      if (statusRes.ok) {
        const statusData = await statusRes.json()
        setApiStatus(statusData)
      }

      // Fetch balance
      const balanceRes = await fetch('/api/balance')
      if (balanceRes.ok) {
        const balanceData = await balanceRes.json()
        setBalance(balanceData)
      }

      // Fetch prices
      const pricesRes = await fetch('/api/prices')
      if (pricesRes.ok) {
        const pricesData = await pricesRes.json()
        setPrices(pricesData)
      }
    } catch (error) {
      console.error('Failed to fetch data:', error)
    } finally {
      setLoading(false)
    }
  }

  const executeTrade = async (side: 'buy' | 'sell') => {
    try {
      const response = await fetch('/api/trading', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          symbol: selectedSymbol,
          side,
          amount: tradeAmount,
          type: 'market'
        })
      })

      const result = await response.json()
      
      if (result.success) {
        alert(`Trade executed: ${result.message}`)
        fetchData() // Refresh data after trade
      } else {
        alert(`Trade failed: ${result.error}`)
      }
    } catch (error) {
      alert('Trade execution failed')
      console.error(error)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-900 text-white p-8 flex items-center justify-center">
        <div className="text-xl">Loading Bitquery Trading Dashboard...</div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-900 text-white p-8">
      <div className="max-w-6xl mx-auto">
        <h1 className="text-3xl font-bold mb-8">Bitquery Trading Dashboard</h1>
        
        {/* Status and Balance */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
          <div className="bg-gray-800 rounded-lg p-6">
            <h2 className="text-xl font-semibold mb-4">Account Status</h2>
            <div className="space-y-2">
              <div>✅ Bitquery API: {apiStatus?.status || 'Loading...'}</div>
              <div>💰 Portfolio Value: ${balance?.totalBalance?.toFixed(2) || '0.00'}</div>
              <div>📊 Available Balance: ${balance?.availableBalance?.toFixed(2) || '0.00'}</div>
            </div>
          </div>
          
          <div className="bg-gray-800 rounded-lg p-6">
            <h2 className="text-xl font-semibold mb-4">Quick Trade</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm text-gray-400 mb-1">Symbol</label>
                <select 
                  value={selectedSymbol}
                  onChange={(e) => setSelectedSymbol(e.target.value)}
                  className="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2"
                >
                  <option value="SOL">SOL</option>
                  <option value="ETH">ETH</option>
                  <option value="BTC">BTC</option>
                </select>
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Amount</label>
                <input 
                  type="number" 
                  value={tradeAmount}
                  onChange={(e) => setTradeAmount(e.target.value)}
                  className="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2" 
                  placeholder="1.0" 
                />
              </div>
              <div className="grid grid-cols-2 gap-2">
                <button 
                  onClick={() => executeTrade('buy')}
                  className="bg-green-600 hover:bg-green-700 px-4 py-2 rounded"
                >
                  BUY
                </button>
                <button 
                  onClick={() => executeTrade('sell')}
                  className="bg-red-600 hover:bg-red-700 px-4 py-2 rounded"
                >
                  SELL
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Token Prices */}
        <div className="bg-gray-800 rounded-lg p-6 mb-8">
          <h2 className="text-xl font-semibold mb-4">Live Prices (Bitquery)</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {prices?.prices?.map((token) => (
              <div key={token.symbol} className="bg-gray-700 rounded-lg p-4">
                <div className="flex justify-between items-center">
                  <span className="font-semibold">{token.symbol}</span>
                  <span className={`${token.change24h >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                    {token.change24h >= 0 ? '+' : ''}{token.change24h.toFixed(2)}%
                  </span>
                </div>
                <div className="text-2xl font-bold">${token.price.toFixed(2)}</div>
                <div className="text-sm text-gray-400">
                  Vol: ${(token.volume24h / 1000000).toFixed(1)}M
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Positions */}
        {balance?.positions && balance.positions.length > 0 && (
          <div className="bg-gray-800 rounded-lg p-6">
            <h2 className="text-xl font-semibold mb-4">Your Positions</h2>
            <div className="space-y-3">
              {balance.positions.map((position) => (
                <div key={position.symbol} className="flex justify-between items-center bg-gray-700 rounded p-3">
                  <div>
                    <span className="font-semibold">{position.symbol}</span>
                    <span className="text-gray-400 ml-2">{position.amount} tokens</span>
                  </div>
                  <div className="text-right">
                    <div className="font-semibold">${position.value.toFixed(2)}</div>
                    <div className="text-sm text-gray-400">${position.price.toFixed(2)} each</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
