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 { createStructuredSelector } from "reselect";
import AlertComponent from "../../components/alert/alert.component";
import SpinComponent from "../../components/loading-spinner/loading-spinner.component";
import NotFound from "../../components/not-found/not-found.component";
import { OwnerNameDisplayFunction } from "../../components/owner-name-display/owner-name-display.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { GET_JOB_BY_PK } from "../../graphql/jobs.queries";
import {
  addRecentItem,
  setBreadcrumbs,
  setJobReadOnly,
  setSelectedHeader
} from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { CreateRecentItem } from "../../utils/create-recent-item";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import IsJobReadOnly from "../../utils/jobReadOnly";
import SimplifiedPartsJobsDetailComponent from "./simplified-parts-jobs-detail.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

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

function SimplifiedPartsJobsDetailContainer({ setBreadcrumbs, addRecentItem, setSelectedHeader, setJobReadOnly }) {
  const { jobId } = useParams();
  const { t } = useTranslation();

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

  useEffect(() => {
    setSelectedHeader("activejobs");
    document.title = loading
      ? InstanceRenderManager({
          imex: t("titles.imexonline"),
          rome: t("titles.romeonline")
        })
      : error
        ? InstanceRenderManager({
            imex: t("titles.imexonline"),
            rome: t("titles.romeonline")
          })
        : t("titles.jobsdetail", {
            app: InstanceRenderManager({
              imex: "$t(titles.imexonline)",
              rome: "$t(titles.romeonline)"
            }),
            ro_number: data.jobs_by_pk?.ro_number || t("general.labels.na")
          });
    setBreadcrumbs([
      { link: "/parts", label: t("titles.bc.parts") },
      {
        link: `/parts/jobs/${jobId}`,
        label: t("titles.bc.jobs-detail", {
          number: (data?.jobs_by_pk && data.jobs_by_pk.ro_number) || t("general.labels.na")
        })
      }
    ]);

    if (data?.jobs_by_pk) {
      setJobReadOnly(IsJobReadOnly(data.jobs_by_pk));

      addRecentItem(
        CreateRecentItem(
          jobId,
          "job",

          `${data.jobs_by_pk.ro_number || t("general.labels.na")} | ${OwnerNameDisplayFunction(data.jobs_by_pk)}`,
          `/parts/jobs/${jobId}`
        )
      );
    }
  }, [loading, data, t, error, setBreadcrumbs, jobId, addRecentItem, setSelectedHeader, setJobReadOnly]);

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

  return data.jobs_by_pk ? (
    <RbacWrapper action="jobs:detail">
      <SimplifiedPartsJobsDetailComponent job={data.jobs_by_pk} refetch={refetch} />
    </RbacWrapper>
  ) : (
    <AlertComponent title={t("jobs.errors.noaccess")} type="error" />
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(SimplifiedPartsJobsDetailContainer);
