import { useEffect, useState } from 'react';
import { Link, Navigate } from 'react-router-dom';
import { api } from '../api';
import { useAuth } from '../AuthContext';

function formatUnlockedAt(iso) {
  if (!iso) return null;
  try {
    return new Date(iso).toLocaleString();
  } catch {
    return null;
  }
}

export default function AchievementsPage() {
  const { user, loading } = useAuth();
  const [achievements, setAchievements] = useState([]);
  const [unlocked, setUnlocked] = useState(0);
  const [total, setTotal] = useState(0);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(true);

  useEffect(() => {
    if (!user || user.role === 'admin') return undefined;
    let cancelled = false;
    (async () => {
      try {
        const data = await api.achievements();
        if (cancelled) return;
        setAchievements(data.achievements || []);
        setUnlocked(data.unlocked || 0);
        setTotal(data.total || 0);
      } catch (err) {
        if (!cancelled) setError(err.message);
      } finally {
        if (!cancelled) setBusy(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [user?.id, user?.role]);

  if (loading || busy) return <p className="muted">Loading…</p>;
  if (!user) return <Navigate to="/login" replace />;
  if (user.role === 'admin') return <Navigate to="/admin" replace />;

  return (
    <section className="section">
      <div className="section-head">
        <div>
          <h1>Achievements</h1>
          <p className="muted">
            Unlock badges by playing. Earned badges show on your{' '}
            <Link to="/profile">profile</Link>.
          </p>
        </div>
        <div className="catalog-luck-pill">
          {unlocked}/{total} unlocked
        </div>
      </div>

      {error && <div className="error">{error}</div>}

      {achievements.length === 0 && !error && (
        <div className="empty">No achievements defined yet.</div>
      )}

      <div className="achievement-grid">
        {achievements.map((a) => {
          const done = Boolean(a.unlockedAt);
          return (
            <article
              key={a.key}
              className={`achievement-card${done ? ' unlocked' : ' locked'}`}
            >
              <div className="achievement-card-icon" aria-hidden>
                {a.icon || '★'}
              </div>
              <div className="achievement-card-body">
                <h2>{a.name}</h2>
                <p className="muted">{a.description}</p>
                {done ? (
                  <span className="achievement-card-meta">
                    Unlocked {formatUnlockedAt(a.unlockedAt)}
                  </span>
                ) : (
                  <span className="achievement-card-meta locked-label">Locked</span>
                )}
              </div>
            </article>
          );
        })}
      </div>
    </section>
  );
}
