import { useQuery } from "@apollo/client";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import AlertComponent from "../../components/alert/alert.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { QUERY_ALL_CC } from "../../graphql/courtesy-car.queries";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import CourtesyCarsPageComponent from "./courtesy-cars.page.component";
import FeatureWrapperComponent from "../../components/feature-wrapper/feature-wrapper.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

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

export function CourtesyCarsPageContainer({ setBreadcrumbs, setSelectedHeader }) {
  const { loading, error, data, refetch } = useQuery(QUERY_ALL_CC, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });
  const { t } = useTranslation();
  useEffect(() => {
    document.title = t("titles.courtesycars", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)",
        promanager: "$t(titles.promanager)"
      })
    });
    setSelectedHeader("courtesycarsall");
    setBreadcrumbs([{ link: "/manage/courtesycars", label: t("titles.bc.courtesycars") }]);
  }, [setBreadcrumbs, t, setSelectedHeader]);

  if (error) return <AlertComponent message={error.message} type="error" />;
  return (
    <RbacWrapper action="courtesycar:list">
      <FeatureWrapperComponent featureName="courtesycars">
        <CourtesyCarsPageComponent loading={loading} data={(data && data.courtesycars) || []} refetch={refetch} />
      </FeatureWrapperComponent>
    </RbacWrapper>
  );
}

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