import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { api, formatCredits, formatLastConnection } from '../api';

export default function AdminDashboard() {
  const [data, setData] = useState(null);
  const [error, setError] = useState('');

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await api.adminStats();
        if (!cancelled) setData(res);
      } catch (err) {
        if (!cancelled) setError(err.message);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  if (error) return <div className="error">{error}</div>;
  if (!data) return <p className="muted">Loading overview…</p>;

  const s = data.stats;

  return (
    <div>
      <div className="section-head">
        <div>
          <h1>Overview</h1>
          <p className="muted">Live snapshot of CaseOrion.</p>
        </div>
      </div>

      <div className="admin-stat-grid">
        <div className="admin-stat">
          <span className="admin-stat-label">Players</span>
          <strong>{s.players}</strong>
          <span className="muted">{s.onlinePlayers} online · {s.openWindows} windows</span>
        </div>
        <div className="admin-stat">
          <span className="admin-stat-label">Cases</span>
          <strong>
            {s.casesActive}/{s.casesTotal}
          </strong>
          <span className="muted">active / total</span>
        </div>
        <div className="admin-stat">
          <span className="admin-stat-label">Catalog items</span>
          <strong>{s.items}</strong>
          <span className="muted">{s.inventoryItems} in inventories</span>
        </div>
        <div className="admin-stat">
          <span className="admin-stat-label">Case opens</span>
          <strong>{s.caseOpens}</strong>
          <span className="muted">all time</span>
        </div>
        <div className="admin-stat">
          <span className="admin-stat-label">Achievements</span>
          <strong>{s.achievementsUnlocked}</strong>
          <span className="muted">{s.achievementsDefined} defined</span>
        </div>
      </div>

      <div className="admin-quick-links">
        <Link to="/admin/players" className="btn secondary">
          Manage players
        </Link>
        <Link to="/admin/cases" className="btn secondary">
          Manage cases
        </Link>
        <Link to="/admin/items" className="btn secondary">
          Manage items
        </Link>
        <Link to="/admin/drops" className="btn secondary">
          Drop rates
        </Link>
        <Link to="/admin/shop" className="btn secondary">
          Shop osu packs
        </Link>
        <Link to="/admin/prestige-server" className="btn secondary">
          Prestige Server
        </Link>
      </div>

      <section className="admin-block" style={{ marginTop: '1.25rem' }}>
        <h3>Recently connected</h3>
        {data.recentPlayers?.length === 0 ? (
          <p className="muted">No players yet.</p>
        ) : (
          <ul className="admin-recent-list">
            {data.recentPlayers.map((p) => (
              <li key={p.id}>
                <div className="admin-recent-avatar" aria-hidden>
                  {p.avatarUrl ? (
                    <img src={p.avatarUrl} alt="" />
                  ) : (
                    <span>{p.username.slice(0, 2).toUpperCase()}</span>
                  )}
                </div>
                <div>
                  <strong>@{p.username}</strong>
                  <div className="muted">
                    {formatCredits(p.balance)} cr ·{' '}
                    {formatLastConnection(p.lastConnection)}
                  </div>
                </div>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}
