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

export default function TopCreatorsWidget() {
  const [data, setData] = useState({ items: [] })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false

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

    load()

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

  const items = Array.isArray(data?.items) ? data.items.slice(0, 5) : []

  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">Leaderboard</p>
          <h2 className="mt-2 text-xl font-semibold text-white">Top Creators</h2>
        </div>
        <a href="/leaderboard?type=creators&period=weekly" className="text-xs font-semibold uppercase tracking-[0.14em] text-sky-300 hover:text-sky-200">
          View all
        </a>
      </div>

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

      {!loading && items.length === 0 ? (
        <p className="mt-4 text-sm text-gray-400">No creators ranked yet.</p>
      ) : null}

      {!loading && items.length > 0 ? (
        <div className="mt-4 space-y-3">
          {items.map((item) => {
            const entity = item.entity || {}

            return (
              <a key={item.rank} href={entity.url || '#'} className="flex items-center gap-3 rounded-xl border border-gray-700 bg-gray-900/60 p-3 transition hover:border-sky-400/40">
                <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/5 text-sm font-black text-white">
                  #{item.rank}
                </div>
                {entity.avatar ? <img src={entity.avatar} alt={entity.name || 'Creator'} className="h-11 w-11 rounded-xl object-cover" loading="lazy" /> : null}
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-semibold text-white">{entity.name}</p>
                  <div className="mt-1 flex items-center gap-2">
                    <LevelBadge level={entity.level} rank={entity.rank} compact />
                  </div>
                </div>
                <span className="text-sm font-semibold text-sky-300">{Math.round(item.score)}</span>
              </a>
            )
          })}
        </div>
      ) : null}
    </section>
  )
}
