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

export default function Dashboard() {
  const { user } = useAuth();
  const [attempts, setAttempts] = useState(null);
  const [purchases, setPurchases] = useState([]);

  useEffect(() => {
    api.get('/attempts').then(({ data }) => setAttempts(data.attempts)).catch(() => setAttempts([]));
    api.get('/payments/my').then(({ data }) => setPurchases(data.purchases)).catch(() => {});
  }, []);

  if (!attempts) return <Spinner />;

  return (
    <div className="container page">
      <h1>Hi, {user.name.split(' ')[0]} 👋</h1>
      <p className="muted">Track your progress and jump back into an exam.</p>

      <div className="card mt-3">
        <h3>Unlocked exams</h3>
        {purchases.length === 0 ? (
          <p className="muted" style={{ marginBottom: 0 }}>No purchased exams yet. <Link to="/vendors">Browse exams →</Link></p>
        ) : (
          <div className="row wrap">
            {purchases.map((p) => (
              <Link key={p.id} to={`/courses/${p.course.slug}`} className="badge badge-green" style={{ textDecoration: 'none' }}>
                {p.course.title}
              </Link>
            ))}
          </div>
        )}
      </div>

      <h2 className="mt-4">Recent attempts</h2>
      {attempts.length === 0 ? (
        <div className="card"><p className="muted" style={{ marginBottom: 0 }}>No attempts yet. <Link to="/vendors">Start an exam →</Link></p></div>
      ) : (
        <div className="card table-card">
          <div className="table-scroll">
          <table className="table">
            <thead>
              <tr><th>Exam</th><th>Mode</th><th>Score</th><th>Date</th><th></th></tr>
            </thead>
            <tbody>
              {attempts.map((a) => (
                <tr key={a.id}>
                  <td>{a.course.title}</td>
                  <td><span className="badge">{a.mode}</span></td>
                  <td>{a.completed ? `${a.score}/${a.total}` : '—'}</td>
                  <td className="muted">{new Date(a.startedAt).toLocaleDateString()}</td>
                  <td>
                    {a.completed
                      ? <Link to={`/result/${a.id}`} className="btn btn-sm btn-ghost">Review</Link>
                      : <Link to={`/courses/${a.course.slug}`} className="btn btn-sm btn-ghost">Resume</Link>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        </div>
      )}
    </div>
  );
}
