import { useCallback, useEffect, useState } from "react"
import { useSearchParams } from "next/navigation"
import { Flex } from "@mantine/core"
import { useLoginStore } from "@/components/login/store"
import { APP_ID, APP_SECRECT, qr_load, qr_login } from "./util"
import {
  APP,
  PLATFORM,
  TENANT,
  getQueryVariable,
} from "@/components/login/libs/common"
import { fetchFeishuLogin } from "../api"

const QrLogin = ({ 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 searchParams = useSearchParams()
  const renderCode = useCallback(async () => {
    await qr_load()
    qr_login(
      APP_ID,
      redirect_url,
      getQueryVariable("app_id") || searchParams.get("app_id") || ""
    )
  }, [redirect_url, searchParams])

  const [times, setTimes] = useState(0)

  const callbackUrl = useCallback(() => {
    times !== 2 && setTimes(times + 1)
  }, [times])

  const { setUserInfo, refreshToken } = useUserStore()

  const feishuLogin = useCallback(async () => {
    try {
      const params = {
        code: getQueryVariable("code") || "",
        redirect_uri: redirect_url,
        tenant: TENANT,
        platform: PLATFORM,
        app: APP,
        fingerprint,
        app_id: APP_ID,
        app_secret: APP_SECRECT,
      }
      const res = await fetchFeishuLogin(params)
      const info = res.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)
    }
  }, [fingerprint, redirect_url, refreshToken, setUserInfo])

  useEffect(() => {
    if (times === 1) {
      renderCode()
      if (getQueryVariable("code")) {
        fingerprint && feishuLogin()
      }
    }
  }, [feishuLogin, fingerprint, renderCode, times])

  useEffect(() => {
    callbackUrl()
  }, [callbackUrl])

  return (
    <Flex align="center" justify="center" w={"100%"} h={"100%"}>
      <div
        id={"login_container"}
        style={{
          width: "200px",
          height: "210px",
          display: "flex",
          justifyContent: "center",
          scale: 0.7,
        }}></div>
    </Flex>
  )
}
export default QrLogin
