import { Modal } from "antd";
import axios from "axios";
import React, { 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 { visible, context } = jobCostingModal;
  const { jobId } = context;

  // const { loading, error, data } = useQuery(QUERY_JOB_COSTING_DETAILS, {
  //   variables: { id: jobId },
  //   skip: !jobId,
  // });

  useEffect(() => {
    async function getData() {
      if (jobId && visible) {
        const { data } = await axios.post("/job/costing", { jobid: jobId });
        console.log(data);
        setCostingData(data);
      }
    }
    getData();
  }, [jobId, visible]);

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

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