import { useQuery } from "@apollo/client/react";
import queryString from "query-string";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import AlertComponent from "../../components/alert/alert.component";
import JobsListPaginated from "../../components/jobs-list-paginated/jobs-list-paginated.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { QUERY_ALL_JOBS_PAGINATED_STATUS_FILTERED } from "../../graphql/jobs.queries";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { pageLimit } from "../../utils/config";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

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

const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

export function AllJobs({ setBreadcrumbs, setSelectedHeader }) {
  const searchParams = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder, statusFilters } = searchParams;

  const { loading, error, data, refetch } = useQuery(QUERY_ALL_JOBS_PAGINATED_STATUS_FILTERED, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    variables: {
      offset: page ? (page - 1) * pageLimit : 0,
      limit: pageLimit,
      ...(statusFilters ? { statusList: JSON.parse(statusFilters) } : {}),
      order: [
        {
          [sortcolumn || "ro_number"]:
            sortorder && sortorder !== "false" ? (sortorder === "descend" ? "desc" : "asc") : "desc"
        }
      ]
    }
  });
  const { t } = useTranslation();

  useEffect(() => {
    document.title = t("titles.jobs-all", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    });
    setSelectedHeader("alljobs");
    setBreadcrumbs([{ link: "/manage/jobs/all", label: t("titles.bc.jobs-all") }]);
  }, [t, setBreadcrumbs, setSelectedHeader]);

  if (error) return <AlertComponent title={error.message} type="error" />;
  return (
    <RbacWrapper action="jobs:list-all">
      <JobsListPaginated
        refetch={refetch}
        loading={loading}
        searchParams={searchParams}
        total={data ? data.jobs_aggregate.aggregate.count : 0}
        jobs={data ? data.jobs : []}
      />
    </RbacWrapper>
  );
}

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