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 { QUERY_INVENTORY_PAGINATED } from "../../graphql/inventory.queries";
import AlertComponent from "../alert/alert.component";
import InventoryListPaginated from "./inventory-list.component";
import { pageLimit } from "../../utils/config";

const mapStateToProps = createStructuredSelector({});

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

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

  const { loading, error, data, refetch } = useQuery(QUERY_INVENTORY_PAGINATED, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    variables: {
      search: search || "",
      offset: page ? (page - 1) * pageLimit : 0,
      limit: pageLimit,
      consumedIsNull: showall === "true" ? null : true,
      order: [
        {
          [sortcolumn || "created_at"]:
            sortorder && sortorder !== "false" ? (sortorder === "descend" ? "desc" : "asc") : "desc"
        }
      ]
    }
  });

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

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