'use client'

import { googleOAuth, type GoogleCredentialResponse } from '@/lib/oauth/google'
import { SocialButton } from './SocialButton'
import { toast } from 'sonner'
import { useEffect, useState, 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 GoogleButton = () => {
  const login = useLogin()
  const router = useRouter()
  const searchParams = useSearchParams()
  const redirect = searchParams.get('redirect')
  const [isLoading, setIsLoading] = useState(false)
  const buttonRef = useRef<HTMLDivElement>(null)
  const isInitializedRef = useRef(false)

  // 处理 Google ID Token 回调
  const handleGoogleResponse = async (response: GoogleCredentialResponse) => {
    try {
      setIsLoading(true)

      // 使用 ID Token (JWT) 调用后端登录接口
      const deviceId = tokenManager.getDeviceId()
      const loginData = {
        appClient: AppClient.Web,
        deviceCode: deviceId,
        thirdToken: response.credential, // Google ID Token (JWT)
        thirdType: ThirdType.Google,
      }

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

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

          const loginRedirectUrl = sessionStorage.getItem('login_redirect_url')
          sessionStorage.removeItem('login_redirect_url')

          // 重定向到首页或指定页面
          if (loginRedirectUrl) {
            router.push(loginRedirectUrl)
          } else {
            router.push('/')
          }
        },
        onError: (error) => {
          console.error('Login error:', error)
          toast.error('Login failed')
          setIsLoading(false)
        },
      })
    } catch (error) {
      console.error('Google login error:', error)
      toast.error('Google login failed')
      setIsLoading(false)
    }
  }

  // 加载 Google Identity Services SDK 并渲染按钮
  useEffect(() => {
    const loadAndInitGoogleButton = async () => {
      try {
        if (isInitializedRef.current || !buttonRef.current) return

        await googleOAuth.loadScript()

        // 使用 Google 提供的标准按钮，这种方式会自动处理未登录的情况
        if (window.google?.accounts?.id && buttonRef.current) {
          googleOAuth.renderButton(buttonRef.current, handleGoogleResponse, {
            type: 'standard',
            theme: 'outline',
            size: 'large',
            text: 'continue_with',
            width: buttonRef.current.offsetWidth.toString(),
          })
          isInitializedRef.current = true
          console.log('Google Sign-In button rendered')
        }
      } catch (error) {
        console.error('Failed to load Google SDK:', error)
        toast.error('Failed to load Google login')
      }
    }

    loadAndInitGoogleButton()
  }, [])

  const handleGoogleLogin = () => {
    // 保存重定向 URL
    if (typeof window !== 'undefined') {
      sessionStorage.setItem('login_redirect_url', redirect || '')
    }

    // 如果 Google 按钮已渲染，点击会自动触发
    // 如果未渲染，显示提示
    if (!isInitializedRef.current) {
      toast.error('Google login is not ready yet')
    }
  }

  return (
    <>
      {/* 隐藏的 Google 标准按钮容器 */}
      <div ref={buttonRef} style={{ display: 'none' }} />

      {/* 自定义样式的按钮，点击时触发隐藏的 Google 按钮 */}
      <SocialButton
        icon={<i className="iconfont icon-social-google !text-[20px] sm:!text-[24px]"></i>}
        onClick={() => {
          handleGoogleLogin()
          // 触发隐藏的 Google 按钮
          if (buttonRef.current) {
            const googleButton = buttonRef.current.querySelector(
              'div[role="button"]'
            ) as HTMLElement
            if (googleButton) {
              googleButton.click()
            }
          }
        }}
        disabled={login.isPending || isLoading}
      >
        {login.isPending || isLoading ? 'Signing in...' : 'Continue with Google'}
      </SocialButton>
    </>
  )
}

export default GoogleButton
