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

export default function RecommendedCreators() {
  const [items, setItems] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [busyId, setBusyId] = useState(null)

  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 : [])
          setError('')
        }
      } catch {
        if (!cancelled) {
          setError('Could not load creator recommendations right now.')
        }
      } finally {
        if (!cancelled) {
          setLoading(false)
        }
      }
    }

    load()

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

  async function handleFollow(creator) {
    if (!creator?.username || busyId === creator.id) {
      return
    }

    setBusyId(creator.id)

    try {
      const response = await window.axios.post(`/@${creator.username}/follow`)
      const isFollowing = Boolean(response.data?.following)

      if (isFollowing) {
        setItems((current) => current.filter((item) => item.id !== creator.id))
      }
    } catch {
      setError('Could not update follow state right now.')
    } finally {
      setBusyId(null)
    }
  }

  return (
    <section className="rounded-[28px] border border-white/10 bg-[#08111c]/90 shadow-2xl shadow-black/20">
      <div className="flex items-start justify-between gap-4 px-5 pt-5 pb-4 sm:px-6 sm:pt-6">
        <div>
          <p className="text-[11px] uppercase tracking-[0.24em] text-sky-200/70">Community</p>
          <h2 className="mt-1 text-xl font-semibold text-white">Recommended Creators</h2>
          <p className="mt-1.5 text-sm leading-6 text-slate-400">
            Strong accounts you are not following yet.
          </p>
        </div>
        <a
          className="mt-1 inline-flex shrink-0 items-center gap-2 rounded-full border border-sky-400/25 bg-sky-400/10 px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-400/15"
          href="/creators/top"
        >
          See all
          <i className="fa-solid fa-arrow-right text-[10px]" />
        </a>
      </div>

      <div className="px-5 pb-5 sm:px-6 sm:pb-6">
        {loading ? (
          <div className="space-y-3">
            {[...Array(3)].map((_, i) => (
              <div key={i} className="flex items-center gap-3 rounded-2xl border border-white/6 bg-white/[0.03] p-3">
                <div className="h-11 w-11 shrink-0 animate-pulse rounded-2xl bg-white/8" />
                <div className="flex-1 space-y-2">
                  <div className="h-3 w-28 animate-pulse rounded-full bg-white/8" />
                  <div className="h-2.5 w-20 animate-pulse rounded-full bg-white/5" />
                </div>
                <div className="h-8 w-16 animate-pulse rounded-full bg-white/5" />
              </div>
            ))}
          </div>
        ) : null}

        {error ? <p className="mb-3 text-sm text-rose-300">{error}</p> : null}

        {!loading && items.length === 0 ? (
          <div className="rounded-2xl border border-white/8 bg-white/5 px-5 py-6 text-sm text-slate-300">
            <p className="font-medium text-white">No creator recommendations right now.</p>
            <p className="mt-2 text-slate-400">Browse the full creator directory to keep expanding your network.</p>
          </div>
        ) : null}

        {!loading && items.length > 0 ? (
          <ul className="space-y-2.5">
            {items.map((creator) => (
              <li key={creator.id}>
                <div className="flex items-center gap-3 rounded-2xl border border-white/8 bg-white/[0.03] p-3 transition hover:border-white/14 hover:bg-white/[0.05]">
                  {/* Avatar */}
                  <a href={creator.url || '#'} className="shrink-0" tabIndex={-1} aria-hidden="true">
                    <img
                      src={creator.avatar || '/images/default-avatar.png'}
                      alt={creator.username || creator.name || 'Creator'}
                      className="h-11 w-11 rounded-2xl border border-white/10 object-cover"
                    />
                  </a>

                  {/* Info */}
                  <a href={creator.url || '#'} className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-1.5">
                      <span className="truncate text-sm font-semibold text-white">
                        {creator.username ? `@${creator.username}` : creator.name}
                      </span>
                      <span className="inline-flex items-center rounded-full border border-sky-400/20 bg-sky-400/10 px-2 py-0.5 text-[9px] font-medium uppercase tracking-wide text-sky-200">
                        Suggested
                      </span>
                    </div>
                    <div className="mt-1 flex flex-wrap items-center gap-2">
                      <LevelBadge level={creator.level} rank={creator.rank} compact />
                      <span className="text-[11px] text-slate-500">
                        {Number(creator.followers_count || 0).toLocaleString()} followers
                        {creator.uploads_count ? ` · ${Number(creator.uploads_count).toLocaleString()} uploads` : ''}
                      </span>
                    </div>
                  </a>

                  {/* Follow button */}
                  <button
                    type="button"
                    onClick={() => handleFollow(creator)}
                    disabled={busyId === creator.id || !creator.username}
                    className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-emerald-400/25 bg-emerald-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-wide text-emerald-100 transition hover:border-emerald-300/40 hover:bg-emerald-400/18 disabled:cursor-not-allowed disabled:opacity-60"
                  >
                    <i className={`fa-solid ${busyId === creator.id ? 'fa-circle-notch fa-spin' : 'fa-user-plus'} text-[10px]`} />
                    Follow
                  </button>
                </div>
              </li>
            ))}
          </ul>
        ) : null}
      </div>
    </section>
  )
}
