import { useState, useEffect } from 'react'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { marathonsApi } from '@/api'
import type { MarathonPublicInfo } from '@/types'
import { useAuthStore } from '@/store/auth'
import { Button, Card, CardContent, CardHeader, CardTitle } from '@/components/ui'
import { Users, Loader2, Trophy, UserPlus, LogIn } from 'lucide-react'

export function InvitePage() {
  const { code } = useParams<{ code: string }>()
  const navigate = useNavigate()
  const { isAuthenticated, setPendingInviteCode } = useAuthStore()

  const [marathon, setMarathon] = useState<MarathonPublicInfo | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isJoining, setIsJoining] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    loadMarathon()
  }, [code])

  const loadMarathon = async () => {
    if (!code) return

    try {
      const data = await marathonsApi.getByCode(code)
      setMarathon(data)
    } catch {
      setError('Марафон не найден или ссылка недействительна')
    } finally {
      setIsLoading(false)
    }
  }

  const handleJoin = async () => {
    if (!code) return

    setIsJoining(true)
    try {
      const joined = await marathonsApi.join(code)
      navigate(`/marathons/${joined.id}`)
    } catch (err: unknown) {
      const apiError = err as { response?: { data?: { detail?: string } } }
      const detail = apiError.response?.data?.detail
      if (detail === 'Already joined this marathon') {
        // Already a member, just redirect
        navigate(`/marathons/${marathon?.id}`)
      } else {
        setError(detail || 'Не удалось присоединиться')
      }
    } finally {
      setIsJoining(false)
    }
  }

  const handleAuthRedirect = (path: string) => {
    if (code) {
      setPendingInviteCode(code)
    }
    navigate(path)
  }

  if (isLoading) {
    return (
      <div className="flex justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-primary-500" />
      </div>
    )
  }

  if (error || !marathon) {
    return (
      <div className="max-w-md mx-auto">
        <Card>
          <CardContent className="text-center py-8">
            <div className="text-red-400 mb-4">{error || 'Марафон не найден'}</div>
            <Link to="/marathons">
              <Button variant="secondary">К списку марафонов</Button>
            </Link>
          </CardContent>
        </Card>
      </div>
    )
  }

  const statusText = {
    preparing: 'Подготовка',
    active: 'Активен',
    finished: 'Завершён',
  }[marathon.status]

  return (
    <div className="max-w-md mx-auto">
      <Card>
        <CardHeader className="text-center">
          <CardTitle className="flex items-center justify-center gap-2">
            <Trophy className="w-6 h-6 text-primary-500" />
            Приглашение в марафон
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Marathon info */}
          <div className="text-center">
            <h2 className="text-2xl font-bold text-white mb-2">{marathon.title}</h2>
            {marathon.description && (
              <p className="text-gray-400 text-sm mb-4">{marathon.description}</p>
            )}
            <div className="flex items-center justify-center gap-4 text-sm text-gray-400">
              <span className="flex items-center gap-1">
                <Users className="w-4 h-4" />
                {marathon.participants_count} участников
              </span>
              <span className={`px-2 py-0.5 rounded text-xs ${
                marathon.status === 'active' ? 'bg-green-900/50 text-green-400' :
                marathon.status === 'preparing' ? 'bg-yellow-900/50 text-yellow-400' :
                'bg-gray-700 text-gray-400'
              }`}>
                {statusText}
              </span>
            </div>
            <p className="text-gray-500 text-xs mt-2">
              Организатор: {marathon.creator_nickname}
            </p>
          </div>

          {marathon.status === 'finished' ? (
            <div className="text-center text-gray-400">
              Этот марафон уже завершён
            </div>
          ) : isAuthenticated ? (
            /* Authenticated - show join button */
            <Button
              className="w-full"
              onClick={handleJoin}
              isLoading={isJoining}
            >
              <UserPlus className="w-4 h-4 mr-2" />
              Присоединиться к марафону
            </Button>
          ) : (
            /* Not authenticated - show login/register options */
            <div className="space-y-3">
              <p className="text-center text-gray-400 text-sm">
                Чтобы присоединиться, войдите или зарегистрируйтесь
              </p>
              <Button
                className="w-full"
                onClick={() => handleAuthRedirect('/login')}
              >
                <LogIn className="w-4 h-4 mr-2" />
                Войти
              </Button>
              <Button
                variant="secondary"
                className="w-full"
                onClick={() => handleAuthRedirect('/register')}
              >
                <UserPlus className="w-4 h-4 mr-2" />
                Зарегистрироваться
              </Button>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
