import { useLazyQuery } from "@apollo/client/react";
import { Input, Modal } from "antd";
import { 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 { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";
import OwnerFindModalComponent from "./owner-find-modal.component";

export default function OwnerFindModalContainer({
  loading,
  error,
  owner,
  selectedOwner,
  setSelectedOwner,
  partsQueueToggle,
  setPartsQueueToggle,
  ...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);

  useEffect(() => {
    if (modalProps.open && owner) {
      const s = OwnerNameDisplayFunction(owner, true);

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

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