import React, { Fragment, memo, useState, useCallback } from 'react';
import { connect } from 'react-redux';
import EditModal from './EditModal';
import { updateTheme } from 'models/theme';

function EditContainer({
  children,
  id,
  name,
  thumb,
  isDefault,
  published,
  coverShow,
  updateTheme
}: {
  children: React.ReactElement;
  id: number;
  name: string;
  thumb: string;
  isDefault: boolean;
  published: boolean;
  coverShow?: boolean;
  updateTheme: (param) => Promise<{}>;
}) {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleSubmit = useCallback(async (values) => {
    setLoading(true);
    const result = await updateTheme({ ...values, id });
    setLoading(false);
    if (result) {
      setVisible(false);
    }
  }, []);

  return (
    <Fragment>
      <span
        onClick={(e) => {
          e.stopPropagation();
          setVisible(true);
        }}>
        {children}
      </span>
      <EditModal
        visible={visible}
        confirmLoading={loading}
        id={id}
        name={name}
        thumb={thumb}
        coverShow={coverShow}
        published={published}
        isDefault={isDefault}
        onCancel={() => setVisible(false)}
        onOk={handleSubmit}
      />
    </Fragment>
  );
}

const mapDispatchToProps = {
  updateTheme
};

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