import React, { useEffect, useState } from 'react'
import LevelBadge from '../../components/xp/LevelBadge'
import XPProgressBar from '../../components/xp/XPProgressBar'

export default function XPProgressWidget({ initialLevel = 1, initialRank = 'Newbie' }) {
  const [data, setData] = useState({
    xp: 0,
    level: initialLevel,
    rank: initialRank,
    current_level_xp: 0,
    next_level_xp: 100,
    progress_percent: 0,
    max_level: false,
  })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false

    async function load() {
      try {
        const response = await window.axios.get('/api/user/xp')
        if (!cancelled && response.data) {
          setData((current) => ({ ...current, ...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-start justify-between gap-3">
        <div>
          <p className="text-xs uppercase tracking-[0.2em] text-gray-400">Progression</p>
          <h2 className="mt-2 text-xl font-semibold text-white">XP Progress</h2>
        </div>
        <LevelBadge level={data.level} rank={data.rank} compact />
      </div>

      <div className="mt-4">
        <XPProgressBar
          xp={data.xp}
          currentLevelXp={data.current_level_xp}
          nextLevelXp={data.next_level_xp}
          progressPercent={data.progress_percent}
          maxLevel={data.max_level}
        />
      </div>

      {loading ? <p className="mt-3 text-xs text-gray-400">Syncing your latest XP...</p> : null}
    </section>
  )
}
