import { useState, useEffect } from 'react'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { useAuthStore } from '@/store/auth'
import { usersApi } from '@/api'
import type { UserProfilePublic, ShopItemPublic } from '@/types'
import { GlassCard, StatsCard } from '@/components/ui'
import {
  User, Trophy, Target, CheckCircle, Flame,
  Loader2, ArrowLeft, Calendar, Shield
} from 'lucide-react'
import clsx from 'clsx'

// ============ COSMETICS HELPERS ============

interface BackgroundResult {
  styles: React.CSSProperties
  className: string
}

function getBackgroundData(background: ShopItemPublic | null): BackgroundResult {
  if (!background?.asset_data) {
    return { styles: {}, className: '' }
  }

  const data = background.asset_data as {
    type?: string
    gradient?: string[]
    pattern?: string
    color?: string
    animation?: string
    animated?: boolean
  }

  const styles: React.CSSProperties = {}
  let className = ''

  switch (data.type) {
    case 'solid':
      if (data.color) {
        styles.backgroundColor = data.color
      }
      break
    case 'gradient':
      if (data.gradient && data.gradient.length > 0) {
        styles.background = `linear-gradient(135deg, ${data.gradient.join(', ')})`
      }
      break
    case 'pattern':
      if (data.pattern === 'stars') {
        className = 'bg-stars-animated'
      } else if (data.pattern === 'gaming-icons') {
        styles.background = `
          linear-gradient(45deg, rgba(34,211,238,0.1) 25%, transparent 25%),
          linear-gradient(-45deg, rgba(34,211,238,0.1) 25%, transparent 25%),
          linear-gradient(45deg, transparent 75%, rgba(168,85,247,0.1) 75%),
          linear-gradient(-45deg, transparent 75%, rgba(168,85,247,0.1) 75%),
          linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%)
        `
        styles.backgroundSize = '40px 40px, 40px 40px, 40px 40px, 40px 40px, 100% 100%'
      }
      break
    case 'animated':
      if (data.animation === 'fire-particles') {
        styles.background = `
          radial-gradient(circle at 50% 100%, rgba(255,100,0,0.4) 0%, transparent 50%),
          radial-gradient(circle at 30% 80%, rgba(255,50,0,0.3) 0%, transparent 40%),
          radial-gradient(circle at 70% 90%, rgba(255,150,0,0.3) 0%, transparent 45%),
          linear-gradient(to top, #1a0a00 0%, #0d0d0d 60%, #1a1a2e 100%)
        `
        className = 'animate-fire-pulse'
      }
      break
  }

  return { styles, className }
}

interface NameColorResult {
  type: 'solid' | 'gradient' | 'animated'
  color?: string
  gradient?: string[]
  animation?: string
}

function getNameColorData(nameColor: ShopItemPublic | null): NameColorResult {
  if (!nameColor?.asset_data) {
    return { type: 'solid', color: '#ffffff' }
  }

  const data = nameColor.asset_data as {
    style?: string
    color?: string
    gradient?: string[]
    animation?: string
  }

  if (data.style === 'gradient' && data.gradient) {
    return { type: 'gradient', gradient: data.gradient }
  }
  if (data.style === 'animated') {
    return { type: 'animated', animation: data.animation }
  }
  return { type: 'solid', color: data.color || '#ffffff' }
}

function getTitleData(title: ShopItemPublic | null): { text: string; color: string } | null {
  if (!title?.asset_data) return null
  const data = title.asset_data as { text?: string; color?: string }
  if (!data.text) return null
  return { text: data.text, color: data.color || '#ffffff' }
}

function getFrameStyles(frame: ShopItemPublic | null): React.CSSProperties {
  if (!frame?.asset_data) return {}

  const data = frame.asset_data as {
    border_color?: string
    gradient?: string[]
    glow_color?: string
  }

  const styles: React.CSSProperties = {}

  if (data.gradient && data.gradient.length > 0) {
    styles.background = `linear-gradient(45deg, ${data.gradient.join(', ')})`
    styles.backgroundSize = '400% 400%'
  } else if (data.border_color) {
    styles.background = data.border_color
  }

  if (data.glow_color) {
    styles.boxShadow = `0 0 20px ${data.glow_color}, 0 0 40px ${data.glow_color}40`
  }

  return styles
}

function getFrameAnimation(frame: ShopItemPublic | null): string {
  if (!frame?.asset_data) return ''
  const data = frame.asset_data as { animation?: string }
  if (data.animation === 'fire-pulse') return 'animate-fire-pulse'
  if (data.animation === 'rainbow-rotate') return 'animate-rainbow-rotate'
  return ''
}

// ============ HERO AVATAR COMPONENT ============

function HeroAvatar({
  avatarUrl,
  telegramAvatarUrl,
  nickname,
  frame,
}: {
  avatarUrl: string | null
  telegramAvatarUrl: string | null
  nickname: string
  frame: ShopItemPublic | null
}) {
  const displayAvatar = avatarUrl || telegramAvatarUrl

  const avatarContent = (
    <div className="w-28 h-28 md:w-36 md:h-36 rounded-2xl overflow-hidden bg-dark-700/80 backdrop-blur-sm">
      {displayAvatar ? (
        <img
          src={displayAvatar}
          alt={nickname}
          className="w-full h-full object-cover"
        />
      ) : (
        <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-neon-500/20 to-accent-500/20">
          <User className="w-14 h-14 text-gray-500" />
        </div>
      )}
    </div>
  )

  if (!frame) {
    return (
      <div className="rounded-2xl border-2 border-neon-500/50 shadow-[0_0_30px_rgba(34,211,238,0.15)]">
        {avatarContent}
      </div>
    )
  }

  return (
    <div
      className={clsx(
        'rounded-2xl p-1.5',
        getFrameAnimation(frame)
      )}
      style={getFrameStyles(frame)}
    >
      {avatarContent}
    </div>
  )
}

// ============ MAIN COMPONENT ============

export function UserProfilePage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const currentUser = useAuthStore((state) => state.user)

  const [profile, setProfile] = useState<UserProfilePublic | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [avatarBlobUrl, setAvatarBlobUrl] = useState<string | null>(null)

  useEffect(() => {
    if (!id) return

    const userId = parseInt(id)

    // Редирект на свой профиль
    if (currentUser && userId === currentUser.id) {
      navigate('/profile', { replace: true })
      return
    }

    loadProfile(userId)
  }, [id, currentUser, navigate])

  // Загрузка аватарки через API
  useEffect(() => {
    if (profile?.id && profile?.avatar_url) {
      loadAvatar(profile.id)
    }
    return () => {
      if (avatarBlobUrl) {
        URL.revokeObjectURL(avatarBlobUrl)
      }
    }
  }, [profile?.id, profile?.avatar_url])

  const loadAvatar = async (userId: number) => {
    try {
      const url = await usersApi.getAvatarUrl(userId)
      setAvatarBlobUrl(url)
    } catch {
      setAvatarBlobUrl(null)
    }
  }

  const loadProfile = async (userId: number) => {
    setIsLoading(true)
    setError(null)
    try {
      const data = await usersApi.getProfile(userId)
      setProfile(data)
    } catch (err: unknown) {
      const error = err as { response?: { status?: number } }
      if (error.response?.status === 404) {
        setError('Пользователь не найден')
      } else {
        setError('Не удалось загрузить профиль')
      }
    } finally {
      setIsLoading(false)
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ru-RU', {
      day: 'numeric',
      month: 'long',
      year: 'numeric',
    })
  }

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-24">
        <Loader2 className="w-12 h-12 animate-spin text-neon-500 mb-4" />
        <p className="text-gray-400">Загрузка профиля...</p>
      </div>
    )
  }

  if (error || !profile) {
    return (
      <div className="max-w-2xl mx-auto">
        <GlassCard className="py-12 text-center">
          <div className="w-20 h-20 mx-auto mb-4 rounded-2xl bg-dark-700 flex items-center justify-center">
            <User className="w-10 h-10 text-gray-600" />
          </div>
          <h2 className="text-xl font-bold text-white mb-2">
            {error || 'Пользователь не найден'}
          </h2>
          <Link to="/" className="text-neon-400 hover:text-neon-300 transition-colors">
            Вернуться на главную
          </Link>
        </GlassCard>
      </div>
    )
  }

  // Get cosmetics data
  const backgroundData = getBackgroundData(profile.equipped_background)
  const nameColorData = getNameColorData(profile.equipped_name_color)
  const titleData = getTitleData(profile.equipped_title)
  const displayAvatar = avatarBlobUrl || profile.telegram_avatar_url

  // Get nickname styles based on color type
  const getNicknameStyles = (): React.CSSProperties => {
    if (nameColorData.type === 'solid') {
      return { color: nameColorData.color }
    }
    if (nameColorData.type === 'gradient' && nameColorData.gradient) {
      return {
        background: `linear-gradient(90deg, ${nameColorData.gradient.join(', ')})`,
        WebkitBackgroundClip: 'text',
        WebkitTextFillColor: 'transparent',
        backgroundClip: 'text',
      }
    }
    if (nameColorData.type === 'animated') {
      return {
        background: 'linear-gradient(90deg, #ff0000, #ff7f00, #ffff00, #00ff00, #0000ff, #4b0082, #9400d3, #ff0000)',
        backgroundSize: '400% 100%',
        WebkitBackgroundClip: 'text',
        WebkitTextFillColor: 'transparent',
        backgroundClip: 'text',
      }
    }
    return { color: '#ffffff' }
  }

  const getNicknameAnimation = (): string => {
    if (nameColorData.type === 'animated' && nameColorData.animation === 'rainbow-shift') {
      return 'animate-rainbow-rotate'
    }
    return ''
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      {/* Кнопка назад */}
      <button
        onClick={() => navigate(-1)}
        className="flex items-center gap-2 text-gray-400 hover:text-neon-400 transition-colors group"
      >
        <ArrowLeft className="w-5 h-5 group-hover:-translate-x-1 transition-transform" />
        Назад
      </button>

      {/* ============ HERO SECTION ============ */}
      <div
        className={clsx(
          'relative rounded-3xl overflow-hidden',
          backgroundData.className
        )}
        style={backgroundData.styles}
      >
        {/* Default gradient background if no custom background */}
        {!profile.equipped_background && (
          <div className="absolute inset-0 bg-gradient-to-br from-dark-800 via-dark-900 to-neon-900/20" />
        )}

        {/* Overlay for readability */}
        <div className="absolute inset-0 bg-gradient-to-t from-dark-900/90 via-dark-900/40 to-transparent" />

        {/* Scan lines effect */}
        <div className="absolute inset-0 bg-[linear-gradient(transparent_50%,rgba(0,0,0,0.03)_50%)] bg-[length:100%_4px] pointer-events-none" />

        {/* Glow effects */}
        <div className="absolute top-0 left-1/4 w-96 h-96 bg-neon-500/10 rounded-full blur-3xl pointer-events-none" />
        <div className="absolute bottom-0 right-1/4 w-64 h-64 bg-accent-500/10 rounded-full blur-3xl pointer-events-none" />

        {/* Content */}
        <div className="relative z-10 px-6 py-10 md:px-10 md:py-14">
          <div className="flex flex-col md:flex-row items-center gap-6 md:gap-10">
            {/* Avatar with Frame */}
            <div className="flex-shrink-0">
              <HeroAvatar
                avatarUrl={displayAvatar}
                telegramAvatarUrl={profile.telegram_avatar_url}
                nickname={profile.nickname}
                frame={profile.equipped_frame}
              />
            </div>

            {/* User Info */}
            <div className="flex-1 text-center md:text-left">
              {/* Nickname with color + Title badge */}
              <div className="flex flex-wrap items-center justify-center md:justify-start gap-3 mb-3">
                <h1
                  className={clsx(
                    'text-3xl md:text-4xl font-bold font-display tracking-wide drop-shadow-[0_0_10px_rgba(255,255,255,0.3)]',
                    getNicknameAnimation()
                  )}
                  style={getNicknameStyles()}
                >
                  {profile.nickname}
                </h1>

                {/* Title badge */}
                {titleData && (
                  <span
                    className="px-3 py-1 rounded-full text-sm font-semibold border backdrop-blur-sm"
                    style={{
                      color: titleData.color,
                      borderColor: `${titleData.color}50`,
                      backgroundColor: `${titleData.color}15`,
                      boxShadow: `0 0 15px ${titleData.color}30`
                    }}
                  >
                    {titleData.text}
                  </span>
                )}
              </div>

              {/* Admin badge */}
              {profile.role === 'admin' && (
                <div className="flex justify-center md:justify-start mb-3">
                  <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-purple-500/20 border border-purple-500/30 text-purple-400 text-sm font-medium">
                    <Shield className="w-4 h-4" />
                    Администратор
                  </div>
                </div>
              )}

              {/* Registration date */}
              <div className="flex items-center justify-center md:justify-start gap-2 text-gray-400 text-sm mb-4">
                <Calendar className="w-4 h-4 text-accent-400" />
                <span>Зарегистрирован {formatDate(profile.created_at)}</span>
              </div>

              {/* Quick stats preview */}
              <div className="flex flex-wrap items-center justify-center md:justify-start gap-4 text-sm text-gray-300">
                <div className="flex items-center gap-1.5">
                  <Trophy className="w-4 h-4 text-yellow-500" />
                  <span>{profile.stats.wins_count} побед</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <Target className="w-4 h-4 text-neon-400" />
                  <span>{profile.stats.marathons_count} марафонов</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <Flame className="w-4 h-4 text-orange-400" />
                  <span>{profile.stats.total_points_earned} очков</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Статистика */}
      <GlassCard>
        <div className="flex items-center gap-3 mb-6">
          <div className="w-10 h-10 rounded-xl bg-yellow-500/20 flex items-center justify-center">
            <Trophy className="w-5 h-5 text-yellow-400" />
          </div>
          <div>
            <h2 className="font-semibold text-white">Статистика</h2>
            <p className="text-sm text-gray-400">Достижения игрока</p>
          </div>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <StatsCard
            label="Марафонов"
            value={profile.stats.marathons_count}
            icon={<Target className="w-6 h-6" />}
            color="neon"
          />
          <StatsCard
            label="Побед"
            value={profile.stats.wins_count}
            icon={<Trophy className="w-6 h-6" />}
            color="purple"
          />
          <StatsCard
            label="Заданий"
            value={profile.stats.completed_assignments}
            icon={<CheckCircle className="w-6 h-6" />}
            color="default"
          />
          <StatsCard
            label="Очков"
            value={profile.stats.total_points_earned}
            icon={<Flame className="w-6 h-6" />}
            color="pink"
          />
        </div>
      </GlassCard>
    </div>
  )
}
