import React, { Fragment, useState, useCallback } from 'react';
import { connect } from 'react-redux';
import { getSource, addSource, updateSource } from 'models/source';
import SourceEditModal from './SourceEditModal';

interface IProps {
  id?: number;
  children: React.ReactNode;
  dispatch: Function;
  defaultType?: string;
}

function SourceEdit({ id, dispatch, children, defaultType }: IProps) {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [sourceData, setSourceData] = useState({});

  const handleShow = async () => {
    if (id) {
      const result = await dispatch(getSource(id));
      if (result) {
        setSourceData(result);
        setVisible(true);
      }
    } else {
      setVisible(true);
    }
  };

  const handleClose = useCallback(() => {
    setVisible(false);
  }, []);

  const handleOk = useCallback((value) => {
    setLoading(true);
    (async () => {
      const result = id
        ? await dispatch(updateSource({ id, ...value }))
        : await dispatch(addSource(value));
      setLoading(false);
      if (result) {
        setVisible(false);
      }
    })();
  }, []);

  return (
    <Fragment>
      <span onClick={handleShow}>{children}</span>
      <SourceEditModal
        visible={visible}
        loading={loading}
        data={sourceData}
        defaultType={defaultType}
        onCancel={handleClose}
        onOk={handleOk}
      />
    </Fragment>
  );
}

export default connect()(SourceEdit);
