import { useRef } from 'react';
import { Box, Menu, MenuItem } from '@mui/material';
import { useReactive } from 'ahooks';
import { mergeSx } from '@arcblock/ux/lib/Util/style';
import PropTypes from 'prop-types';
import { AppInfoItem } from '@arcblock/ux/lib/DIDConnect';

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

export default function SwitchApp({ sx = {}, children }) {
  const { appInfoList, extraParams, connectState } = useStateContext();
  const switchAppRef = useRef(null);
  const currentState = useReactive({
    open: false,
  });
  if (appInfoList.length <= 1) return null;

  return (
    <>
      <Box
        component="span"
        ref={switchAppRef}
        sx={mergeSx(
          {
            color: 'text.secondary',
            cursor: 'pointer',
          },
          sx
        )}
        onClick={() => {
          currentState.open = true;
        }}>
        {children}
      </Box>
      <Menu
        anchorEl={switchAppRef.current}
        open={currentState.open}
        onClose={() => {
          currentState.open = false;
        }}
        slotProps={{
          paper: {
            variant: 'outlined',
            sx: {
              border: 0,
              boxShadow: ({ palette }) => `0px 4px 8px 0px ${palette.grey[100]}, 0px 0px 0px 1px ${palette.grey[100]}`,
              borderRadius: 1,
            },
          },
        }}>
        {appInfoList.map((item) => (
          <MenuItem
            key={item.appPid}
            onClick={() => {
              currentState.open = false;
              connectState.sourceAppPid = item.sourceAppPid;
            }}>
            <AppInfoItem appInfo={item} active={item.sourceAppPid === extraParams?.sourceAppPid} />
          </MenuItem>
        ))}
      </Menu>
    </>
  );
}

SwitchApp.propTypes = {
  sx: PropTypes.object,
  children: PropTypes.any.isRequired,
};
