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 } from '@/types'
import { GlassCard, StatsCard } from '@/components/ui'
import {
  User, Trophy, Target, CheckCircle, Flame,
  Loader2, ArrowLeft, Calendar, Zap
} from 'lucide-react'

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

  return (
    <div className="max-w-2xl 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>

      {/* Профиль */}
      <GlassCard variant="neon">
        <div className="flex items-center gap-6">
          {/* Аватар */}
          <div className="relative">
            <div className="w-24 h-24 rounded-2xl overflow-hidden bg-dark-700 border-2 border-neon-500/30 shadow-[0_0_14px_rgba(34,211,238,0.15)]">
              {avatarBlobUrl ? (
                <img
                  src={avatarBlobUrl}
                  alt={profile.nickname}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-dark-700 to-dark-800">
                  <User className="w-12 h-12 text-gray-500" />
                </div>
              )}
            </div>
            {/* Online indicator effect */}
            <div className="absolute -bottom-1 -right-1 w-6 h-6 rounded-lg bg-neon-500/20 border border-neon-500/30 flex items-center justify-center">
              <Zap className="w-3 h-3 text-neon-400" />
            </div>
          </div>

          {/* Инфо */}
          <div>
            <h1 className="text-2xl font-bold text-white mb-2">
              {profile.nickname}
            </h1>
            <div className="flex items-center gap-2 text-gray-400 text-sm">
              <Calendar className="w-4 h-4 text-accent-400" />
              <span>Зарегистрирован {formatDate(profile.created_at)}</span>
            </div>
          </div>
        </div>
      </GlassCard>

      {/* Статистика */}
      <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>
  )
}
