import { useQuery } from "@apollo/react-hooks";
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 { CalculateJob } from "../../components/job-totals-table/job-totals.utility";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import { QUERY_JOB_CLOSE_DETAILS } from "../../graphql/jobs.queries";
import { setBreadcrumbs } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import JobsCloseComponent from "./jobs-close.component";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop,
});

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

export function JobsCloseContainer({ setBreadcrumbs, bodyshop }) {
  const { jobId } = useParams();
  const { loading, error, data } = useQuery(QUERY_JOB_CLOSE_DETAILS, {
    variables: { id: jobId },
  });
  const { t } = useTranslation();
  useEffect(() => {
    document.title = t("titles.jobs-close", {
      number: data ? data.jobs_by_pk.ro_number : null,
    });

    setBreadcrumbs([
      {
        link: `/manage/jobs/${jobId}/`,
        label: t("titles.bc.jobs"),
      },
      {
        link: `/manage/jobs/${jobId}/`,
        label: t("titles.bc.jobs-detail", {
          number: data ? data.jobs_by_pk.ro_number : null,
        }),
      },
      {
        link: `/manage/jobs/${jobId}/close`,
        label: t("titles.bc.jobs-close"),
      },
    ]);
  }, [setBreadcrumbs, t, jobId, data]);

  console.log("Container rerender");
  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent message={error.message} type="error" />;

  const jobTotals = CalculateJob(data.jobs_by_pk, bodyshop.shoprates);
  return (
    <div>
      <JobsCloseComponent
        job={data ? data.jobs_by_pk : {}}
        jobTotals={jobTotals}
      />
    </div>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(JobsCloseContainer);
