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

interface Trade {
  id: string
  symbol: string
  side: string
  amount: number
  price: number
  status: string
  executedAt: string
  pnl?: number
}

export default function TradingHistory() {
  const [trades, setTrades] = useState<Trade[]>([])
  const [loading, setLoading] = useState(true)
  const [isClient, setIsClient] = useState(false)

  useEffect(() => {
    setIsClient(true)
  }, [])

  const formatTime = (dateString: string) => {
    if (!isClient) return '--:--:--'
    return new Date(dateString).toLocaleTimeString()
  }

  useEffect(() => {
    async function fetchTrades() {
      try {
        // Try Drift trading history first
        const driftRes = await fetch('/api/drift/trading-history')
        if (driftRes.ok) {
          const data = await driftRes.json()
          if (data.success && data.trades) {
            setTrades(data.trades)
          } else {
            // No trades available
            setTrades([])
          }
        } else {
          // API failed - try fallback to local database
          const res = await fetch('/api/trading-history')
          if (res.ok) {
            const data = await res.json()
            setTrades(data || [])
          } else {
            // Both APIs failed - show empty state
            setTrades([])
          }
        }
      } catch (error) {
        console.error('Failed to fetch trades:', error)
        setTrades([])
      }
      setLoading(false)
    }
    fetchTrades()
  }, [])

  const getSideColor = (side: string) => {
    return side.toLowerCase() === 'buy' ? 'text-green-400' : 'text-red-400'
  }

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case 'filled': return 'text-green-400'
      case 'pending': return 'text-yellow-400'
      case 'cancelled': return 'text-red-400'
      default: return 'text-gray-400'
    }
  }

  const getPnLColor = (pnl?: number) => {
    if (!pnl) return 'text-gray-400'
    return pnl >= 0 ? 'text-green-400' : 'text-red-400'
  }

  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-purple-400 to-violet-600 rounded-lg flex items-center justify-center mr-3">
            📊
          </span>
          Trading History
        </h2>
        <span className="text-xs text-gray-400">Latest {trades.length} trades</span>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-8">
          <div className="spinner"></div>
          <span className="ml-2 text-gray-400">Loading trades...</span>
        </div>
      ) : trades.length === 0 ? (
        <div className="text-center py-8">
          <div className="w-16 h-16 bg-gray-700/50 rounded-full flex items-center justify-center mx-auto mb-4">
            <span className="text-gray-400 text-2xl">📈</span>
          </div>
          <p className="text-gray-400 font-medium">No trading history</p>
          <p className="text-gray-500 text-sm mt-2">Your completed trades will appear here</p>
        </div>
      ) : (
        <div className="overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-700">
                  <th className="text-left py-3 px-4 text-gray-400 font-medium text-sm">Asset</th>
                  <th className="text-left py-3 px-4 text-gray-400 font-medium text-sm">Side</th>
                  <th className="text-right py-3 px-4 text-gray-400 font-medium text-sm">Amount</th>
                  <th className="text-right py-3 px-4 text-gray-400 font-medium text-sm">Price</th>
                  <th className="text-center py-3 px-4 text-gray-400 font-medium text-sm">Status</th>
                  <th className="text-right py-3 px-4 text-gray-400 font-medium text-sm">P&L</th>
                  <th className="text-right py-3 px-4 text-gray-400 font-medium text-sm">Time</th>
                </tr>
              </thead>
              <tbody>
                {trades.map((trade, index) => (
                  <tr key={trade.id} className="border-b border-gray-800/50 hover:bg-gray-800/30 transition-colors">
                    <td className="py-4 px-4">
                      <div className="flex items-center">
                        <div className="w-8 h-8 bg-gradient-to-br from-orange-400 to-orange-600 rounded-full flex items-center justify-center mr-3">
                          <span className="text-white text-xs font-bold">
                            {trade.symbol.slice(0, 2)}
                          </span>
                        </div>
                        <span className="font-medium text-white">{trade.symbol}</span>
                      </div>
                    </td>
                    <td className="py-4 px-4">
                      <span className={`font-semibold ${getSideColor(trade.side)}`}>
                        {trade.side}
                      </span>
                    </td>
                    <td className="py-4 px-4 text-right font-mono text-gray-300">
                      {trade.amount}
                    </td>
                    <td className="py-4 px-4 text-right font-mono text-gray-300">
                      ${trade.price.toLocaleString()}
                    </td>
                    <td className="py-4 px-4 text-center">
                      <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                        trade.status.toLowerCase() === 'filled' ? 'bg-green-100 text-green-800' :
                        trade.status.toLowerCase() === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                        'bg-red-100 text-red-800'
                      }`}>
                        {trade.status}
                      </span>
                    </td>
                    <td className="py-4 px-4 text-right">
                      <span className={`font-mono font-semibold ${getPnLColor(trade.pnl)}`}>
                        {trade.pnl ? `${trade.pnl >= 0 ? '+' : ''}$${trade.pnl.toFixed(2)}` : '--'}
                      </span>
                    </td>
                    <td className="py-4 px-4 text-right text-xs text-gray-400">
                      {formatTime(trade.executedAt)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}
