import { Modal } from "antd";
import React from "react";
import { useQuery } from "react-apollo";
import { useTranslation } from "react-i18next";
import { QUERY_SEARCH_OWNER_BY_IDX } from "../../graphql/owners.queries";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import OwnerFindModalComponent from "./owner-find-modal.component";

export default function OwnerFindModalContainer({
  loading,
  error,
  owner,
  selectedOwner,
  setSelectedOwner,
  ...modalProps
}) {
  //use owner object to run query and find what possible owners there are.
  const { t } = useTranslation();

  const ownersList = useQuery(QUERY_SEARCH_OWNER_BY_IDX, {
    variables: {
      search: owner ? `${owner.ownr_fn || ""} ${owner.ownr_ln || ""}` : null
    },
    skip: !owner,
    fetchPolicy: "network-only"
  });

  return (
    <Modal
      title={t("owners.labels.existing_owners")}
      width={"80%"}
      {...modalProps}>
      {loading ? <LoadingSpinner /> : null}
      {error ? <AlertComponent message={error.message} type='error' /> : null}
      {owner ? (
        <OwnerFindModalComponent
          selectedOwner={selectedOwner}
          setSelectedOwner={setSelectedOwner}
          ownersListLoading={ownersList.loading}
          ownersList={
            ownersList.data && ownersList.data.search_owner
              ? ownersList.data.search_owner
              : null
          }
        />
      ) : null}
    </Modal>
  );
}
