import { useQuery } from "@apollo/client/react";
import queryString from "query-string";
import { connect } from "react-redux";
import { useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import AlertComponent from "../../components/alert/alert.component";
import { QUERY_SIMPLIFIED_PARTS_PAGINATED_STATUS_FILTERED } from "../../graphql/jobs.queries";
import { pageLimit } from "../../utils/config";
import SimplifiedPartsJobsListComponent from "./simplified-parts-jobs-list.component";

const mapStateToProps = createStructuredSelector({});

const mapDispatchToProps = () => ({});

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

  const { loading, error, data, refetch } = useQuery(QUERY_SIMPLIFIED_PARTS_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"
        }
      ]
    }
  });

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

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