import { useLazyQuery } from "@apollo/client";
import { Input, Modal } from "antd";
import React, { useEffect, useState } from "react";
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 [searchText, setSearchText] = useState(null);

  const [callSearchowners, ownersList] = useLazyQuery(
    QUERY_SEARCH_OWNER_BY_IDX,
    {
      variables: {
        search: searchText,
      },
    }
  );

  useEffect(() => {
    if (modalProps.visible && owner) {
      const s = `${owner.ownr_fn || ""} ${owner.ownr_ln || ""} ${
        owner.ownr_co_nm || ""
      }`;

      setSearchText(s.trim());
      callSearchowners({ variables: { search: s.trim() } });
    }
  }, [callSearchowners, modalProps.visible, owner]);

  return (
    <Modal
      title={t("owners.labels.existing_owners")}
      width={"80%"}
      {...modalProps}
    >
      {loading ? <LoadingSpinner /> : null}
      {error ? <AlertComponent message={error.message} type="error" /> : null}
      {owner ? (
        <>
          <Input.Search
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            onSearch={(val) =>
              callSearchowners({ variables: { search: val.trim() } })
            }
          />
          <OwnerFindModalComponent
            selectedOwner={selectedOwner}
            setSelectedOwner={setSelectedOwner}
            ownersListLoading={ownersList.loading}
            ownersList={
              ownersList.data && ownersList.data.search_owners
                ? ownersList.data.search_owners
                : null
            }
          />
        </>
      ) : null}
    </Modal>
  );
}
