import { useState, useEffect, useRef } from 'react'
import { MessageCircle, ExternalLink, X, Loader2, RefreshCw, CheckCircle, User, Link2, Link2Off } from 'lucide-react'
import { telegramApi } from '@/api/telegram'
import { authApi } from '@/api/auth'
import { useAuthStore } from '@/store/auth'

export function TelegramLink() {
  const { user, updateUser } = useAuthStore()
  const [isOpen, setIsOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const [botUrl, setBotUrl] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [isPolling, setIsPolling] = useState(false)
  const [linkSuccess, setLinkSuccess] = useState(false)
  const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null)

  const isLinked = !!user?.telegram_id

  // Cleanup polling on unmount
  useEffect(() => {
    return () => {
      if (pollingRef.current) {
        clearInterval(pollingRef.current)
      }
    }
  }, [])

  const startPolling = () => {
    setIsPolling(true)
    let attempts = 0
    const maxAttempts = 60 // 5 minutes (5 sec intervals)

    pollingRef.current = setInterval(async () => {
      attempts++
      try {
        const userData = await authApi.me()
        if (userData.telegram_id) {
          // Success! User linked their account
          updateUser({
            telegram_id: userData.telegram_id,
            telegram_username: userData.telegram_username,
            telegram_first_name: userData.telegram_first_name,
            telegram_last_name: userData.telegram_last_name,
            telegram_avatar_url: userData.telegram_avatar_url
          })
          setLinkSuccess(true)
          setIsPolling(false)
          setBotUrl(null)
          if (pollingRef.current) {
            clearInterval(pollingRef.current)
          }
        }
      } catch {
        // Ignore errors, continue polling
      }

      if (attempts >= maxAttempts) {
        setIsPolling(false)
        if (pollingRef.current) {
          clearInterval(pollingRef.current)
        }
      }
    }, 5000)
  }

  const stopPolling = () => {
    setIsPolling(false)
    if (pollingRef.current) {
      clearInterval(pollingRef.current)
    }
  }

  const handleGenerateLink = async () => {
    setLoading(true)
    setError(null)
    setLinkSuccess(false)
    try {
      const { bot_url } = await telegramApi.generateLinkToken()
      setBotUrl(bot_url)
    } catch {
      setError('Не удалось сгенерировать ссылку')
    } finally {
      setLoading(false)
    }
  }

  const handleUnlink = async () => {
    setLoading(true)
    setError(null)
    try {
      await telegramApi.unlinkTelegram()
      updateUser({
        telegram_id: null,
        telegram_username: null,
        telegram_first_name: null,
        telegram_last_name: null,
        telegram_avatar_url: null
      })
      setIsOpen(false)
    } catch {
      setError('Не удалось отвязать аккаунт')
    } finally {
      setLoading(false)
    }
  }

  const handleOpenBot = () => {
    if (botUrl) {
      window.open(botUrl, '_blank')
      startPolling()
    }
  }

  const handleClose = () => {
    setIsOpen(false)
    setBotUrl(null)
    setError(null)
    setLinkSuccess(false)
    stopPolling()
  }

  return (
    <>
      <button
        onClick={() => setIsOpen(true)}
        className={`p-2 rounded-lg transition-colors ${
          isLinked
            ? 'text-blue-400 hover:text-blue-300 hover:bg-dark-700'
            : 'text-gray-400 hover:text-white hover:bg-dark-700'
        }`}
        title={isLinked ? 'Telegram привязан' : 'Привязать Telegram'}
      >
        <MessageCircle className="w-5 h-5" />
      </button>

      {isOpen && (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-xl max-w-md w-full p-6 relative border border-dark-600">
            <button
              onClick={handleClose}
              className="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors"
            >
              <X className="w-5 h-5" />
            </button>

            <div className="flex items-center gap-3 mb-6">
              <div className="w-12 h-12 bg-blue-500/10 rounded-full flex items-center justify-center border border-blue-500/30">
                <MessageCircle className="w-6 h-6 text-blue-400" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-white">Telegram</h2>
                <p className="text-sm text-gray-400">
                  {isLinked ? 'Аккаунт привязан' : 'Привяжи аккаунт'}
                </p>
              </div>
            </div>

            {error && (
              <div className="mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-red-400 text-sm">
                {error}
              </div>
            )}

            {isLinked || linkSuccess ? (
              <div className="space-y-4">
                {linkSuccess && (
                  <div className="p-4 bg-green-500/20 border border-green-500/50 rounded-lg flex items-center gap-3">
                    <CheckCircle className="w-6 h-6 text-green-400 flex-shrink-0" />
                    <p className="text-green-400 font-medium">Аккаунт успешно привязан!</p>
                  </div>
                )}

                {/* User Profile Card */}
                <div className="p-4 bg-dark-700/50 rounded-xl border border-dark-600">
                  <div className="flex items-center gap-4">
                    {/* Avatar - Telegram avatar */}
                    <div className="relative">
                      {user?.telegram_avatar_url ? (
                        <img
                          src={user.telegram_avatar_url}
                          alt={user.nickname}
                          className="w-12 h-12 rounded-full object-cover border-2 border-blue-500/50"
                        />
                      ) : (
                        <div className="w-12 h-12 rounded-full bg-gradient-to-br from-blue-500 to-accent-500 flex items-center justify-center border-2 border-blue-500/50">
                          <User className="w-6 h-6 text-white" />
                        </div>
                      )}
                      {/* Link indicator */}
                      <div className="absolute -bottom-1 -right-1 w-5 h-5 bg-green-500 rounded-full flex items-center justify-center border-2 border-dark-800">
                        <Link2 className="w-2.5 h-2.5 text-white" />
                      </div>
                    </div>

                    {/* User Info */}
                    <div className="flex-1 min-w-0">
                      <p className="text-lg font-bold text-white truncate">
                        {[user?.telegram_first_name, user?.telegram_last_name].filter(Boolean).join(' ') || user?.nickname}
                      </p>
                      {user?.telegram_username && (
                        <p className="text-blue-400 font-medium truncate">@{user.telegram_username}</p>
                      )}
                    </div>
                  </div>
                </div>

                {/* Notifications Info */}
                <div className="p-4 bg-dark-700/30 rounded-lg border border-dark-600/50">
                  <p className="text-sm text-gray-300 font-medium mb-3">Уведомления включены:</p>
                  <div className="grid grid-cols-1 gap-2">
                    <div className="flex items-center gap-2 text-sm text-gray-400">
                      <span className="text-yellow-400">🌟</span>
                      <span>События (Golden Hour, Jackpot)</span>
                    </div>
                    <div className="flex items-center gap-2 text-sm text-gray-400">
                      <span className="text-green-400">🚀</span>
                      <span>Старт и финиш марафонов</span>
                    </div>
                    <div className="flex items-center gap-2 text-sm text-gray-400">
                      <span className="text-red-400">⚠️</span>
                      <span>Споры по заданиям</span>
                    </div>
                  </div>
                </div>

                <button
                  onClick={handleUnlink}
                  disabled={loading}
                  className="w-full py-3 px-4 bg-red-500/10 hover:bg-red-500/20 text-red-400 rounded-lg font-medium transition-colors disabled:opacity-50 flex items-center justify-center gap-2 border border-red-500/30"
                >
                  {loading ? (
                    <Loader2 className="w-5 h-5 animate-spin" />
                  ) : (
                    <>
                      <Link2Off className="w-4 h-4" />
                      Отвязать аккаунт
                    </>
                  )}
                </button>
              </div>
            ) : botUrl ? (
              <div className="space-y-4">
                {isPolling ? (
                  <>
                    <div className="p-4 bg-blue-500/20 border border-blue-500/50 rounded-lg">
                      <div className="flex items-center gap-3 mb-2">
                        <RefreshCw className="w-5 h-5 text-blue-400 animate-spin" />
                        <p className="text-blue-400 font-medium">Ожидание привязки...</p>
                      </div>
                      <p className="text-sm text-gray-400">
                        Открой бота в Telegram и нажми Start. Статус обновится автоматически.
                      </p>
                    </div>

                    <button
                      onClick={handleOpenBot}
                      className="w-full py-3 px-4 bg-blue-500/20 hover:bg-blue-500/30 text-blue-400 border border-blue-500/50 hover:border-blue-500 rounded-lg font-medium transition-all duration-200 flex items-center justify-center gap-2"
                    >
                      <ExternalLink className="w-5 h-5" />
                      Открыть Telegram снова
                    </button>
                  </>
                ) : (
                  <>
                    <p className="text-gray-300">
                      Нажми кнопку ниже, чтобы открыть бота и завершить привязку:
                    </p>

                    <button
                      onClick={handleOpenBot}
                      className="w-full py-3 px-4 bg-blue-500/20 hover:bg-blue-500/30 text-blue-400 border border-blue-500/50 hover:border-blue-500 rounded-lg font-medium transition-all duration-200 flex items-center justify-center gap-2"
                    >
                      <ExternalLink className="w-5 h-5" />
                      Открыть Telegram
                    </button>

                    <p className="text-sm text-gray-400 text-center">
                      Ссылка действительна 10 минут
                    </p>
                  </>
                )}
              </div>
            ) : (
              <div className="space-y-4">
                <p className="text-gray-300">
                  Привяжи Telegram, чтобы получать уведомления о важных событиях:
                </p>

                <ul className="text-sm text-gray-400 space-y-2">
                  <li className="flex items-center gap-2">
                    <span className="text-yellow-400">🌟</span>
                    Golden Hour - очки x1.5
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="text-yellow-400">🎰</span>
                    Jackpot - очки x3
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="text-yellow-400">⚡</span>
                    Double Risk и другие события
                  </li>
                </ul>

                <button
                  onClick={handleGenerateLink}
                  disabled={loading}
                  className="w-full py-3 px-4 bg-blue-500/20 hover:bg-blue-500/30 text-blue-400 border border-blue-500/50 hover:border-blue-500 rounded-lg font-medium transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {loading ? (
                    <Loader2 className="w-5 h-5 animate-spin" />
                  ) : (
                    <>
                      <MessageCircle className="w-5 h-5" />
                      Привязать Telegram
                    </>
                  )}
                </button>
              </div>
            )}
          </div>
        </div>
      )}
    </>
  )
}
