import PropTypes from 'prop-types';
import { CircularProgress } from '@mui/material';
import { useCreation, useMemoizedFn, useReactive } from 'ahooks';
import { openWebWallet, detectWalletExtension } from '@arcblock/ux/lib/Util';
import { mergeSx } from '@arcblock/ux/lib/Util/style';
import noop from 'lodash/noop';
import omit from 'lodash/omit';
import { useImperativeHandle } from 'react';
import ProviderIcon from '@arcblock/ux/lib/DIDConnect/provider-icon';
import { LOGIN_PROVIDER, LOGIN_PROVIDER_ICON_SIZE } from '@arcblock/ux/lib/Util/constant';

import LoginMethodItem from './login-method-item';
import { useStateContext } from '../../contexts/state';
import { EXT_DOWNLOAD_URL } from '../../../constant';
import useAuthUrl from '../../hooks/auth-url';

export default function WebLoginItem({
  ref = null,
  tokenState,
  locale = 'en',
  webWalletUrl,
  onClick = noop,
  disableSwitchApp = false,
  autoConnect = true,
  ...rest
}) {
  const { browserBrand } = useStateContext();
  const extension = detectWalletExtension();
  const currentState = useReactive({
    loading: false,
  });

  const urlWithParams = useAuthUrl({ disableSwitchApp, tokenState });

  const handleConnectFn = useMemoizedFn(() => {
    if (!autoConnect) {
      return;
    }
    currentState.loading = true;
    const openResult = openWebWallet({
      webWalletUrl,
      url: urlWithParams,
      locale,
      appInfo: tokenState.appInfo,
      memberAppInfo: tokenState.memberAppInfo,
    });
    if (openResult?.type === 'web') {
      currentState.loading = false;
    } else {
      // 后续需要通过插件回传消息，才能准确的关闭 loading 状态
      setTimeout(() => {
        currentState.loading = false;
      }, 3000);
    }
  });
  const handleConnect = useMemoizedFn((e) => {
    if (!tokenState.url) {
      return;
    }

    onClick(e);
    e?.preventDefault();
    handleConnectFn();
  });

  useImperativeHandle(ref, () => ({
    connect: handleConnectFn,
  }));

  const extDownloadUrl = useCreation(() => {
    if (browserBrand === 'edge') {
      return EXT_DOWNLOAD_URL.edge;
    }
    if (browserBrand === 'chrome') {
      return EXT_DOWNLOAD_URL.chrome;
    }
    return null;
  }, [browserBrand]);

  const buttonProps = useCreation(() => {
    const result = {};
    if (extension || !autoConnect) {
      result.onClick = handleConnect;
    } else if (extDownloadUrl && autoConnect) {
      result.component = 'a';
      result.href = extDownloadUrl;
      result.target = '_blank';
      result.rel = 'noopener';
    } else {
      result.onClick = handleConnect;
    }

    if (!tokenState.url) {
      result.sx = {
        cursor: 'not-allowed',
      };
    }
    return result;
  }, [handleConnect, tokenState.url]);

  const title = useCreation(() => {
    if (!autoConnect) {
      return 'DID Wallet';
    }
    if (extension || extDownloadUrl) {
      return 'DID Wallet (Extension)';
    }
    return 'DID Wallet (Web)';
  }, [extension, extDownloadUrl]);

  return (
    <LoginMethodItem
      {...rest}
      sx={mergeSx(
        {
          textDecoration: 'none',
        },
        rest?.sx,
        buttonProps.sx
      )}
      title={title}
      icon={
        currentState.loading || !tokenState.url ? (
          <CircularProgress
            color="primary"
            size={LOGIN_PROVIDER_ICON_SIZE}
            sx={{
              '& svg': {
                transform: 'scale(0.75)',
              },
            }}
          />
        ) : (
          <ProviderIcon
            sx={{
              width: LOGIN_PROVIDER_ICON_SIZE,
              height: LOGIN_PROVIDER_ICON_SIZE,
              transform: 'scale(0.9)',
            }}
            provider={LOGIN_PROVIDER.DID_WALLET}
          />
        )
      }
      {...omit(buttonProps, 'sx')}
    />
  );
}

WebLoginItem.propTypes = {
  tokenState: PropTypes.object.isRequired,
  locale: PropTypes.string,
  webWalletUrl: PropTypes.string.isRequired,
  onClick: PropTypes.func,
  disableSwitchApp: PropTypes.bool,
  autoConnect: PropTypes.bool, // 点击后是否自动连接，默认true
  ref: PropTypes.any,
};
