import React, { useState } from 'react'
import ProfileCoverEditor from './ProfileCoverEditor'
import LevelBadge from '../xp/LevelBadge'
import XPProgressBar from '../xp/XPProgressBar'
import FollowButton from '../social/FollowButton'

export default function ProfileHero({ user, profile, isOwner, viewerIsFollowing, followerCount, heroBgUrl, countryName, leaderboardRank, extraActions = null }) {
  const [following, setFollowing] = useState(viewerIsFollowing)
  const [count, setCount] = useState(followerCount)
  const [editorOpen, setEditorOpen] = useState(false)
  const [coverUrl, setCoverUrl] = useState(user?.cover_url || heroBgUrl || null)
  const [coverPosition, setCoverPosition] = useState(Number.isFinite(user?.cover_position) ? user.cover_position : 50)

  const uname = user.username || user.name || 'Unknown'
  const displayName = user.name || uname
  const joinDate = user.created_at
    ? new Date(user.created_at).toLocaleDateString('en-US', { month: 'long', year: 'numeric' })
    : null
  const bio = profile?.bio || profile?.about || ''

  return (
    <>
      <div className="max-w-6xl mx-auto px-4 pt-4">
        <div className="relative overflow-hidden rounded-2xl border border-white/10">
          <div
            className="w-full h-[180px] md:h-[220px] xl:h-[252px]"
            style={{
              background: coverUrl
                ? `url('${coverUrl}') center ${coverPosition}% / cover no-repeat`
                : 'linear-gradient(140deg, #0f1724 0%, #101a2a 45%, #0a1220 100%)',
              position: 'relative',
            }}
          >
            {isOwner ? (
              <div className="absolute right-3 top-3 z-20">
                <button
                  type="button"
                  onClick={() => setEditorOpen(true)}
                  className="inline-flex items-center gap-2 rounded-lg border border-white/20 bg-black/40 px-3 py-2 text-xs font-medium text-white hover:bg-black/60"
                  aria-label="Edit cover image"
                >
                  <i className="fa-solid fa-image" />
                  Edit Cover
                </button>
              </div>
            ) : null}

            <div
              className="absolute inset-0"
              style={{
                background: coverUrl
                  ? 'linear-gradient(to bottom, rgba(0,0,0,0.2), rgba(0,0,0,0.62))'
                  : 'radial-gradient(ellipse at 16% 40%, rgba(77,163,255,.18) 0%, transparent 60%), radial-gradient(ellipse at 84% 22%, rgba(224,122,33,.12) 0%, transparent 54%)',
              }}
            />
            <div className="absolute inset-0 opacity-[0.06] pointer-events-none" style={{ backgroundImage: 'url(/gfx/noise.png)', backgroundSize: '32px' }} />
          </div>
        </div>

        <div className="relative -mt-14 md:-mt-16 pb-4 px-1">
          <div className="flex flex-col gap-4 md:flex-row md:items-end md:gap-5">
            <div className="mx-auto z-10 shrink-0 md:mx-0">
              <img
                src={user.avatar_url || '/default/avatar_default.webp'}
                alt={`${uname}'s avatar`}
                className="h-[104px] w-[104px] rounded-full border-2 border-white/15 object-cover shadow-[0_0_0_6px_rgba(15,23,36,0.95),0_10px_32px_rgba(0,0,0,0.6)] md:h-[116px] md:w-[116px]"
              />
            </div>

            <div className="min-w-0 flex-1 text-center md:text-left">
              <h1 className="text-[28px] font-bold leading-tight tracking-tight text-white md:text-[34px]">
                {displayName}
              </h1>
              <p className="mt-0.5 font-mono text-sm text-slate-400">@{uname}</p>

              <div className="mt-3 flex flex-wrap items-center justify-center gap-2 md:justify-start">
                <LevelBadge level={user?.level} rank={user?.rank} />
                {leaderboardRank?.rank ? (
                  <span className="inline-flex items-center gap-2 rounded-full border border-sky-400/25 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-sky-100">
                    Rank #{leaderboardRank.rank} this week
                  </span>
                ) : null}
              </div>

              <div className="mt-2 flex flex-wrap items-center justify-center gap-2.5 text-xs text-slate-400 md:justify-start">
                {countryName ? (
                  <span className="inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/5 px-2.5 py-1">
                    {profile?.country_code ? (
                      <img
                        src={`/gfx/flags/shiny/24/${encodeURIComponent(String(profile.country_code).toUpperCase())}.png`}
                        alt={countryName}
                        className="w-4 h-auto rounded-sm"
                        onError={(event) => { event.target.style.display = 'none' }}
                      />
                    ) : null}
                    {countryName}
                  </span>
                ) : null}

                {joinDate ? (
                  <span className="inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/5 px-2.5 py-1">
                    <i className="fa-solid fa-calendar-days fa-fw opacity-70" />
                    Joined {joinDate}
                  </span>
                ) : null}

                {profile?.website ? (
                  <a
                    href={profile.website.startsWith('http') ? profile.website : `https://${profile.website}`}
                    target="_blank"
                    rel="nofollow noopener noreferrer"
                    className="inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/5 px-2.5 py-1 text-sky-300 transition-colors hover:bg-white/10 hover:text-sky-200"
                  >
                    <i className="fa-solid fa-link fa-fw" />
                    {(() => {
                      try {
                        const url = profile.website.startsWith('http') ? profile.website : `https://${profile.website}`
                        return new URL(url).hostname
                      } catch {
                        return profile.website
                      }
                    })()}
                  </a>
                ) : null}
              </div>

              {bio ? (
                <p className="mx-auto mt-3 max-w-2xl line-clamp-2 text-sm leading-relaxed text-slate-300/90 md:mx-0 md:line-clamp-3">
                  {bio}
                </p>
              ) : null}

              <XPProgressBar
                xp={user?.xp}
                currentLevelXp={user?.current_level_xp}
                nextLevelXp={user?.next_level_xp}
                progressPercent={user?.progress_percent}
                maxLevel={user?.max_level}
                className="mt-4 max-w-xl"
              />
            </div>

            <div className="shrink-0 flex items-center justify-center gap-2 pb-0.5 md:justify-end">
              {extraActions}
              {isOwner ? (
                <>
                  <a
                    href="/dashboard/profile"
                    className="inline-flex items-center gap-2 rounded-xl border border-white/15 px-4 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/5 hover:text-white"
                    aria-label="Edit profile"
                  >
                    <i className="fa-solid fa-pen fa-fw" />
                    Edit Profile
                  </a>
                  <a
                    href="/studio"
                    className="inline-flex items-center gap-2 rounded-xl bg-sky-600 px-4 py-2.5 text-sm font-medium text-white shadow-lg shadow-sky-900/30 transition-all hover:bg-sky-500"
                    aria-label="Open Studio"
                  >
                    <i className="fa-solid fa-wand-magic-sparkles fa-fw" />
                    Studio
                  </a>
                </>
              ) : (
                <>
                  <FollowButton
                    username={uname}
                    initialFollowing={following}
                    initialCount={count}
                    followingClassName="bg-green-500/10 border border-green-400/40 text-green-400 hover:bg-green-500/15"
                    idleClassName="bg-sky-500/10 border border-sky-400/40 text-sky-400 hover:bg-sky-500/20"
                    onChange={({ following: nextFollowing, followersCount }) => {
                      setFollowing(nextFollowing)
                      setCount(followersCount)
                    }}
                  />

                  <button
                    type="button"
                    onClick={() => {
                      if (navigator.share) {
                        navigator.share({ title: `${displayName} on Skinbase`, url: window.location.href })
                      } else {
                        navigator.clipboard.writeText(window.location.href)
                      }
                    }}
                    aria-label="Share profile"
                    className="rounded-xl border border-white/10 p-2.5 text-slate-400 transition-all hover:bg-white/5 hover:text-white"
                  >
                    <i className="fa-solid fa-share-nodes fa-fw" />
                  </button>
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      <ProfileCoverEditor
        open={editorOpen}
        onClose={() => setEditorOpen(false)}
        currentCoverUrl={coverUrl}
        currentPosition={coverPosition}
        coverUrl={coverUrl}
        coverPosition={coverPosition}
        onCoverUpdated={(nextUrl, nextPosition) => {
          setCoverUrl(nextUrl)
          setCoverPosition(nextPosition)
        }}
        onCoverRemoved={() => {
          setCoverUrl(null)
          setCoverPosition(50)
        }}
      />
    </>
  )
}
