import { Modal } from "antd";
import axios from "axios";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { toggleModalVisible } from "../../redux/modals/modals.actions";
import { selectJobCosting } from "../../redux/modals/modals.selectors";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import JobCostingModalComponent from "./job-costing-modal.component";

const mapStateToProps = createStructuredSelector({
  jobCostingModal: selectJobCosting
});

const mapDispatchToProps = (dispatch) => ({
  toggleModalVisible: () => dispatch(toggleModalVisible("jobCosting"))
});

export function JobCostingModalContainer({ jobCostingModal, toggleModalVisible }) {
  const { t } = useTranslation();
  const [costingData, setCostingData] = useState(null);
  const { open, context } = jobCostingModal;
  const { jobId } = context;

  useEffect(() => {
    async function getData() {
      if (jobId && open) {
        const { data } = await axios.post("/job/costing", { jobid: jobId });

        setCostingData(data);
      }
    }

    getData();
  }, [jobId, open]);

  return (
    <Modal
      open={open}
      title={t("jobs.labels.jobcosting")}
      onOk={() => {
        toggleModalVisible();
        setCostingData(null);
      }}
      onCancel={() => {
        toggleModalVisible();
        setCostingData(null);
      }}
      cancelButtonProps={{ style: { display: "none" } }}
      width="90%"
      destroyOnHidden
    >
      {!costingData ? (
        <LoadingSpinner loading={true} />
      ) : (
        <JobCostingModalComponent costCenterData={costingData.costCenterData} summaryData={costingData.summaryData} />
      )}
    </Modal>
  );
}

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