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 JobChecklist from "../../components/job-checklist/job-checklist.component";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import { QUERY_INTAKE_CHECKLIST } from "../../graphql/bodyshop.queries";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { Card, Result } from "antd";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import FeatureWrapperComponent from "../../components/feature-wrapper/feature-wrapper.component";
import UpsellComponent, { upsellEnum } from "../../components/upsell/upsell.component";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

export function JobsIntakeContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
  const { t } = useTranslation();
  const { jobId } = useParams();

  const { loading, error, data } = useQuery(QUERY_INTAKE_CHECKLIST, {
    variables: { shopId: bodyshop.id, jobId: jobId },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  useEffect(() => {
    document.title = t("titles.jobs-intake", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    });
    setSelectedHeader("activejobs");
    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?.ro_number || t("general.labels.na"))
        })
      },
      {
        link: `/manage/jobs/${jobId}/intake`,
        label: t("titles.bc.jobs-intake")
      }
    ]);
  }, [t, setBreadcrumbs, jobId, data, setSelectedHeader]);

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent title={error.message} type="error" />;

  if (data && !data.bodyshops_by_pk.intakechecklist)
    return <AlertComponent title={t("intake.errors.nochecklist")} type="error" />;

  return (
    <FeatureWrapperComponent
      featureName="checklist"
      noauth={
        <Card>
          <UpsellComponent upsell={upsellEnum().checklist.general} />
        </Card>
      }
    >
      <RbacWrapper action="jobs:intake">
        <div>
          {!!data.jobs_by_pk.intakechecklist ||
          !bodyshop.md_ro_statuses.pre_production_statuses.includes(data.jobs_by_pk.status) ? (
            <Result status="warning" title={t("jobs.errors.cannotintake")} />
          ) : (
            <JobChecklist
              type="intake"
              checklistConfig={(data && data.bodyshops_by_pk.intakechecklist) || {}}
              job={data?.jobs_by_pk}
            />
          )}
        </div>
      </RbacWrapper>
    </FeatureWrapperComponent>
  );
}

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