import React, { useEffect, useState } from 'react'
import AchievementBadge from '../../components/achievements/AchievementBadge'

export default function RecentAchievements() {
  const [data, setData] = useState({ recent: [], counts: { unlocked: 0, total: 0 } })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false

    async function load() {
      try {
        const response = await window.axios.get('/api/user/achievements')
        if (!cancelled && response.data) {
          setData(response.data)
        }
      } finally {
        if (!cancelled) {
          setLoading(false)
        }
      }
    }

    load()

    return () => {
      cancelled = true
    }
  }, [])

  return (
    <section className="rounded-xl border border-gray-700 bg-gray-800 p-5 shadow-lg">
      <div className="flex items-center justify-between gap-3">
        <div>
          <p className="text-xs uppercase tracking-[0.2em] text-gray-400">Achievements</p>
          <h2 className="mt-2 text-xl font-semibold text-white">Recent Unlocks</h2>
        </div>
        <span className="rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs text-gray-300">
          {data?.counts?.unlocked || 0} / {data?.counts?.total || 0}
        </span>
      </div>

      {loading ? <p className="mt-4 text-sm text-gray-400">Loading achievements...</p> : null}

      {!loading && (!Array.isArray(data?.recent) || data.recent.length === 0) ? (
        <p className="mt-4 text-sm text-gray-400">No achievements unlocked yet.</p>
      ) : null}

      {!loading && Array.isArray(data?.recent) && data.recent.length > 0 ? (
        <div className="mt-4 space-y-3">
          {data.recent.map((achievement) => (
            <article key={achievement.id} className="rounded-xl border border-gray-700 bg-gray-900/60 p-3">
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0">
                  <p className="text-sm font-semibold text-white">{achievement.name}</p>
                  <p className="mt-1 text-xs text-gray-400">{achievement.description}</p>
                </div>
                <AchievementBadge achievement={achievement} compact />
              </div>
            </article>
          ))}
        </div>
      ) : null}
    </section>
  )
}
