import { useEffect, useState } from 'react'
import { accountApi } from '@/services/api'

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

  useEffect(() => {
    let mounted = true
    ;(async () => {
      try {
        setLoading(true)
        const [a, p] = await Promise.all([accountApi.getAccount(), accountApi.getPositions()])
        if (mounted) { setAccount(a); setPositions(p) }
      } catch (e: any) {
        setError(e?.message || 'Failed to load account')
      } finally {
        setLoading(false)
      }
    })()
    return () => { mounted = false }
  }, [])

  return (
    <div className="card">
      <div className="title">Account & Positions</div>
      {loading && <div className="text-gray-400">Loading…</div>}
      {error && <div className="text-red-500">{error}</div>}
      {!loading && !error && account && (
        <div style={{ display: 'grid', gap: 12 }}>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            <Metric label="Cash" value={fmt(account.cash)} />
            <Metric label="Equity" value={fmt(account.equity)} />
            <Metric label="Initial" value={fmt(account.initial_capital)} />
          </div>
          <div>
            <div className="text-gray-300 font-semibold mb-2">Positions</div>
            {positions.length === 0 ? (
              <div className="text-gray-400">No open positions</div>
            ) : (
              <table className="w-full text-sm">
                <thead>
                  <tr className="text-left text-gray-400">
                    <th>Symbol</th>
                    <th>Qty</th>
                    <th>Avg Price</th>
                    <th>Last Price</th>
                    <th>Market Value</th>
                  </tr>
                </thead>
                <tbody>
                  {positions.map((p, i) => (
                    <tr key={i} className="border-t border-dark-border">
                      <td>{p.symbol}</td>
                      <td>{p.quantity}</td>
                      <td>{fmt(p.avg_price)}</td>
                      <td>{p.last_price ? fmt(p.last_price) : '-'}</td>
                      <td>{fmt(p.market_value)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
      )}
    </div>
  )
}

function Metric({ label, value }: { label: string; value: string }) {
  return (
    <div className="card" style={{ padding: 12 }}>
      <div className="text-gray-400 text-xs">{label}</div>
      <div className="text-gray-100 text-lg font-semibold">{value}</div>
    </div>
  )
}

function fmt(n: number) {
  return n.toLocaleString(undefined, { maximumFractionDigits: 2 })
}