import { useState } from 'react';
import PropTypes from 'prop-types';
import Spinner from '@mui/material/CircularProgress';
import Dialog from '@arcblock/ux/lib/Dialog';
import DialogContentText from '@mui/material/DialogContentText';
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import ListItem from '@mui/material/ListItem';
import AddIcon from '@mui/icons-material/Add';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Button from '@arcblock/ux/lib/Button';
import Alert from '@mui/material/Alert';
import { useNodeContext } from '../../../contexts/node';
import { formatError, isNewStoreUrl } from '../../../util';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
export default function AddEndpoint({
  disabled = false,
  endpointList = [],
  teamDid,
  onAdd = () => {},
  hiddenChildren = false,
  open = false,
  onClose = () => {}
}) {
  const {
    api
  } = useNodeContext();
  const [loading, setLoading] = useState(false);
  const [disable, setDisable] = useState(true);
  const [isOpen, setIsOpen] = useState(false);
  const [url, setUrl] = useState('');
  const [error, setError] = useState('');
  const {
    t
  } = useLocaleContext();
  const handleClose = () => {
    setUrl('');
    setIsOpen(false);
    onClose();
  };
  const onConfirm = async () => {
    setLoading(true);
    try {
      const {
        decoded
      } = isNewStoreUrl(url, endpointList);
      await api.addUploadEndpoint({
        input: {
          teamDid,
          url: decoded
        }
      });
      onAdd(decoded);
      handleClose();
    } catch (err) {
      const errMsg = `${t('blocklet.publish.endpoint.addFailed')} ${formatError(err)}`;
      setError(errMsg);
    } finally {
      setLoading(false);
    }
  };
  return /*#__PURE__*/_jsxs(_Fragment, {
    children: [!hiddenChildren && /*#__PURE__*/_jsxs(ListItem, {
      button: true,
      disabled: disabled,
      sx: theme => ({
        marginTop: '8px',
        justifyContent: 'center',
        color: theme.palette.primary.main,
        lineHeight: '3.2'
      }),
      onClick: () => {
        setIsOpen(true);
      },
      children: [/*#__PURE__*/_jsx(AddIcon, {
        font: true
      }), /*#__PURE__*/_jsx(Typography, {
        variant: "inherit",
        children: t('blocklet.publish.endpoint.addEndpoint')
      })]
    }), /*#__PURE__*/_jsxs(Dialog, {
      title: t('blocklet.publish.endpoint.addEndpoint'),
      fullWidth: true,
      maxWidth: "md",
      open: open || isOpen,
      onClose: handleClose,
      PaperProps: {
        style: {
          minHeight: 'auto'
        }
      },
      actions: /*#__PURE__*/_jsxs(_Fragment, {
        children: [/*#__PURE__*/_jsx(Button, {
          onClick: e => {
            e.stopPropagation();
            handleClose();
          },
          color: "inherit",
          children: t('common.cancel')
        }), /*#__PURE__*/_jsxs(Button, {
          onClick: e => {
            e.stopPropagation();
            onConfirm();
          },
          color: "primary",
          "data-cy": "install-blocklet-next-step",
          disabled: loading || !url || disable,
          variant: "contained",
          autoFocus: true,
          children: [loading && /*#__PURE__*/_jsx(Spinner, {
            size: 16
          }), t('common.confirm')]
        })]
      }),
      children: [/*#__PURE__*/_jsx("div", {
        style: {
          paddingTop: 12,
          overflowY: 'hidden'
        },
        children: /*#__PURE__*/_jsx(DialogContentText, {
          component: "div",
          children: /*#__PURE__*/_jsx(Typography, {
            component: "div",
            children: /*#__PURE__*/_jsx(TextField, {
              label: t('blocklet.publish.endpoint.addEndpoint'),
              autoComplete: "off",
              variant: "outlined",
              name: "url",
              "data-cy": "add-blocklet-endpoint-url",
              fullWidth: true,
              value: url,
              onChange: e => {
                setError(null);
                let isDisabled = false;
                if (!e.target.value.trim()) {
                  isDisabled = true;
                }
                if (!e.target.value.trim()) {
                  setError(t('blocklet.publish.endpoint.urlEmpty'));
                }
                setUrl(e.target.value);
                setDisable(isDisabled);
              },
              disabled: loading,
              onKeyPress: e => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  if (!e.target.value.trim()) {
                    setError(t('blocklet.publish.endpoint.urlEmpty'));
                  } else {
                    onConfirm();
                  }
                }
              }
            })
          })
        })
      }), !!error && /*#__PURE__*/_jsx(Alert, {
        severity: "error",
        style: {
          width: '100%'
        },
        children: error
      })]
    })]
  });
}
AddEndpoint.propTypes = {
  teamDid: PropTypes.string.isRequired,
  disabled: PropTypes.bool,
  endpointList: PropTypes.array,
  onAdd: PropTypes.func,
  hiddenChildren: PropTypes.bool,
  open: PropTypes.bool,
  onClose: PropTypes.func
};