import { useQuery } from "@apollo/react-hooks";
import queryString from "query-string";
import React, { 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 { QUERY_ALL_JOBS_PAGINATED } from "../../graphql/jobs.queries";
import {
  setBreadcrumbs,
  setSelectedHeader,
} from "../../redux/application/application.actions";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";

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, search } = searchParams;

  const { loading, error, data, refetch } = useQuery(QUERY_ALL_JOBS_PAGINATED, {
    variables: {
      search: search || "",
      offset: page ? (page - 1) * 25 : 0,
      limit: 25,
      order: [
        {
          [sortcolumn || "est_number"]: sortorder
            ? sortorder === "descend"
              ? "desc"
              : "asc"
            : "desc",
        },
      ],
    },
  });
  const { t } = useTranslation();

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

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

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