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 { QUERY_ALL_ACTIVE_JOBS } from "../../graphql/jobs.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import JobsFindModalComponent from "./jobs-find-modal.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

export default connect(
  mapStateToProps,
  null
)(function JobsFindModalContainer({
  bodyshop,
  loading,
  error,
  selectedJob,
  setSelectedJob,
  importOptionsState,
  modalSearchState,
  partsQueueToggle,
  setPartsQueueToggle,
  updateSchComp,
  setSchComp,
  ...modalProps
}) {
  const { t } = useTranslation();

  const jobsList = useQuery(QUERY_ALL_ACTIVE_JOBS, {
    variables: {
      statuses: bodyshop.md_ro_statuses.active_statuses || ["Open"]
    },
    skip: !modalProps.open,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const modalSearch = modalSearchState[0];

  const jobsData =
    jobsList.data && jobsList.data.jobs
      ? modalSearch
        ? jobsList.data.jobs.filter(
            (j) =>
              (j.ro_number || "").toLowerCase().includes(modalSearch.toLowerCase()) ||
              (j.ownr_fn || "").toLowerCase().includes(modalSearch.toLowerCase()) ||
              (j.ownr_ln || "").toLowerCase().includes(modalSearch.toLowerCase()) ||
              (j.status || "").toLowerCase().includes(modalSearch.toLowerCase()) ||
              (j.v_make_desc || "").toLowerCase().includes(modalSearch.toLowerCase()) ||
              (j.v_model_desc || "").toLowerCase().includes(modalSearch.toLowerCase()) ||
              (j.clm_no || "").toLowerCase().includes(modalSearch.toLowerCase()) ||
              (j.plate_no || "").toLowerCase().includes(modalSearch.toLowerCase())
          )
        : jobsList.data.jobs
      : null;

  return (
    <Modal
      title={t("jobs.labels.existing_jobs")}
      width={"80%"}
      destroyOnHidden
      okButtonProps={{ disabled: selectedJob ? false : true, id: "jobs-find-modal-container-ok" }}
      {...modalProps}
    >
      {loading ? <LoadingSpinner /> : null}
      {error ? <AlertComponent title={error.message} type="error" /> : null}
      <JobsFindModalComponent
        selectedJob={selectedJob}
        setSelectedJob={setSelectedJob}
        importOptionsState={importOptionsState}
        jobsListLoading={jobsList.loading}
        jobsListRefetch={jobsList.refetch}
        jobsList={jobsData}
        modalSearchState={modalSearchState}
        partsQueueToggle={partsQueueToggle}
        setPartsQueueToggle={setPartsQueueToggle}
        updateSchComp={updateSchComp}
        setSchComp={setSchComp}
      />
    </Modal>
  );
});
