import { useQuery } from "@apollo/client";
import { Col, Row, Typography } from "antd";
import dayjs from "../../utils/day";
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 JobChecklistForm from "../../components/job-checklist/components/job-checklist-form/job-checklist-form.component";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { QUERY_JOB_CHECKLISTS } from "../../graphql/jobs.queries";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

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

export function JobsChecklistViewContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
  const { t } = useTranslation();
  const { jobId } = useParams();
  const { loading, error, data } = useQuery(QUERY_JOB_CHECKLISTS, {
    variables: { id: jobId },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

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

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

  //The Form is the actual config to use.

  const CompletedBy = ({ checklist }) => (
    <div>
      <div>
        {t("jobs.labels.checklistcompletedby", {
          by: checklist.completed_by,
          at: dayjs(checklist.completed_at).format("MM/DD/YYYY @ h:mm a")
        })}
      </div>
    </div>
  );

  return (
    <RbacWrapper action="jobs:checklist-view">
      <Row gutter={[16, 16]}>
        <Col span={12}>
          <Typography.Title level={4}>{t("jobs.labels.intakechecklist")}</Typography.Title>
          {data.jobs_by_pk.intakechecklist && data.jobs_by_pk.intakechecklist.form && (
            <>
              <JobChecklistForm
                formItems={data.jobs_by_pk.intakechecklist && data.jobs_by_pk.intakechecklist.form}
                type="intake"
                job={data.jobs_by_pk}
                readOnly
              />
              <CompletedBy checklist={data.jobs_by_pk.intakechecklist} />
            </>
          )}
        </Col>
        <Col span={12}>
          <Typography.Title level={4}>{t("jobs.labels.deliverchecklist")}</Typography.Title>
          {data.jobs_by_pk.deliverchecklist && data.jobs_by_pk.deliverchecklist.form && (
            <>
              <JobChecklistForm
                formItems={data.jobs_by_pk.deliverchecklist && data.jobs_by_pk.deliverchecklist.form}
                type="deliver"
                job={data.jobs_by_pk}
                readOnly
              />
              <CompletedBy checklist={data.jobs_by_pk.deliverchecklist} />
            </>
          )}
        </Col>
      </Row>
    </RbacWrapper>
  );
}

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