'use client'

import { discordOAuth } from '@/lib/oauth/discord'
import { SocialButton } from './SocialButton'
import { toast } from 'sonner'
import { useEffect, useRef } from 'react'
import { useLogin } from '@/hooks/auth'
import { useRouter, useSearchParams } from 'next/navigation'
import { tokenManager } from '@/lib/auth/token'
import { AppClient, ThirdType } from '@/services/auth'

const DiscordButton = () => {
  const login = useLogin()
  const router = useRouter()
  const searchParams = useSearchParams()
  const redirect = searchParams.get('redirect')

  // 处理Discord OAuth回调
  useEffect(() => {
    const discordCode = searchParams.get('discord_code')
    const discordState = searchParams.get('discord_state')
    const error = searchParams.get('error')

    // 处理错误情况
    if (error) {
      toast.error('Discord login failed')

      // 清理URL参数
      const newUrl = new URL(window.location.href)
      newUrl.searchParams.delete('error')
      router.replace(newUrl.pathname)
      return
    }

    // 处理Discord授权码
    if (discordCode) {
      // 验证state参数（可选的安全检查）
      const savedState = sessionStorage.getItem('discord_oauth_state')
      if (savedState && discordState && savedState !== discordState) {
        toast.error('Discord login failed')
        return
      }

      // 使用code调用后端登录接口
      const deviceId = tokenManager.getDeviceId()
      const loginData = {
        appClient: AppClient.Web,
        deviceCode: deviceId,
        thirdToken: discordCode, // 直接传递Discord授权码
        thirdType: ThirdType.Discord,
      }

      login.mutate(loginData, {
        onSuccess: () => {
          toast.success('Login successful')

          // 清除 Next.js 路由缓存，避免使用登录前 prefetch 的重定向响应
          router.refresh()

          // 清理URL参数和sessionStorage
          sessionStorage.removeItem('discord_oauth_state')
          const newUrl = new URL(window.location.href)
          newUrl.searchParams.delete('discord_code')
          newUrl.searchParams.delete('discord_state')
          router.replace(newUrl.pathname)

          const loginRedirectUrl = sessionStorage.getItem('login_redirect_url')

          // 重定向到首页或指定页面
          if (loginRedirectUrl) {
            router.push(loginRedirectUrl)
          } else {
            router.push('/')
          }
        },
        onError: (error) => {
          // 清理URL参数
          const newUrl = new URL(window.location.href)
          newUrl.searchParams.delete('discord_code')
          newUrl.searchParams.delete('discord_state')
          newUrl.searchParams.delete('redirect')
          router.replace(newUrl.pathname)
        },
      })
    }
  }, [])

  const handleDiscordLogin = () => {
    try {
      // 生成随机state用于安全验证
      const state = Math.random().toString(36).substring(2, 15)

      // 获取Discord授权URL
      const authUrl = discordOAuth.getAuthUrl(state)

      // 将state保存到sessionStorage用于后续验证
      if (typeof window !== 'undefined') {
        sessionStorage.setItem('discord_oauth_state', state)
        sessionStorage.setItem('login_redirect_url', redirect || '')
      }

      // 跳转到Discord授权页面
      window.location.href = authUrl
    } catch (error) {
      console.error('Discord login error:', error)
      toast.error('Discord login failed')
    }
  }

  return (
    <SocialButton
      icon={<i className="iconfont icon-social-discord !text-[24px]"></i>}
      onClick={handleDiscordLogin}
      disabled={login.isPending}
    >
      {login.isPending ? 'Signing in...' : 'Continue with Discord'}
    </SocialButton>
  )
}

export default DiscordButton
