import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Icon } from '@iconify/react';
import AddIcon from '@mui/icons-material/Add';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import { Box, Button, ButtonGroup, CircularProgress, ClickAwayListener, Divider, Grow, IconButton, MenuItem, MenuList, Paper, Popper, Typography } from '@mui/material';
import PropTypes from 'prop-types';
import { useRef, useState } from 'react';
import { formatError } from '@blocklet/error';
import Toast from '@arcblock/ux/lib/Toast';
import ConfirmDialog from '../../../confirm';
import { useBlockletContext } from '../../../contexts/blocklet';
import { useNodeContext } from '../../../contexts/node';
import { useSessionContext } from '../../../contexts/session';
import AddStore from '../../../store/add';
import ShortenLabel from '../../component/shorten-label';
import canDeleteStore from '../utils/can-delete-store';
import getStudioStoreList from '../utils/get-studio-store-list';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
export default function ConnectStoreButton({
  blocklet = null,
  store = null,
  onChangeStore,
  onClick,
  disabled,
  loading,
  componentDid
}) {
  const {
    t
  } = useLocaleContext();
  const {
    session
  } = useSessionContext();
  const {
    api,
    info: nodeInfo,
    inService
  } = useNodeContext();
  const blockletContext = useBlockletContext();
  const [open, setOpen] = useState(false);
  const anchorRef = useRef(null);
  const [openAddStore, setOpenAddStore] = useState(false);
  const [deleteStore, setDeleteStore] = useState(null);
  const handleSelectStore = nextStore => {
    onChangeStore(nextStore);
    setOpen(false);
  };
  const handleToggle = () => {
    setOpen(!open);
  };
  const handleClose = event => {
    if (anchorRef.current && anchorRef.current.contains(event.target)) {
      return;
    }
    setOpen(false);
  };
  const handleOpenAddStore = () => {
    setOpenAddStore(true);
  };
  const handleCloseAddStore = () => {
    setOpenAddStore(false);
  };
  const handleDeleteStore = async () => {
    if (!deleteStore) {
      return;
    }
    try {
      await api.deleteBlockletStore({
        input: {
          teamDid: blocklet.meta.did,
          url: deleteStore.url,
          projectId: '',
          scope: deleteStore.scope || 'studio'
        }
      });
      await blockletContext?.actions?.refreshBlocklet();
    } catch (err) {
      Toast.error(`Remove Blocklet Store Error: ${formatError(err)}`);
    } finally {
      setDeleteStore(null);
    }
  };
  const {
    storeList
  } = getStudioStoreList({
    fromBlocklet: inService,
    blocklet,
    nodeInfo,
    componentDid,
    userDid: session?.user?.did
  });
  const did = blocklet?.meta?.did;
  return /*#__PURE__*/_jsxs(_Fragment, {
    children: [/*#__PURE__*/_jsxs(ButtonGroup, {
      disabled: disabled,
      ref: anchorRef,
      variant: "contained",
      color: "primary",
      "aria-label": "Button group with connect store",
      children: [/*#__PURE__*/_jsxs(Button, {
        onClick: onClick,
        children: [loading && /*#__PURE__*/_jsx(CircularProgress, {
          size: 14,
          sx: {
            mr: 0.5
          }
        }), `${t('common.connect')} ${store.name || ''}`]
      }), /*#__PURE__*/_jsx(Button, {
        size: "small",
        "aria-controls": open ? 'split-button-menu' : undefined,
        "aria-expanded": open ? 'true' : undefined,
        "aria-label": "select merge strategy",
        "aria-haspopup": "menu",
        onClick: handleToggle,
        children: /*#__PURE__*/_jsx(ArrowDropDownIcon, {})
      })]
    }), /*#__PURE__*/_jsx(Popper, {
      sx: {
        zIndex: 10
      },
      open: open,
      anchorEl: anchorRef.current,
      placement: "bottom-end",
      role: undefined,
      transition: true,
      disablePortal: true,
      children: ({
        TransitionProps
      }) => /*#__PURE__*/_jsx(Grow, {
        ...TransitionProps,
        style: {
          transformOrigin: 'center top'
        },
        children: /*#__PURE__*/_jsx(Paper, {
          children: /*#__PURE__*/_jsx(ClickAwayListener, {
            onClickAway: handleClose,
            children: /*#__PURE__*/_jsxs(MenuList, {
              id: "split-button-menu",
              autoFocusItem: true,
              sx: {
                maxHeight: 300,
                overflowY: 'auto',
                zIndex: 10
              },
              children: [storeList?.map(option => /*#__PURE__*/_jsxs(MenuItem, {
                selected: option.id === store?.id,
                sx: {
                  height: 56
                },
                onClick: () => handleSelectStore(option),
                children: [/*#__PURE__*/_jsxs(Box, {
                  children: [/*#__PURE__*/_jsx(ShortenLabel, {
                    sx: {
                      fontSize: '16px'
                    },
                    maxLength: 24,
                    children: option.name
                  }), /*#__PURE__*/_jsx(ShortenLabel, {
                    sx: {
                      fontSize: '13px',
                      opacity: 0.6
                    },
                    maxLength: 30,
                    children: option.url
                  })]
                }), canDeleteStore({
                  store: option,
                  userDid: session?.user?.did
                }) && /*#__PURE__*/_jsx(IconButton, {
                  sx: {
                    ml: 1
                  },
                  onClick: e => {
                    e.preventDefault();
                    e.stopPropagation();
                    setDeleteStore(option);
                  },
                  children: /*#__PURE__*/_jsx(Icon, {
                    icon: "ic:outline-delete"
                  })
                })]
              }, option.url)), /*#__PURE__*/_jsx(Divider, {}), /*#__PURE__*/_jsxs(MenuItem, {
                onClick: handleOpenAddStore,
                children: [/*#__PURE__*/_jsx(AddIcon, {
                  font: true
                }), /*#__PURE__*/_jsx(Typography, {
                  variant: "inherit",
                  children: t('store.blockletRegistry.addRegistry')
                })]
              })]
            })
          })
        })
      })
    }), openAddStore && /*#__PURE__*/_jsx(AddStore, {
      hiddenChildren: true,
      open: true,
      onClose: handleCloseAddStore,
      teamDid: did,
      storeList: storeList,
      scope: "studio",
      onAdd: blockletContext?.actions?.refreshBlocklet
    }), deleteStore && /*#__PURE__*/_jsx(ConfirmDialog, {
      displayError: true,
      title: `${t('common.delete')} ${deleteStore.name}`,
      description: t('blocklet.publish.deleteStoreTip', {
        name: deleteStore.name
      }),
      confirm: t('common.confirm'),
      onConfirm: handleDeleteStore,
      onCancel: () => setDeleteStore(null)
    })]
  });
}
ConnectStoreButton.propTypes = {
  store: PropTypes.object,
  blocklet: PropTypes.object,
  onChangeStore: PropTypes.func.isRequired,
  onClick: PropTypes.func.isRequired,
  loading: PropTypes.bool.isRequired,
  disabled: PropTypes.bool.isRequired,
  componentDid: PropTypes.string.isRequired,
  projectType: PropTypes.string.isRequired,
  getData: PropTypes.func.isRequired
};