import React, { useState } from 'react';
import { IconButton } from '@mui/material';
import { DeleteOutline as DeleteOutlineIcon } from '@mui/icons-material';
import Confirm from '@arcblock/ux/lib/Dialog/confirm';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import toast from '@arcblock/ux/lib/Toast';
import { SpaceGateway } from '../../../contexts/config-user-space';

function SpaceDelete({
  spaceGateway,
  onDeleteSpace,
}: {
  spaceGateway: SpaceGateway;
  onDeleteSpace: (spaceGateway: SpaceGateway) => Promise<void>;
}) {
  const { t } = useLocaleContext();
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleOpen = (e: React.MouseEvent, bool: boolean) => {
    e?.stopPropagation();
    setOpen(bool);
  };

  const handleOnDelete = async (e: React.MouseEvent) => {
    try {
      e?.stopPropagation();
      setLoading(true);
      await onDeleteSpace(spaceGateway);
      setOpen(false);
    } catch (error: any) {
      console.error(error);
      toast.error(`${t('storage.spaces.gateway.delete.failed')}: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <IconButton size="small" onClick={(e) => handleOpen(e, true)}>
        <DeleteOutlineIcon />
      </IconButton>

      <Confirm
        title={t('common.delConfirmDescription', {
          data: `${spaceGateway?.name}`,
        })}
        open={open}
        confirmButton={{
          text: t('common.confirm'),
          props: {
            variant: 'contained',
            color: 'error',
            loading,
          },
        }}
        cancelButton={{
          text: t('common.cancel'),
          props: {
            variant: 'contained',
            color: 'primary',
          },
        }}
        onConfirm={handleOnDelete}
        onCancel={(e: React.MouseEvent) => handleOpen(e, false)}
      />
    </>
  );
}

export default SpaceDelete;
