import React, { Fragment, memo, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { updateThemesPack, addThemesPack } from 'models/theme';
import ConfirmModal from 'components/ConfirmModal';
import EditThemePack, { EditThemeConfigType, EditThemeRef } from 'components/EasyvEditTheme/index';
import { ThemeType, Type } from 'models/theme.types';
import message from 'components/message';

function EditContainer({
  children,
  updateThemesPack,
  addThemesPack,
  curEditThemeConfig,
  model,
  type
}: {
  children: React.ReactElement;
  addThemesPack: (data: EditThemeConfigType) => Promise<boolean>;
  updateThemesPack: (data: ThemeType) => Promise<boolean>;
  curEditThemeConfig?: EditThemeConfigType;
  model: 'add' | 'edit';
  type: Type;
}) {
  const ref = useRef<EditThemeRef>(null);
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async () => {
    if (!ref.current?.themeConfig.name) {
      message.error('主题名不能为空');
      return;
    }
    setLoading(true);
    let result;
    if (model === 'edit') {
      result = await updateThemesPack(ref.current?.themeConfig as ThemeType);
    } else {
      result = await addThemesPack(ref.current?.themeConfig as EditThemeConfigType);
    }
    setLoading(false);
    if (result) {
      setVisible(false);
    }
  };

  return (
    <Fragment>
      <span
        onClick={(e) => {
          e.stopPropagation();
          setVisible(true);
        }}>
        {children}
      </span>
      <ConfirmModal
        visible={visible}
        title={model === 'edit' ? '编辑主题包信息' : '新建主题包'}
        footer={true}
        okText={model === 'edit' ? '保存' : '确定'}
        confirmLoading={loading}
        destroyOnClose
        onCancel={() => setVisible(false)}
        onOk={handleSubmit}>
        <span style={{ pointerEvents: loading ? 'none' : 'auto' }}>
          <EditThemePack ref={ref} type={type} model={model} curEditThemeConfig={curEditThemeConfig} />
        </span>
      </ConfirmModal>
    </Fragment>
  );
}

const mapDispatchToProps = {
  updateThemesPack,
  addThemesPack
};

export default connect(undefined, mapDispatchToProps)(memo(EditContainer));
