import { useMutation, useQuery } from "@apollo/client";
import React, { 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, UPDATE_JOB } 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 JobsDetailPage from "./jobs-detail.page.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 JobsDetailPageContainer({ 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"
  });
  const [mutationUpdateJob] = useMutation(UPDATE_JOB);

  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 && data.jobs_by_pk.ro_number) || t("general.labels.na")
          });
    setBreadcrumbs([
      { link: "/manage/jobs", label: t("titles.bc.jobs") },
      {
        link: `/manage/jobs/${jobId}`,
        label: t("titles.bc.jobs-detail", {
          number: (data && data.jobs_by_pk && data.jobs_by_pk.ro_number) || t("general.labels.na")
        })
      }
    ]);

    if (data && 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)}`,
          `/manage/jobs/${jobId}`
        )
      );
    }
  }, [loading, data, t, error, setBreadcrumbs, jobId, addRecentItem, setSelectedHeader, setJobReadOnly]);

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

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

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