import { useCallback, useEffect } from "react"
import { DigitalIcon } from "../resource/icons/digital"
import { useLoginStore } from "@/components/login/store"
import { useRouter } from "next/navigation"
import { APP, PLATFORM, TENANT } from "@/components/login/libs/common"
import { APP_ID, APP_SECRECT } from "./util"
import { fetchFeishuLogin } from "../api"

const HeaderIcon = DigitalIcon

const FeishuAutoLogin = ({ useUserStore }: { useUserStore: any }) => {
  const fingerprint = useLoginStore.getState().fingerprint

  const list = window.location.href.split("/")
  const http_header =
    window.location.protocol.toLowerCase() === "https:" ? "https" : "http"

  const redirect_url =
    http_header + "://" + list[2] + `${process.env.NEXT_PUBLIC_BASE_PATH}/login`

  const { setUserInfo, refreshToken } = useUserStore()
  const router = useRouter()

  const autoLogin = useCallback(
    (
      fingerprint: any,
      redirect_url: any,
      router: any,
      setUserInfo: (arg0: any, arg1: any, arg2: any) => void
    ) => {
      if (!window.h5sdk || !window.tt) {
        console.error("Feishu H5 SDK is not available")
        setTimeout(() => {
          autoLogin(fingerprint, redirect_url, router, setUserInfo)
        }, 500)
        return
      }

      // 确保每次进到这个页面是未登录，然后触发自动登录逻辑
      window.h5sdk.ready(async () => {
        console.log("Feishu H5 SDK is ready, requesting auth code")
        window.tt.requestAuthCode({
          appId: APP_ID,
          success: async (res: any) => {
            try {
              const params = {
                code: res.code,
                redirect_uri: redirect_url,
                tenant: TENANT,
                platform: PLATFORM,
                app: APP,
                fingerprint,
                app_id: APP_ID,
                app_secret: APP_SECRECT,
              }
              const response = await fetchFeishuLogin(params)
              const info = response.message
              setUserInfo(info.tenant, info.user_info, info.rbac)
              refreshToken({
                access_token: info.access_token || "",
                refresh_token: info.refresh_token || "",
              })
              window.location.href = "/"
            } catch (err) {
              console.log(err)
            }
          },
          fail: (err: any) => {
            console.error("Failed to get auth code from Feishu:", err)
            alert(JSON.stringify(err))
          },
        })
      })
    },
    [refreshToken]
  )

  const isFeishu = useCallback(() => !!(window.h5sdk && window.tt), [])

  useEffect(() => {
    console.log("Feishu auto login effect triggered")
    autoLogin(fingerprint, redirect_url, router, setUserInfo)
  }, [fingerprint, redirect_url, router, setUserInfo, autoLogin, isFeishu])

  return (
    <div
      style={{
        width: "100%",
        height: "100%",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        flexDirection: "column",
        gap: 20,
      }}>
      <HeaderIcon />
      <span>自动登录中，请稍后...</span>
    </div>
  )
}

export default FeishuAutoLogin
