import { useQuery } from "@apollo/client/react";
import { QUERY_ALL_OWNERS_PAGINATED } from "../../graphql/owners.queries";
import AlertComponent from "../alert/alert.component";
import OwnersListComponent from "./owners-list.component";
import queryString from "query-string";
import { useLocation } from "react-router-dom";
import { pageLimit } from "../../utils/config";

export default function OwnersListContainer() {
  const searchParams = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder, search, pageSize } = searchParams;

  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_OWNERS_PAGINATED, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    variables: {
      search: search || "",
      offset: (currentPage - 1) * currentPageSize,
      limit: currentPageSize,
      order: [
        {
          [sortcolumn || "created_at"]: sortorder ? (sortorder === "descend" ? "desc" : "asc") : "desc"
        }
      ]
    }
  });

  if (error) return <AlertComponent title={error.message} type="error" />;
  return (
    <OwnersListComponent
      loading={loading}
      owners={data ? data.search_owners : null}
      total={data ? data.search_owners_aggregate.aggregate.count : 0}
      refetch={refetch}
    />
  );
}
