import { useMutation, useQuery } from "@apollo/client";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
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 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 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({
  bodyshop,
  match,
  setBreadcrumbs,
  addRecentItem,
  setSelectedHeader,
  setJobReadOnly,
}) {
  const { jobId } = match.params;
  const { t } = useTranslation();

  const { loading, error, data, refetch } = useQuery(GET_JOB_BY_PK, {
    variables: { id: jobId },
    fetchPolicy: "network-only",
  });
  const [mutationUpdateJob] = useMutation(UPDATE_JOB);

  useEffect(() => {
    setSelectedHeader("activejobs");
    document.title = loading
      ? t("titles.app")
      : error
      ? t("titles.app")
      : t("titles.jobsdetail", {
          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(
        data.jobs_by_pk.date_exported ||
          data.jobs_by_pk.date_invoiced ||
          data.jobs_by_pk.voided
      );

      addRecentItem(
        CreateRecentItem(
          jobId,
          "job",
          `${data.jobs_by_pk.ro_number || t("general.labels.na")} | ${
            data.jobs_by_pk.ownr_fn || ""
          } ${data.jobs_by_pk.ownr_ln || ""} ${
            data.jobs_by_pk.ownr_co_nm || ""
          }`,
          `/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);
