import { useQuery } from "@apollo/client/react";
import queryString from "query-string";
import { useLocation, useNavigate } from "react-router-dom";
import AlertComponent from "../../components/alert/alert.component";
import { QUERY_ALL_VENDORS } from "../../graphql/vendors.queries";
import VendorsListComponent from "./vendors-list.component";

export default function VendorsListContainer() {
  const { loading, error, data, refetch } = useQuery(QUERY_ALL_VENDORS, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });
  const search = queryString.parse(useLocation().search);
  const history = useNavigate();

  const handleNewVendor = () => {
    search.selectedvendor = "new";
    history({ search: queryString.stringify(search) });
  };

  const handleOnRowClick = (record) => {
    if (record) {
      search.selectedvendor = record.id;
      history({ search: queryString.stringify(search) });
    } else {
      delete search.selectedvendor;
      history({ search: queryString.stringify(search) });
    }
  };

  if (error) return <AlertComponent title={error.message} type="error" />;
  return (
    <VendorsListComponent
      handleNewVendor={handleNewVendor}
      handleOnRowClick={handleOnRowClick}
      loading={loading}
      vendors={data ? data.vendors : null}
      refetch={refetch}
    />
  );
}
