import { useBrowser } from '@arcblock/react-hooks';
import { useCreation, useRequest } from 'ahooks';
import isNil from 'lodash/isNil';
import { LOGIN_PROVIDER } from '@arcblock/ux/lib/Util/constant';
import { getBlockletData, getFederatedEnabled, getMaster } from '@arcblock/ux/lib/Util/federated';
import { useState } from 'react';

const getAuthenticationConfig = async ({ sourceAppPid }) => {
  const blocklet = globalThis?.blocklet;
  if (!blocklet) {
    return {
      [LOGIN_PROVIDER.WALLET]: {
        order: 0,
        enabled: true,
        showQrcode: true,
      },
      [LOGIN_PROVIDER.PASSKEY]: {
        order: 1,
        enabled: true,
      },
    };
  }
  const federatedEnabled = getFederatedEnabled(blocklet);
  const master = getMaster(blocklet);
  if (federatedEnabled && master?.appPid && sourceAppPid === master?.appPid) {
    const masterBlocklet = await getBlockletData(master.appUrl);
    return masterBlocklet?.settings?.authentication || {};
  }
  return blocklet?.settings?.authentication || {};
};

const getLoginProviderList = async ({ sourceAppPid } = {}) => {
  const authenticationConfig = await getAuthenticationConfig({ sourceAppPid });
  const loginProviderList = Object.entries(authenticationConfig)
    .map(([key, value]) => {
      return { ...value, provider: key };
    })
    .filter((item) => item.enabled)
    .sort((a, b) => {
      if (!isNil(a?.order) && !isNil(b?.order)) {
        return a.order - b.order;
      }
      if (!isNil(a?.order)) {
        return -1;
      }
      return 1;
    });
  return loginProviderList;
};

export default function useProviderList({
  allowWallet = true,
  passkeyBehavior = 'none',
  action,
  sourceAppPid,
  mode = 'dialog',
  blocklet = globalThis.blocklet,
  isSmallView = false,
  lastLoginMethod = '',
}) {
  const [loadingProviderList, setLoadingProviderList] = useState(false);
  const oauthActionList = ['login', 'invite', 'connect-to-did-space', 'connect-to-did-domain', 'destroy-self'];
  const emailActionList = ['login', 'invite', 'connect-to-did-space', 'connect-to-did-domain', 'destroy-self'];
  const browser = useBrowser();

  const { data: loginProviderList = [] } = useRequest(
    async () => {
      setLoadingProviderList(true);
      const data = await getLoginProviderList({ sourceAppPid });
      setLoadingProviderList(false);
      return data;
    },
    { refreshDeps: [sourceAppPid] }
  );

  const showedLoginProviderList = useCreation(() => {
    const result = loginProviderList
      .filter((item) => {
        if (item.provider === LOGIN_PROVIDER.WALLET) {
          return allowWallet;
        }
        if (item.provider === LOGIN_PROVIDER.PASSKEY) {
          return passkeyBehavior !== 'none' && !browser.wallet && !browser.arcSphere;
        }
        if (item.provider === LOGIN_PROVIDER.EMAIL) {
          return emailActionList.includes(action) && (blocklet?.settings?.notification?.email?.enabled ?? false);
        }

        if (item.type === 'oauth') {
          if (!oauthActionList.includes(action)) {
            return false;
          }
        }
        return true;
      })
      .sort((a, b) => {
        // 优先处理 lastLoginMethod：匹配的项目排在最前面
        if (lastLoginMethod) {
          const aIsLastMethod = a.provider === lastLoginMethod;
          const bIsLastMethod = b.provider === lastLoginMethod;
          if (aIsLastMethod && !bIsLastMethod) {
            return -1;
          }
          if (!aIsLastMethod && bIsLastMethod) {
            return 1;
          }
        }
        // 然后按照 order 属性排序
        if (!isNil(a?.order) && !isNil(b?.order)) {
          return a.order - b.order;
        }
        if (!isNil(a?.order)) {
          return -1;
        }
        if (!isNil(b?.order)) {
          return 1;
        }
        return 0;
      });
    return result;
  }, [loginProviderList, lastLoginMethod]);

  const hideQRCode = useCreation(() => {
    const isMobileView = mode === 'drawer' || (isSmallView && browser.mobile.any);
    if (!globalThis?.blocklet) {
      if (!isMobileView) {
        return false;
      }
      return true;
    }

    const walletProvider = showedLoginProviderList.find((item) => item.provider === LOGIN_PROVIDER.WALLET);
    if (walletProvider?.showQrcode !== true) {
      return true;
    }
    if (isMobileView) {
      return true;
    }
    return false;
  }, [mode, isSmallView, showedLoginProviderList]);

  const hideChooseList = useCreation(() => {
    return false;
    // NOTICE: 先保留这部分逻辑，后续根据需求调整
    // if (showOAuthLogin || showPasskeyLogin) {
    //   return false;
    // }
    // return true;
  });

  const result = {
    hideChooseList,
    hideQRCode,
    providerList: showedLoginProviderList,
    loadingProviderList,
  };

  return result;
}
