import React from "react";
import { useQuery } from "react-apollo";
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({ selectedVendorState }) {
  const [selectedVendor, setSelectedVendor] = selectedVendorState;
  const { loading, error, data, refetch } = useQuery(QUERY_ALL_VENDORS, {
    fetchPolicy: "network-only"
  });

  const handleNewVendor = () => {
    setSelectedVendor({});
  };

  const handleOnRowClick = record => {
    if (record) {
      setSelectedVendor(record);
      return;
    }
    setSelectedVendor(null);
  };

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