import React, { useEffect, useState } from 'react';

const Login = () => {
  const [userInfo, setUserInfo] = useState(null);
  const lang = window.navigator.language;

  useEffect(() => {
    const apiAuth = async () => {
      console.log("start apiAuth");

      if (!window.h5sdk) {
        console.log("invalid h5sdk");
        alert("please open in feishu");
        return;
      }

      const url = encodeURIComponent(location.href.split("#")[0]);
      console.log("接入方前端将需要鉴权的url发给接入方服务端,url为:", url);

      try {
        const response = await fetch(`/get_config_parameters?url=${url}`);
        const res = await response.json();

        console.log(
          "接入方服务端返回给接入方前端的结果(前端调用config接口的所需参数):", res
        );

        window.h5sdk.error((err) => {
          console.error("h5sdk error:", JSON.stringify(err));
        });

        window.h5sdk.config({
          appId: res.appid,
          timestamp: res.timestamp,
          nonceStr: res.noncestr,
          signature: res.signature,
          jsApiList: [],
          onSuccess: (res) => {
            console.log(`config success: ${JSON.stringify(res)}`);
          },
          onFail: (err) => {
            console.error(`config failed: ${JSON.stringify(err)}`);
          },
        });

        window.h5sdk.ready(() => {
          // 获取用户信息
          window.tt.getUserInfo({
            success: (res) => {
              console.log(`getUserInfo success: ${JSON.stringify(res)}`);
              setUserInfo(res.userInfo);
              localStorage.setItem('userInfo', JSON.stringify(res.userInfo));
            },
            fail: (err) => {
              console.log(`getUserInfo failed:`, JSON.stringify(err));
            },
          });

          // 显示Toast
          window.tt.showToast({
            title: "鉴权成功",
            icon: "success",
            duration: 3000,
            success(res) {
              console.log("showToast 调用成功", res.errMsg);

            },
            fail(res) {
              // console.log("showToast 调用失败", res.errMsg);
            },
            complete(res) {
              // console.log("showToast 调用结束", res.errMsg);
            },
          });
        });
      } catch (e) {
        console.error("fetch error:", e);
      }
    };

    apiAuth();
  }, []);

  const renderUserInfo = () => {
    if (!userInfo) return null;

    const name =
      lang === 'zh_CN' || lang === 'zh-CN'
        ? userInfo.nickName
        : userInfo.i18nName?.en_us;

    const welcomeText =
      lang === 'zh_CN' || lang === 'zh-CN'
        ? '欢迎使用飞书'
        : 'Welcome to Feishu';

    return (
      // <div>
      //   <div id="img_div">
      //     <img src={userInfo.avatarUrl} alt="avatar" style={{ width: '100%' }} />
      //   </div>
      //   <h2 id="hello_text_name">{name}</h2>
      //   <p id="hello_text_welcome">{welcomeText}</p>
      // </div>
      <></>
    );
  };

  return (
    <div>
      {/* <h1>Feishu 鉴权 Demo</h1>
      {renderUserInfo()} */}
    </div>
  );
};

export default Login;
