import { useQuery } from "@apollo/client/react";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useParams } from "react-router-dom";
import AlertComponent from "../../components/alert/alert.component";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { QUERY_OWNER_BY_ID } from "../../graphql/owners.queries";
import { addRecentItem, setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { CreateRecentItem } from "../../utils/create-recent-item";
import OwnersDetailComponent from "./owners-detail.page.component";
import NotFound from "../../components/not-found/not-found.component";
import { OwnerNameDisplayFunction } from "../../components/owner-name-display/owner-name-display.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  addRecentItem: (item) => dispatch(addRecentItem(item)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

export function OwnersDetailContainer({ setBreadcrumbs, addRecentItem, setSelectedHeader }) {
  const { ownerId } = useParams();
  const { t } = useTranslation();

  const { loading, data, error, refetch } = useQuery(QUERY_OWNER_BY_ID, {
    variables: { id: ownerId },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  useEffect(() => {
    document.title = t("titles.owners-detail", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      }),
      name: data ? OwnerNameDisplayFunction(data.owners_by_pk) : ""
    });
    setSelectedHeader("owners");
    setBreadcrumbs([
      { link: "/manage/owners", label: t("titles.bc.owners") },
      {
        link: `/manage/owners/${ownerId}`,
        label: t("titles.bc.owner-detail", {
          name: data ? OwnerNameDisplayFunction(data.owners_by_pk) : ""
        })
      }
    ]);

    if (data && data.owners_by_pk)
      addRecentItem(
        CreateRecentItem(ownerId, "owner", OwnerNameDisplayFunction(data.owners_by_pk), `/manage/owners/${ownerId}`)
      );
  }, [setBreadcrumbs, t, data, ownerId, addRecentItem, setSelectedHeader]);

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent title={error.message} type="error" />;
  if (!data.owners_by_pk) return <NotFound />;

  return (
    <RbacWrapper action="owners:detail">
      <OwnersDetailComponent owner={data.owners_by_pk} refetch={refetch} />
    </RbacWrapper>
  );
}

export default connect(null, mapDispatchToProps)(OwnersDetailContainer);
