/*
 * Copyright 2025 coze-dev Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import { useEffect } from 'react';

import { useDocumentVisibility, useMemoizedFn } from 'ahooks';

import { type LoginStatus } from '../types';
import { useUserStore } from '../store/user';

/**
 * @description 用于获取用户登录状态
 * @returns 登录状态
 */
export const useLoginStatus = (): LoginStatus =>
  useUserStore(state => {
    if (state.isSettled) {
      return state.userInfo?.user_id_str ? 'logined' : 'not_login';
    }
    return 'settling';
  });

/**
 * @description 用于获取用户信息
 * @returns 用户信息
 */
export const useUserInfo = () => useUserStore(state => state.userInfo);

/**
 * @description 当前是否为错误状态
 * @returns 是否为错误状态
 */
export const useHasError = () => useUserStore(state => state.hasError);

const currentUidLSKey = 'coze_current_uid';
/**
 * 用于打开多页签情况下，探测其它页签下发生的登出事件并在当前触发提示
 * @param alert 触发提示的具体实现
 */
export const useAlterOnLogout = (alert: () => void) => {
  const visibility = useDocumentVisibility();
  const loginStatus = useLoginStatus();

  const isLogined = loginStatus === 'logined';
  const memoizedAlert = useMemoizedFn(() => {
    alert();
  });

  useEffect(() => {
    if (visibility === 'hidden' && isLogined) {
      const lastUserId = useUserStore.getState().userInfo?.user_id_str;
      // 登录态下，每次页面从后台回到前台，重新检查一次登录用户是否发生了变化
      return () => {
        const latestUserId = localStorage.getItem(currentUidLSKey);
        if (lastUserId !== latestUserId) {
          memoizedAlert();
        }
      };
    }
  }, [visibility, isLogined]);

  // 在登录态变化后，更新本地缓存状态
  useEffect(() => {
    if (loginStatus !== 'settling') {
      localStorage.setItem(
        currentUidLSKey,
        useUserStore.getState().userInfo?.user_id_str ?? '',
      );
    }
  }, [loginStatus]);
};

export const useUserLabel = () => useUserStore(state => state.userLabel);

export const useUserAuthInfo = () => useUserStore(state => state.userAuthInfos);
