import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import api from '../../api/client.js';
import { useAuth } from '../../context/AuthContext.jsx';

export default function AdminDashboard() {
  const { isSuperAdmin } = useAuth();
  const [stats, setStats] = useState({ vendors: 0, courses: 0, pending: 0 });

  useEffect(() => {
    Promise.all([
      api.get('/vendors'),
      api.get('/courses/admin/all'),
      api.get('/questions/pending'),
    ]).then(([v, c, p]) => {
      setStats({
        vendors: v.data.vendors.length,
        courses: c.data.courses.length,
        pending: p.data.questions.length,
      });
    }).catch(() => {});
  }, []);

  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))' }}>
        <div className="card stat">
          <div className="icon-chip" style={{ margin: '0 auto 10px' }}>🏢</div>
          <div className="num">{stats.vendors}</div><div className="lbl">Vendors</div>
        </div>
        <div className="card stat">
          <div className="icon-chip" style={{ margin: '0 auto 10px' }}>📚</div>
          <div className="num">{stats.courses}</div><div className="lbl">Courses / Exams</div>
        </div>
        <Link to="/admin/approvals" className="card stat card-hover">
          <div className={`icon-chip ${stats.pending ? 'amber' : ''}`} style={{ margin: '0 auto 10px' }}>⏳</div>
          <div className="num" style={{ color: stats.pending ? 'var(--amber)' : 'var(--blue-600)', WebkitTextFillColor: stats.pending ? 'var(--amber)' : '' }}>{stats.pending}</div>
          <div className="lbl">Pending approvals</div>
        </Link>
      </div>

      <div className="card mt-3">
        <h3>Quick actions</h3>
        <div className="row wrap mt-2">
          <Link to="/admin/vendors" className="btn btn-ghost">+ Add vendor</Link>
          <Link to="/admin/courses" className="btn btn-ghost">+ Add course / exam</Link>
          <Link to="/admin/import" className="btn btn-ghost">⬆ Import questions (CSV/Excel)</Link>
          <Link to="/admin/approvals" className="btn btn-ghost">Review submissions</Link>
          {isSuperAdmin && (
            <>
              <Link to="/admin/users" className="btn btn-ghost">👤 Manage users</Link>
              <Link to="/admin/finance" className="btn btn-ghost">💰 Finance</Link>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
