import { fetchTopPriceIps, fetchStats } from '../api';
import { usePolling } from '../hooks/usePolling';
import './Dashboard.css';

function formatUptime(seconds: number): string {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = Math.floor(seconds % 60);
  return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}

export function Dashboard() {
  const { data: stats } = usePolling(fetchStats, 5000);
  const { data: topIps } = usePolling(fetchTopPriceIps, 10000);

  return (
    <div className="dashboard">
      <header className="dash-header">
        <span className="dash-logo">◈ SENTINEL_LENS</span>
        <span className="dash-status">
          <span className="dot dot--green" /> OPERATIONAL
        </span>
      </header>

      <div className="stat-grid">
        <div className="stat-card">
          <div className="stat-label">SYSTEM_UPTIME</div>
          <div className="stat-value">{stats ? formatUptime(stats.uptime_seconds) : '--:--:--'}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">TOTAL_HITS</div>
          <div className="stat-value neon-green">
            {stats ? stats.total_hits.toLocaleString() : '—'}
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-label">ACTIVE_IPS</div>
          <div className="stat-value neon-cyan">
            <span className="blink">✦</span> {stats ? stats.active_ips : '—'}
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-label">AVG_LATENCY</div>
          <div className="stat-value neon-cyan">
            <span className="blink">◈</span> {stats ? `${stats.avg_latency_ms.toFixed(0)}ms` : '—'}
          </div>
        </div>
      </div>

      <section className="geo-section">
        <div className="section-title">
          PRICE_API_CALLERS <span className="globe">📡</span>
        </div>
        {topIps && topIps.length > 0 ? (
          <ul className="geo-list">
            {topIps.map((item) => (
              <li key={item.ip} className="geo-item">
                <span className="geo-country">{item.ip}</span>
                <div className="geo-bar-wrap">
                  <div className="geo-bar" style={{ width: `${item.percentage}%` }} />
                </div>
                <span className="geo-pct">{item.hit_count}</span>
              </li>
            ))}
          </ul>
        ) : (
          <div className="empty-msg">No price API calls yet</div>
        )}
      </section>
    </div>
  );
}
