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

export default function TrendingArtworks() {
  const [items, setItems] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false

    async function load() {
      try {
        const response = await window.axios.get('/api/dashboard/trending-artworks')
        if (!cancelled) {
          setItems(Array.isArray(response.data?.data) ? response.data.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="mb-4 flex items-center justify-between">
        <h2 className="text-xl font-semibold">Trending Artworks</h2>
        <a className="text-xs text-cyan-300 hover:text-cyan-200" href="/discover/trending">
          Explore more
        </a>
      </div>

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

      {!loading && items.length === 0 ? (
        <p className="text-sm text-gray-400">No trending artworks available.</p>
      ) : null}

      {!loading && items.length > 0 ? (
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
          {items.map((item) => (
            <a
              key={item.id}
              href={item.url}
              className="group overflow-hidden rounded-xl border border-gray-700 bg-gray-900/70 transition hover:scale-[1.02] hover:border-cyan-500/40"
            >
              <img
                src={item.thumbnail || '/images/placeholder.jpg'}
                alt={item.title}
                loading="lazy"
                className="h-28 w-full object-cover sm:h-32"
              />
              <div className="p-2">
                <p className="line-clamp-1 text-sm font-semibold text-white">{item.title}</p>
                {item.creator ? (
                  <div className="mt-1 flex items-center justify-between gap-2">
                    <span className="truncate text-xs text-gray-400">
                      {item.creator.username ? `@${item.creator.username}` : item.creator.name}
                    </span>
                    <LevelBadge level={item.creator.level} rank={item.creator.rank} compact />
                  </div>
                ) : null}
                <p className="mt-1 text-xs text-gray-400">
                  {item.likes} likes • {item.views} views
                </p>
              </div>
            </a>
          ))}
        </div>
      ) : null}
    </section>
  )
}
