"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 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")
          
          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 loadAndInitGoogleSDK = async () => {
      try {
        if (isInitializedRef.current) return
        
        await googleOAuth.loadScript()
        
        // 初始化 Google Identity
        if (window.google?.accounts?.id) {
          googleOAuth.initGoogleId(handleGoogleResponse)
          isInitializedRef.current = true
          console.log('Google Identity Services initialized')
        }
      } catch (error) {
        console.error('Failed to load Google SDK:', error)
        toast.error("Failed to load Google login")
      }
    }

    loadAndInitGoogleSDK()
  }, [handleGoogleResponse])

  const handleGoogleLogin = async () => {
    try {
      setIsLoading(true)

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

      // 确保 SDK 已加载并初始化
      if (!window.google?.accounts?.id) {
        await googleOAuth.loadScript()
        googleOAuth.initGoogleId(handleGoogleResponse)
      }

      // 触发 One Tap 登录流程
      if (window.google?.accounts?.id) {
        window.google.accounts.id.prompt((notification) => {
          if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
            console.log('One Tap not displayed:', notification.getNotDisplayedReason() || notification.getSkippedReason())
            // One Tap 无法显示时,使用备选方案 (可选)
            setIsLoading(false)
          }
        })
      }
    } catch (error) {
      console.error('Google login error:', error)
      toast.error("Failed to initialize Google login")
      setIsLoading(false)
    }
  }

  return (
    <SocialButton
      icon={<i className="iconfont icon-social-google !text-[20px] sm:!text-[24px]"></i>}
      onClick={handleGoogleLogin}
      disabled={login.isPending}
    >
      {login.isPending ? "Signing in..." : "Continue with Google"}
    </SocialButton>
  );
}

export default GoogleButton;

