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-[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-start sm:justify-between">
        <div>
          <p className="text-[11px] uppercase tracking-[0.24em] text-sky-200/70">Progression</p>
          <h2 className="mt-2 text-xl font-semibold text-white">XP Progress</h2>
          <p className="mt-2 max-w-xs text-sm leading-6 text-slate-300">Track how close you are to the next level and keep your creator momentum visible.</p>
        </div>
        <div className="sm:self-start">
          <LevelBadge level={data.level} rank={data.rank} compact />
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-white/8 bg-white/[0.04] p-4">
        <XPProgressBar
          xp={data.xp}
          currentLevelXp={data.current_level_xp}
          nextLevelXp={data.next_level_xp}
          progressPercent={data.progress_percent}
          maxLevel={data.max_level}
        />

        <div className="mt-4 flex items-center justify-between gap-3 text-xs uppercase tracking-[0.16em] text-slate-400">
          <span>Total XP</span>
          <span className="font-semibold text-sky-100">{Number(data.xp || 0).toLocaleString()}</span>
        </div>
      </div>

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