import VehiclesListComponent from "./vehicles-list.component";
import { useQuery } from "@apollo/client/react";
import AlertComponent from "../alert/alert.component";
import { QUERY_ALL_VEHICLES_PAGINATED } from "../../graphql/vehicles.queries";
import queryString from "query-string";
import { useLocation } from "react-router-dom";
import { pageLimit } from "../../utils/config";
import { connect } from "react-redux";
import { selectIsPartsEntry } from "../../redux/application/application.selectors";
import { createStructuredSelector } from "reselect";
import getPartsBasePath from "../../utils/getPartsBasePath.js";

const mapStateToProps = createStructuredSelector({
  isPartsEntry: selectIsPartsEntry
});

export function VehiclesListContainer({ isPartsEntry }) {
  const searchParams = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder, search, pageSize } = searchParams;
  const basePath = getPartsBasePath(isPartsEntry);

  const currentPage = Number.parseInt(page || "1", 10);
  const parsedPageSize = Number.parseInt(pageSize || String(pageLimit), 10);
  const currentPageSize = Number.isNaN(parsedPageSize) ? pageLimit : parsedPageSize;

  const { loading, error, data, refetch } = useQuery(QUERY_ALL_VEHICLES_PAGINATED, {
    variables: {
      search: search || "",
      offset: (currentPage - 1) * currentPageSize,
      limit: currentPageSize,
      order: [
        {
          [sortcolumn || "created_at"]: sortorder ? (sortorder === "descend" ? "desc" : "asc") : "desc"
        }
      ]
    },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  if (error) return <AlertComponent title={error.message} type="error" />;
  return (
    <VehiclesListComponent
      loading={loading}
      vehicles={data ? data.search_vehicles : null}
      total={data ? data.search_vehicles_aggregate.aggregate.count : 0}
      refetch={refetch}
      basePath={basePath}
    />
  );
}

export default connect(mapStateToProps)(VehiclesListContainer);
