import { useEffect, useState } from 'react'
import { performanceApi } from '@/services/api'
import SimpleLineChart from './SimpleLineChart'

export default function EquityPerformancePanel() {
  const [equity, setEquity] = useState<{ time: number; equity: number }[]>([])
  const [perf, setPerf] = useState<any | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let mounted = true
    ;(async () => {
      try {
        setLoading(true)
        const [eq, pf] = await Promise.all([
          performanceApi.getEquityHistory('XAU/USD', '1m', 300),
          performanceApi.getPerformance('XAU/USD', '1m', 300),
        ])
        if (mounted) { setEquity(eq); setPerf(pf) }
      } catch (e: any) {
        setError(e?.message || 'Failed to load equity/performance')
      } finally {
        setLoading(false)
      }
    })()
    return () => { mounted = false }
  }, [])

  return (
    <div className="card">
      <div className="title">Equity & Performance</div>
      {loading && <div className="text-gray-400">Loading…</div>}
      {error && <div className="text-red-500">{error}</div>}
      {!loading && !error && (
        <div style={{ display: 'grid', gap: 12 }}>
          <SimpleLineChart title="Equity Curve" data={equity.map(r => ({ time: r.time, value: r.equity }))} />
          {perf?.available ? (
            <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
              <Metric label="Total Return" value={pct(perf.total_return)} />
              <Metric label="Sharpe" value={num(perf.sharpe)} />
              <Metric label="Sortino" value={num(perf.sortino)} />
              <Metric label="Max Drawdown" value={pct(perf.max_drawdown)} />
            </div>
          ) : (
            <div className="text-gray-400">Not enough data</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 pct(v?: number | null) {
  if (v === null || v === undefined) return '-'
  return (v * 100).toFixed(2) + '%'
}

function num(v?: number | null) {
  if (v === null || v === undefined) return '-'
  return String(Number(v).toFixed(2))
}