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

export default function DecisionLogPanel() {
  const [items, setItems] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let mounted = true
    ;(async () => {
      try {
        setLoading(true)
        const rows = await decisionsApi.getLatest(50)
        if (mounted) setItems(rows)
      } catch (e: any) {
        setError(e?.message || 'Failed to load decisions')
      } finally {
        setLoading(false)
      }
    })()
    return () => { mounted = false }
  }, [])

  return (
    <div className="card">
      <div className="title">Decision Log</div>
      {loading && <div className="text-gray-400">Loading…</div>}
      {error && <div className="text-red-500">{error}</div>}
      {!loading && !error && (
        <div style={{ overflowX: 'auto' }}>
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-gray-400">
                <th>Time</th>
                <th>Symbol</th>
                <th>TF</th>
                <th>Rec</th>
                <th>Conf</th>
                <th>Risk</th>
                <th>Rationale</th>
              </tr>
            </thead>
            <tbody>
              {items.map((d) => (
                <tr key={d.id} className="border-t border-dark-border">
                  <td className="whitespace-nowrap">{new Date(d.time).toLocaleString()}</td>
                  <td>{d.symbol}</td>
                  <td>{d.timeframe}</td>
                  <td>{d.recommendation}</td>
                  <td>{(Number(d.confidence) * 100).toFixed(0)}%</td>
                  <td>{d.risk_level}</td>
                  <td className="max-w-[600px] truncate" title={d.rationale}>{d.rationale}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}