import { useQuery } from "@apollo/client/react";
import { Modal } from "antd";
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, open } = reconciliationModal;
  const { job } = context;

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

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

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

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