import React, { useEffect, useCallback } from 'react';
import { connect } from 'react-redux';
import Mousetrap from 'mousetrap';
import { deleteComponents } from 'models/component';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';

function ComponentDeleteModal({ enabled, deleteComponents }) {
  const deleteRef = useConfirmRef();
  useEffect(() => {
    Mousetrap.bind(['del', 'backspace'], () => {
      if (enabled) {
        deleteRef.current?.show();
      }
    });
    return () => {
      Mousetrap.unbind(['del', 'backspace']);
    };
  }, [enabled]);

  const onCommitDelete = useCallback(() => {
    deleteComponents();
    deleteRef.current?.close();
  }, []);
  return (
    <EasyvModal.Confirm
      title="删除组件"
      content="删除24小时可在组件回收站内恢复"
      ref={deleteRef}
      onOk={onCommitDelete}
    />
  );
}

const mapStateToProps = ({ createApp }) => {
  const { layersSelected } = createApp;
  return {
    layersSelected,
    enabled: layersSelected.length > 0, // WARNING 这里如果不是第一次创建会不会有其他的影响
  };
};

const mapDispatchToProps = {
  deleteComponents,
};

export default connect(mapStateToProps, mapDispatchToProps)(ComponentDeleteModal);
