import { Modal, notification } from "antd";
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useLazyQuery } from "react-apollo";
import ReactDOMServer from "react-dom/server";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { toggleEmailOverlayVisible } from "../../redux/email/email.actions";
import {
  selectEmailConfig,
  selectEmailVisible
} from "../../redux/email/email.selectors.js";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import EmailOverlayComponent from "./email-overlay.component";

const mapStateToProps = createStructuredSelector({
  modalVisible: selectEmailVisible,
  emailConfig: selectEmailConfig
});
const mapDispatchToProps = dispatch => ({
  toggleEmailOverlayVisible: () => dispatch(toggleEmailOverlayVisible())
});
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(function EmailOveralContainer({
  emailConfig,
  modalVisible,
  toggleEmailOverlayVisible
}) {
  const { t } = useTranslation();
  const [messageOptions, setMessageOptions] = useState(
    emailConfig.messageOptions
  );
  useEffect(() => {
    setMessageOptions(emailConfig.messageOptions);
  }, [setMessageOptions, emailConfig.messageOptions]);

  const [executeQuery, { called, loading, data }] = useLazyQuery(
    emailConfig.queryConfig[0],
    {
      ...emailConfig.queryConfig[1],
      fetchPolicy: "network-only"
    }
  );

  if (
    emailConfig.queryConfig[0] &&
    emailConfig.queryConfig[1] &&
    modalVisible &&
    !called
  ) {
    executeQuery();
  }

  if (data && !messageOptions.html && emailConfig.template) {
    setMessageOptions({
      ...messageOptions,
      html: ReactDOMServer.renderToStaticMarkup(
        <emailConfig.template data={data} />
      )
      //html: renderEmail(<emailConfig.template data={data} />)
    });
  }

  const handleOk = () => {
    //sendEmail(messageOptions);
    axios
      .post("/sendemail", messageOptions)
      .then(response => {
        console.log(JSON.stringify(response));
        notification["success"]({ message: t("emails.successes.sent") });
        toggleEmailOverlayVisible();
      })
      .catch(error => {
        console.log(JSON.stringify(error));
        notification["error"]({
          message: t("emails.errors.notsent", { message: error.message })
        });
      });
  };
  const handleConfigChange = event => {
    const { name, value } = event.target;
    setMessageOptions({ ...messageOptions, [name]: value });
  };
  const handleHtmlChange = text => {
    setMessageOptions({ ...messageOptions, html: text });
  };

  return (
    <Modal
      destroyOnClose={true}
      visible={modalVisible}
      width={"80%"}
      onOk={handleOk}
      onCancel={() => toggleEmailOverlayVisible()}
    >
      <LoadingSpinner loading={loading}>
        <EmailOverlayComponent
          handleConfigChange={handleConfigChange}
          messageOptions={messageOptions}
          handleHtmlChange={handleHtmlChange}
        />
        <button
          onClick={() => {
            console.log(messageOptions.html);
            navigator.clipboard.writeText(messageOptions.html);
          }}
        >
          Get HTML
        </button>
      </LoadingSpinner>
    </Modal>
  );
});
