import React, { useEffect, useState } from 'react'

export default function RecommendedCreators() {
  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/recommended-creators')
        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">Recommended Creators</h2>
        <a className="text-xs text-cyan-300 hover:text-cyan-200" href="/creators/top">
          See all
        </a>
      </div>

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

      {!loading && items.length === 0 ? (
        <p className="text-sm text-gray-400">No creator recommendations right now.</p>
      ) : null}

      {!loading && items.length > 0 ? (
        <div className="space-y-3">
          {items.map((creator) => (
            <article
              key={creator.id}
              className="flex items-center justify-between rounded-xl border border-gray-700 bg-gray-900/70 p-3 transition hover:scale-[1.02]"
            >
              <a href={creator.url || '#'} className="flex min-w-0 items-center gap-3">
                <img
                  src={creator.avatar || '/images/default-avatar.png'}
                  alt={creator.username || creator.name || 'Creator'}
                  className="h-10 w-10 rounded-full border border-gray-600 object-cover"
                />
                <div className="min-w-0">
                  <p className="truncate text-sm font-semibold text-white">
                    {creator.username ? `@${creator.username}` : creator.name}
                  </p>
                  <p className="text-xs text-gray-400">{creator.followers_count} followers</p>
                </div>
              </a>

              <a
                href={creator.url || '#'}
                className="rounded-lg border border-cyan-400/60 px-3 py-1 text-xs font-semibold text-cyan-200 transition hover:bg-cyan-500/20"
              >
                Follow
              </a>
            </article>
          ))}
        </div>
      ) : null}
    </section>
  )
}
