import { useState, useEffect } from 'react'
import { useParams, Link } from 'react-router-dom'
import { marathonsApi } from '@/api'
import type { LeaderboardEntry, ShopItemPublic, User, Marathon } from '@/types'
import { GlassCard, UserAvatar, NeonButton } from '@/components/ui'
import { useAuthStore } from '@/store/auth'
import { useToast } from '@/store/toast'
import { Trophy, Flame, ArrowLeft, Loader2, Crown, Medal, Award, Star, Zap, Target, SkipForward, X, Ban } from 'lucide-react'

// Helper to get name color styles and animation class
function getNameColorData(nameColor: ShopItemPublic | null | undefined): { styles: React.CSSProperties; className: string } {
  if (!nameColor?.asset_data) return { styles: {}, className: '' }

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

  if (data.style === 'gradient' && data.gradient) {
    return {
      styles: {
        background: `linear-gradient(90deg, ${data.gradient.join(', ')})`,
        WebkitBackgroundClip: 'text',
        WebkitTextFillColor: 'transparent',
        backgroundClip: 'text',
      },
      className: '',
    }
  }

  if (data.style === 'animated') {
    return {
      styles: {
        background: 'linear-gradient(90deg, #ff0000, #ff7f00, #ffff00, #00ff00, #0000ff, #9400d3, #ff0000)',
        backgroundSize: '400% 100%',
        WebkitBackgroundClip: 'text',
        WebkitTextFillColor: 'transparent',
        backgroundClip: 'text',
      },
      className: 'animate-rainbow-rotate',
    }
  }

  if (data.style === 'solid' && data.color) {
    return { styles: { color: data.color }, className: '' }
  }

  return { styles: {}, className: '' }
}

// Helper to get title data
function getTitleData(title: ShopItemPublic | null | undefined): { 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',
  }
}

// Styled nickname component
function StyledNickname({ user, className = '' }: { user: User; className?: string }) {
  const nameColorData = getNameColorData(user.equipped_name_color)
  const titleData = getTitleData(user.equipped_title)

  return (
    <span className={`inline-flex items-center gap-2 ${className}`}>
      <span className={nameColorData.className} style={nameColorData.styles}>{user.nickname}</span>
      {titleData && (
        <span
          className="px-1.5 py-0.5 text-xs font-medium rounded bg-dark-700/50"
          style={{ color: titleData.color }}
        >
          {titleData.text}
        </span>
      )}
    </span>
  )
}

export function LeaderboardPage() {
  const { id } = useParams<{ id: string }>()
  const user = useAuthStore((state) => state.user)
  const toast = useToast()
  const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([])
  const [marathon, setMarathon] = useState<Marathon | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  // Skip modal state
  const [skipModalUser, setSkipModalUser] = useState<User | null>(null)
  const [skipExile, setSkipExile] = useState(false)
  const [skipReason, setSkipReason] = useState('')
  const [isSkipping, setIsSkipping] = useState(false)

  const isOrganizer = marathon?.my_participation?.role === 'organizer' || user?.role === 'admin'

  useEffect(() => {
    loadData()
  }, [id])

  const loadData = async () => {
    if (!id) return
    try {
      const [leaderboardData, marathonData] = await Promise.all([
        marathonsApi.getLeaderboard(parseInt(id)),
        marathonsApi.get(parseInt(id)),
      ])
      setLeaderboard(leaderboardData)
      setMarathon(marathonData)
    } catch (error) {
      console.error('Failed to load data:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleSkip = async () => {
    if (!skipModalUser || !id) return

    setIsSkipping(true)
    try {
      await marathonsApi.skipParticipantAssignment(
        parseInt(id),
        skipModalUser.id,
        skipExile,
        skipReason || undefined
      )
      toast.success(
        skipExile
          ? `Задание ${skipModalUser.nickname} пропущено, игра изгнана`
          : `Задание ${skipModalUser.nickname} пропущено`
      )
      setSkipModalUser(null)
      setSkipExile(false)
      setSkipReason('')
      loadData()
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Не удалось пропустить задание')
    } finally {
      setIsSkipping(false)
    }
  }

  const getRankConfig = (rank: number) => {
    switch (rank) {
      case 1:
        return {
          icon: <Crown className="w-6 h-6" />,
          color: 'text-yellow-400',
          bg: 'bg-yellow-500/20',
          border: 'border-yellow-500/30',
          glow: 'shadow-[0_0_20px_rgba(234,179,8,0.3)]',
          gradient: 'from-yellow-500/20 via-transparent to-transparent',
        }
      case 2:
        return {
          icon: <Medal className="w-6 h-6" />,
          color: 'text-gray-300',
          bg: 'bg-gray-400/20',
          border: 'border-gray-400/30',
          glow: 'shadow-[0_0_15px_rgba(156,163,175,0.2)]',
          gradient: 'from-gray-400/10 via-transparent to-transparent',
        }
      case 3:
        return {
          icon: <Award className="w-6 h-6" />,
          color: 'text-amber-600',
          bg: 'bg-amber-600/20',
          border: 'border-amber-600/30',
          glow: 'shadow-[0_0_15px_rgba(217,119,6,0.2)]',
          gradient: 'from-amber-600/10 via-transparent to-transparent',
        }
      default:
        return {
          icon: <span className="text-gray-500 font-mono font-bold">{rank}</span>,
          color: 'text-gray-500',
          bg: 'bg-dark-700',
          border: 'border-dark-600',
          glow: '',
          gradient: '',
        }
    }
  }

  // Top 3 for podium
  const topThree = leaderboard.slice(0, 3)

  // Calculate stats
  const totalPoints = leaderboard.reduce((acc, e) => acc + e.total_points, 0)
  const maxStreak = Math.max(...leaderboard.map(e => e.current_streak), 0)

  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>
    )
  }

  return (
    <div className="max-w-3xl mx-auto">
      {/* Header */}
      <div className="flex items-center gap-4 mb-8">
        <Link
          to={`/marathons/${id}`}
          className="w-10 h-10 rounded-xl bg-dark-700 border border-dark-600 flex items-center justify-center text-gray-400 hover:text-white hover:border-neon-500/30 transition-all"
        >
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-white">Таблица лидеров</h1>
          <p className="text-gray-400 text-sm">Рейтинг участников марафона</p>
        </div>
      </div>

      {leaderboard.length === 0 ? (
        <GlassCard className="text-center py-16">
          <div className="w-20 h-20 mx-auto mb-6 rounded-2xl bg-dark-700 flex items-center justify-center">
            <Trophy className="w-10 h-10 text-gray-600" />
          </div>
          <h3 className="text-xl font-semibold text-white mb-2">Пока нет участников</h3>
          <p className="text-gray-400">Станьте первым в рейтинге!</p>
        </GlassCard>
      ) : (
        <>
          {/* Podium for top 3 */}
          {topThree.length >= 3 && (
            <div className="mb-8">
              <div className="flex items-end justify-center gap-4 mb-4">
                {/* 2nd place */}
                <div className="flex flex-col items-center animate-slide-in-up" style={{ animationDelay: '100ms' }}>
                  <div className="mb-3">
                    <UserAvatar
                      userId={topThree[1].user.id}
                      hasAvatar={!!topThree[1].user.avatar_url}
                      nickname={topThree[1].user.nickname}
                      size="lg"
                      frame={topThree[1].user.equipped_frame}
                      telegramAvatarUrl={topThree[1].user.telegram_avatar_url}
                    />
                  </div>
                  <Link to={`/users/${topThree[1].user.id}`} className="glass rounded-xl p-4 text-center w-32 hover:border-neon-500/30 transition-colors border border-transparent">
                    <Medal className="w-6 h-6 text-gray-300 mx-auto mb-2" />
                    <p className="text-sm font-medium truncate hover:text-neon-400 transition-colors">
                      <StyledNickname user={topThree[1].user} />
                    </p>
                    <p className="text-xs text-gray-400">{topThree[1].total_points} очков</p>
                  </Link>
                </div>

                {/* 1st place */}
                <div className="flex flex-col items-center animate-slide-in-up" style={{ animationDelay: '0ms' }}>
                  <div className="mb-3 relative">
                    <UserAvatar
                      userId={topThree[0].user.id}
                      hasAvatar={!!topThree[0].user.avatar_url}
                      nickname={topThree[0].user.nickname}
                      size="xl"
                      frame={topThree[0].user.equipped_frame}
                      telegramAvatarUrl={topThree[0].user.telegram_avatar_url}
                    />
                    <div className="absolute -top-2 -right-2 w-8 h-8 rounded-full bg-yellow-500 flex items-center justify-center shadow-lg shadow-yellow-500/50">
                      <Crown className="w-5 h-5 text-dark-900" />
                    </div>
                  </div>
                  <Link to={`/users/${topThree[0].user.id}`} className="glass-neon rounded-xl p-4 text-center w-36 hover:shadow-[0_0_20px_rgba(34,211,238,0.3)] transition-shadow">
                    <Star className="w-6 h-6 text-yellow-400 mx-auto mb-2" />
                    <p className="font-semibold truncate hover:text-neon-400 transition-colors">
                      <StyledNickname user={topThree[0].user} />
                    </p>
                    <p className="text-sm text-neon-400 font-bold">{topThree[0].total_points} очков</p>
                  </Link>
                </div>

                {/* 3rd place */}
                <div className="flex flex-col items-center animate-slide-in-up" style={{ animationDelay: '200ms' }}>
                  <div className="mb-3">
                    <UserAvatar
                      userId={topThree[2].user.id}
                      hasAvatar={!!topThree[2].user.avatar_url}
                      nickname={topThree[2].user.nickname}
                      size="lg"
                      frame={topThree[2].user.equipped_frame}
                      telegramAvatarUrl={topThree[2].user.telegram_avatar_url}
                    />
                  </div>
                  <Link to={`/users/${topThree[2].user.id}`} className="glass rounded-xl p-4 text-center w-32 hover:border-neon-500/30 transition-colors border border-transparent">
                    <Award className="w-6 h-6 text-amber-600 mx-auto mb-2" />
                    <p className="text-sm font-medium truncate hover:text-neon-400 transition-colors">
                      <StyledNickname user={topThree[2].user} />
                    </p>
                    <p className="text-xs text-gray-400">{topThree[2].total_points} очков</p>
                  </Link>
                </div>
              </div>
            </div>
          )}

          {/* Stats row */}
          <div className="grid grid-cols-3 gap-4 mb-8">
            <div className="glass rounded-xl p-4 text-center">
              <Trophy className="w-6 h-6 text-neon-400 mx-auto mb-2" />
              <p className="text-2xl font-bold text-white">{leaderboard.length}</p>
              <p className="text-xs text-gray-400">Участников</p>
            </div>
            <div className="glass rounded-xl p-4 text-center">
              <Zap className="w-6 h-6 text-accent-400 mx-auto mb-2" />
              <p className="text-2xl font-bold text-white">{totalPoints}</p>
              <p className="text-xs text-gray-400">Всего очков</p>
            </div>
            <div className="glass rounded-xl p-4 text-center">
              <Flame className="w-6 h-6 text-orange-400 mx-auto mb-2" />
              <p className="text-2xl font-bold text-white">{maxStreak}</p>
              <p className="text-xs text-gray-400">Макс. серия</p>
            </div>
          </div>

          {/* Full leaderboard */}
          <GlassCard>
            <div className="flex items-center gap-3 mb-6">
              <div className="w-10 h-10 rounded-xl bg-neon-500/20 flex items-center justify-center">
                <Target className="w-5 h-5 text-neon-400" />
              </div>
              <div>
                <h3 className="font-semibold text-white">Полный рейтинг</h3>
                <p className="text-sm text-gray-400">Все участники марафона</p>
              </div>
            </div>

            <div className="space-y-2">
              {leaderboard.map((entry, index) => {
                const isCurrentUser = entry.user.id === user?.id
                const rankConfig = getRankConfig(entry.rank)

                return (
                  <div
                    key={entry.user.id}
                    className={`
                      relative flex items-center gap-4 p-4 rounded-xl
                      transition-all duration-300 group
                      ${isCurrentUser
                        ? 'bg-neon-500/10 border border-neon-500/30 shadow-[0_0_14px_rgba(34,211,238,0.08)]'
                        : `${rankConfig.bg} border ${rankConfig.border} hover:border-neon-500/20`
                      }
                    `}
                    style={{ animationDelay: `${index * 50}ms` }}
                  >
                    {/* Gradient overlay for top 3 */}
                    {entry.rank <= 3 && (
                      <div className={`absolute inset-0 bg-gradient-to-r ${rankConfig.gradient} rounded-xl pointer-events-none`} />
                    )}

                    {/* Rank */}
                    <div className={`
                      relative w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0
                      ${rankConfig.bg} ${rankConfig.color} ${rankConfig.glow}
                    `}>
                      {rankConfig.icon}
                    </div>

                    {/* Avatar */}
                    <div className="flex-shrink-0">
                      <UserAvatar
                        userId={entry.user.id}
                        hasAvatar={!!entry.user.avatar_url}
                        nickname={entry.user.nickname}
                        size="sm"
                        frame={entry.user.equipped_frame}
                        telegramAvatarUrl={entry.user.telegram_avatar_url}
                      />
                    </div>

                    {/* User info */}
                    <div className="relative flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <Link
                          to={`/users/${entry.user.id}`}
                          className={`font-semibold truncate hover:text-neon-400 transition-colors ${isCurrentUser ? 'text-neon-400' : ''}`}
                        >
                          <StyledNickname user={entry.user} />
                        </Link>
                        {isCurrentUser && (
                          <span className="px-2 py-0.5 text-xs font-medium bg-neon-500/20 text-neon-400 rounded-full border border-neon-500/30">
                            Вы
                          </span>
                        )}
                      </div>
                      <div className="flex items-center gap-3 text-sm text-gray-400">
                        <span className="flex items-center gap-1">
                          <span className="w-1.5 h-1.5 bg-green-500 rounded-full" />
                          {entry.completed_count} выполнено
                        </span>
                        {entry.dropped_count > 0 && (
                          <span className="flex items-center gap-1">
                            <span className="w-1.5 h-1.5 bg-red-500 rounded-full" />
                            {entry.dropped_count} пропущено
                          </span>
                        )}
                      </div>
                    </div>

                    {/* Streak */}
                    {entry.current_streak > 0 && (
                      <div className="relative flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-orange-500/10 border border-orange-500/20">
                        <Flame className="w-4 h-4 text-orange-400" />
                        <span className="text-sm font-semibold text-orange-400">{entry.current_streak}</span>
                      </div>
                    )}

                    {/* Skip button for organizers */}
                    {isOrganizer && (
                      <button
                        onClick={(e) => {
                          e.preventDefault()
                          setSkipModalUser(entry.user)
                        }}
                        className="relative p-2 text-orange-400 hover:bg-orange-500/20 rounded-lg transition-colors"
                        title="Скипнуть задание"
                      >
                        <SkipForward className="w-4 h-4" />
                      </button>
                    )}

                    {/* Points */}
                    <div className="relative text-right">
                      <div className={`text-xl font-bold ${isCurrentUser ? 'text-neon-400' : 'text-white'}`}>
                        {entry.total_points}
                      </div>
                      <div className="text-xs text-gray-500">очков</div>
                    </div>
                  </div>
                )
              })}
            </div>
          </GlassCard>
        </>
      )}

      {/* Skip Modal */}
      {skipModalUser && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="glass rounded-2xl p-6 max-w-md w-full mx-4 border border-dark-600 shadow-2xl">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-lg font-semibold text-white flex items-center gap-2">
                <SkipForward className="w-5 h-5 text-orange-400" />
                Скипнуть задание {skipModalUser.nickname}
              </h3>
              <button
                onClick={() => {
                  setSkipModalUser(null)
                  setSkipExile(false)
                  setSkipReason('')
                }}
                className="p-1.5 text-gray-400 hover:text-white rounded-lg hover:bg-dark-600/50 transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Skip type */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-300 mb-3">
                Тип скипа
              </label>
              <div className="space-y-2">
                <label className="flex items-center gap-3 p-3 rounded-xl bg-dark-700/50 border border-dark-600 cursor-pointer hover:border-orange-500/30 transition-colors">
                  <input
                    type="radio"
                    name="skipType"
                    checked={!skipExile}
                    onChange={() => setSkipExile(false)}
                    className="w-4 h-4 text-orange-500 bg-dark-700 border-dark-500 focus:ring-orange-500/50"
                  />
                  <div>
                    <div className="text-white font-medium">Обычный скип</div>
                    <div className="text-sm text-gray-400">Задание пропускается, игра может выпасть снова</div>
                  </div>
                </label>
                <label className="flex items-center gap-3 p-3 rounded-xl bg-dark-700/50 border border-dark-600 cursor-pointer hover:border-red-500/30 transition-colors">
                  <input
                    type="radio"
                    name="skipType"
                    checked={skipExile}
                    onChange={() => setSkipExile(true)}
                    className="w-4 h-4 text-red-500 bg-dark-700 border-dark-500 focus:ring-red-500/50"
                  />
                  <div>
                    <div className="text-white font-medium flex items-center gap-2">
                      Скип с изгнанием
                      <Ban className="w-4 h-4 text-red-400" />
                    </div>
                    <div className="text-sm text-gray-400">Игра навсегда удаляется из пула участника</div>
                  </div>
                </label>
              </div>
            </div>

            {/* Reason */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Причина (опционально)
              </label>
              <textarea
                value={skipReason}
                onChange={(e) => setSkipReason(e.target.value)}
                placeholder="Причина скипа..."
                rows={2}
                className="w-full bg-dark-700/50 border border-dark-600 rounded-xl px-4 py-2.5 text-white placeholder:text-gray-500 focus:outline-none focus:border-orange-500/50 transition-colors resize-none"
              />
            </div>

            <div className="flex gap-3 justify-end">
              <NeonButton
                variant="ghost"
                onClick={() => {
                  setSkipModalUser(null)
                  setSkipExile(false)
                  setSkipReason('')
                }}
              >
                Отмена
              </NeonButton>
              <NeonButton
                color={skipExile ? 'pink' : 'neon'}
                onClick={handleSkip}
                disabled={isSkipping}
                isLoading={isSkipping}
                icon={<SkipForward className="w-4 h-4" />}
              >
                {skipExile ? 'Скипнуть и изгнать' : 'Скипнуть'}
              </NeonButton>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
