import { useQuery } from "@apollo/client/react";
import { 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";
import { Card } from "antd";
import UpsellComponent, { upsellEnum } from "../../components/upsell/upsell.component";

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)"
      })
    });
    setSelectedHeader("courtesycarsall");
    setBreadcrumbs([{ link: "/manage/courtesycars", label: t("titles.bc.courtesycars") }]);
  }, [setBreadcrumbs, t, setSelectedHeader]);

  if (error) return <AlertComponent title={error.message} type="error" />;
  return (
    <FeatureWrapperComponent
      featureName="courtesycars"
      noauth={
        <Card>
          <UpsellComponent upsell={upsellEnum().courtesycars.general} />
        </Card>
      }
    >
      <RbacWrapper action="courtesycar:list">
        <CourtesyCarsPageComponent loading={loading} data={data?.courtesycars || []} refetch={refetch} />
      </RbacWrapper>
    </FeatureWrapperComponent>
  );
}

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