"use client"
import React, { useEffect, useState } from 'react'
import AutoTradingPanel from './AutoTradingPanel'
import TradingHistory from './TradingHistory'
import DeveloperSettings from './DeveloperSettings'

export default function Dashboard() {
  const [positions, setPositions] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    async function fetchPositions() {
      try {
        const res = await fetch('/api/trading')
        if (res.ok) {
          const data = await res.json()
          setPositions(data.positions || [])
        } else {
          setError('Failed to load positions')
        }
      } catch (e) {
        setError('Error loading positions')
      }
      setLoading(false)
    }
    fetchPositions()
  }, [])

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-8 p-8 bg-gray-950 min-h-screen">
      <div className="space-y-8">
        <AutoTradingPanel />
        <DeveloperSettings />
      </div>
      <div className="space-y-8">
        <div className="bg-gray-900 rounded-lg shadow p-6">
          <h2 className="text-xl font-bold mb-4 text-white">Open Positions</h2>
          {loading ? <div className="text-gray-400">Loading...</div> : error ? <div className="text-red-400">{error}</div> : (
            <table className="w-full text-sm text-left">
              <thead className="text-gray-400 border-b border-gray-700">
                <tr>
                  <th className="py-2">Symbol</th>
                  <th>Side</th>
                  <th>Size</th>
                  <th>Entry Price</th>
                  <th>Unrealized PnL</th>
                </tr>
              </thead>
              <tbody>
                {positions.map((pos, i) => (
                  <tr key={i} className="border-b border-gray-800 hover:bg-gray-800">
                    <td className="py-2">{pos.symbol}</td>
                    <td>{pos.side}</td>
                    <td>{pos.size}</td>
                    <td>{pos.entryPrice}</td>
                    <td>{pos.unrealizedPnl}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
        <TradingHistory />
      </div>
    </div>
  )
}
