import { useQuery } from "@apollo/client/react";
import { Card, Col, Row, Typography } from "antd";
import dayjs from "../../utils/day";
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 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 InstanceRenderManager from "../../utils/instanceRenderMgr";
import FeatureWrapperComponent from "../../components/feature-wrapper/feature-wrapper.component";
import UpsellComponent, { upsellEnum } from "../../components/upsell/upsell.component";

const mapStateToProps = createStructuredSelector({});
const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

export function JobsChecklistViewContainer({ 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)"
      })
    });
    setSelectedHeader("activejobs");
    setBreadcrumbs([
      { link: "/manage/jobs", label: t("titles.bc.jobs") },
      {
        link: `/manage/jobs/${jobId}`,
        label: t("titles.bc.jobs-detail", {
          number: (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 title={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 (
    <FeatureWrapperComponent
      featureName="checklist"
      noauth={
        <Card>
          <UpsellComponent upsell={upsellEnum().checklist.general} />
        </Card>
      }
    >
      <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?.form && (
              <>
                <JobChecklistForm
                  formItems={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?.form && (
              <>
                <JobChecklistForm
                  formItems={data.jobs_by_pk.deliverchecklist?.form}
                  type="deliver"
                  job={data.jobs_by_pk}
                  readOnly
                />
                <CompletedBy checklist={data.jobs_by_pk.deliverchecklist} />
              </>
            )}
          </Col>
        </Row>
      </RbacWrapper>
    </FeatureWrapperComponent>
  );
}

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