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-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.82))] p-5 shadow-[0_24px_90px_rgba(2,8,23,0.32)]">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <p className="text-[11px] uppercase tracking-[0.24em] text-sky-200/70">Achievements</p>
          <h2 className="mt-2 text-xl font-semibold text-white">Recent Unlocks</h2>
          <p className="mt-2 max-w-xs text-sm leading-6 text-slate-300">Recent badges and milestones that reflect how your account is developing.</p>
        </div>
        <span className="inline-flex items-center justify-center rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs text-slate-300 sm:justify-start">
          {data?.counts?.unlocked || 0} / {data?.counts?.total || 0}
        </span>
      </div>

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

      {!loading && (!Array.isArray(data?.recent) || data.recent.length === 0) ? (
        <div className="mt-4 rounded-2xl border border-white/8 bg-white/[0.04] px-4 py-5 text-sm text-slate-300">
          <p className="font-medium text-white">No achievements unlocked yet.</p>
          <p className="mt-2 text-slate-400">Keep posting, engaging, and growing your profile to start earning them.</p>
        </div>
      ) : 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-2xl border border-white/8 bg-white/[0.04] p-4 transition hover:border-white/15 hover:bg-white/[0.06]">
              <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-slate-400">{achievement.description}</p>
                </div>
                <AchievementBadge achievement={achievement} compact />
              </div>
            </article>
          ))}
        </div>
      ) : null}
    </section>
  )
}
