import PropTypes from 'prop-types';
import { Box, Popover } from '@mui/material';
import { useRef } from 'react';
import isEmpty from 'lodash/isEmpty';
import isNull from 'lodash/isNull';
import isUndefined from 'lodash/isUndefined';
import { useCreation, useMount, useReactive } from 'ahooks';
import { mergeSx } from '@arcblock/ux/lib/Util/style';
import { AppIcon, AppInfoItem } from '@arcblock/ux/lib/DIDConnect';

import { useStateContext } from '../contexts/state';

function CurrentApp({ appInfo }) {
  const popoverRef = useRef(null);
  const currentState = useReactive({
    hoverOnButton: false,
    hoverOnPopover: false,
  });

  const open = useCreation(() => {
    return currentState.hoverOnButton || currentState.hoverOnPopover;
  }, [currentState.hoverOnButton, currentState.hoverOnPopover]);
  return (
    <>
      <Box
        component="span"
        ref={popoverRef}
        sx={{
          color: 'secondary.main',
          cursor: 'help',
        }}
        onClick={() => {
          currentState.hoverOnButton = true;
        }}
        onMouseEnter={() => {
          currentState.hoverOnButton = true;
        }}
        onMouseLeave={() => {
          setTimeout(() => {
            currentState.hoverOnButton = false;
          }, 200);
        }}>
        {appInfo.appName}
      </Box>
      <Popover
        open={open}
        sx={{
          pointerEvents: 'none',
        }}
        slotProps={{
          paper: {
            variant: 'outlined',
            sx: {
              border: 0,
              boxShadow: ({ palette }) => `0px 4px 8px 0px ${palette.grey[100]}, 0px 0px 0px 1px ${palette.grey[100]}`,
              py: 1,
              px: 1.5,
              borderRadius: 1,
              transform: 'translateY(-6px) !important',
            },
          },
        }}
        anchorEl={popoverRef.current}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        transformOrigin={{
          vertical: 'bottom',
          horizontal: 'center',
        }}
        onClose={() => {
          currentState.open = false;
        }}
        disableRestoreFocus>
        <Box
          component="span"
          sx={{
            pointerEvents: 'auto',
          }}
          onMouseEnter={() => {
            currentState.hoverOnPopover = true;
          }}
          onMouseLeave={() => {
            currentState.hoverOnPopover = false;
          }}>
          <AppInfoItem appInfo={appInfo} appLogo={<AppIcon appInfo={appInfo} />} />
        </Box>
      </Popover>
    </>
  );
}
CurrentApp.propTypes = {
  appInfo: PropTypes.object.isRequired,
};

export default function AppTips({ disableSwitchApp = false, sx = null }) {
  const { appInfoList, extraParams, connectState, blocklet, locale } = useStateContext();
  const appInfo = useCreation(() => {
    return appInfoList.find((x) => {
      if (isUndefined(extraParams?.sourceAppPid)) return true;

      if (isNull(x.sourceAppPid)) {
        return x.appPid === blocklet?.appPid;
      }

      return x.sourceAppPid === extraParams?.sourceAppPid;
    });
  }, [extraParams?.sourceAppPid, appInfoList]);

  const canSwitch = !disableSwitchApp && appInfoList.length > 1;

  useMount(() => {
    if (blocklet?.appPid === appInfo?.appPid) {
      connectState.sourceAppPid = null;
    } else {
      connectState.sourceAppPid = appInfo?.appPid;
    }
  });

  const content = useCreation(() => {
    if (locale === 'zh') {
      return (
        <>
          您正在使用 <CurrentApp appInfo={appInfo} appInfoList={appInfoList} /> 账户来连接站点
        </>
      );
    }
    return (
      <>
        You're using <CurrentApp appInfo={appInfo} /> account for site access
      </>
    );
  }, [locale, appInfo, appInfoList, canSwitch]);

  if (isEmpty(appInfoList)) return null;

  return (
    <Box
      sx={mergeSx(
        {
          fontSize: '13px',
          color: 'text.secondary',
          lineHeight: 1.5,
        },
        sx
      )}>
      {content}
    </Box>
  );
}

AppTips.propTypes = {
  disableSwitchApp: PropTypes.bool,
  sx: PropTypes.object,
};
