import { useQuery } from "@apollo/client";
import { Modal } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { GET_JOB_RECONCILIATION_BY_PK } from "../../graphql/jobs.queries";
import { toggleModalVisible } from "../../redux/modals/modals.actions";
import { selectReconciliation } from "../../redux/modals/modals.selectors";
import JobReconciliationModalComponent from "./job-reconciliation-modal.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import AlertComponent from "../alert/alert.component";
import "./job-reconciliation-modal.styles.scss";

const mapStateToProps = createStructuredSelector({
  reconciliationModal: selectReconciliation,
});
const mapDispatchToProps = (dispatch) => ({
  toggleModalVisible: () => dispatch(toggleModalVisible("reconciliation")),
});

function JobReconciliationModalContainer({
  reconciliationModal,
  toggleModalVisible,
}) {
  const { t } = useTranslation();
  const { context, visible } = reconciliationModal;
  const { job } = context;

  const { loading, error, data } = useQuery(GET_JOB_RECONCILIATION_BY_PK, {
    variables: { id: job && job.id },
    skip: !(job && job.id) || !visible,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
  });

  const handleCancel = () => {
    toggleModalVisible();
  };

  return (
    <Modal
      title={t("jobs.labels.reconciliationheader")}
      width={"95%"}
      visible={visible}
      okText={t("general.actions.close")}
      onOk={handleCancel}
      onCancel={handleCancel}
      cancelButtonProps={{ display: "none" }}
      destroyOnClose
      className="imex-reconciliation-modal"
    >
      {loading && <LoadingSpinner loading={loading} />}
      {error && <AlertComponent message={error.message} type="error" />}
      {data && (
        <JobReconciliationModalComponent
          job={data && data.jobs_by_pk}
          bills={data && data.bills}
        />
      )}
    </Modal>
  );
}

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