import { useMutation, useQuery } from "@apollo/client";
import { Card, Form, notification } from "antd";
import dayjs from "../../utils/day";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useParams } from "react-router-dom";
import AlertComponent from "../../components/alert/alert.component";
import CourtesyCarReturnModalContainer from "../../components/courtesy-car-return-modal/courtesy-car-return-modal.container";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { QUERY_CONTRACT_BY_PK, UPDATE_CONTRACT } from "../../graphql/cccontracts.queries";
import { addRecentItem, setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { CreateRecentItem } from "../../utils/create-recent-item";
import ContractDetailPageComponent from "./contract-detail.page.component";
import NotFound from "../../components/not-found/not-found.component";
import FeatureWrapperComponent from "../../components/feature-wrapper/feature-wrapper.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import UpsellComponent, { upsellEnum } from "../../components/upsell/upsell.component";

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

export function ContractDetailPageContainer({ setBreadcrumbs, addRecentItem, setSelectedHeader }) {
  const { t } = useTranslation();
  const [updateContract] = useMutation(UPDATE_CONTRACT);
  const [saveLoading, setsaveLoading] = useState(false);
  const [form] = Form.useForm();
  const { contractId } = useParams();

  const { loading, error, data, refetch } = useQuery(QUERY_CONTRACT_BY_PK, {
    variables: { id: contractId },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  useEffect(() => {
    setSelectedHeader("contracts");
    document.title = loading
      ? InstanceRenderManager({
          imex: t("titles.imexonline"),
          rome: t("titles.romeonline")
        })
      : error
        ? InstanceRenderManager({
            imex: t("titles.imexonline"),
            rome: t("titles.romeonline")
          })
        : t("titles.contracts-detail", {
            id: (data && data.cccontracts_by_pk && data.cccontracts_by_pk.agreementnumber) || ""
          });

    setBreadcrumbs([
      { link: "/manage/courtesycars", label: t("titles.bc.courtesycars") },
      {
        link: "/manage/courtesycars/contracts",
        label: t("titles.bc.contracts")
      },
      {
        link: "/manage/courtesycars/contracts/new",
        label: t("titles.bc.contracts-detail", {
          number: (data && data.cccontracts_by_pk && data.cccontracts_by_pk.agreementnumber) || ""
        })
      }
    ]);

    if (data && data.cccontracts_by_pk)
      addRecentItem(
        CreateRecentItem(
          contractId,
          "contract",
          data.cccontracts_by_pk.agreementnumber,
          `/manage/courtesycars/contracts/${contractId}`
        )
      );
  }, [t, data, error, loading, setBreadcrumbs, addRecentItem, contractId, setSelectedHeader]);

  const handleFinish = async (values) => {
    setsaveLoading(true);
    const result = await updateContract({
      variables: { cccontract: { ...values }, contractId: contractId }
    });
    if (!!result.errors) {
      notification["error"]({
        message: t("contracts.errors.saving", {
          message: JSON.stringify(result.errors)
        })
      });
      return;
    }
    notification["success"]({ message: t("contracts.successes.saved") });
    if (refetch) await refetch();
    setsaveLoading(false);

    form.resetFields();
    form.resetFields();
  };

  useEffect(() => {
    if (data && data.cccontracts_by_pk) form.resetFields();
  }, [data, form]);

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

  if (!data.cccontracts_by_pk) return <NotFound />;

  return (
    <FeatureWrapperComponent
      featureName="courtesycars"
      noauth={
        <Card>
          <UpsellComponent upsell={upsellEnum().courtesycars.general} />
        </Card>
      }
    >
      <RbacWrapper action="contracts:detail">
        <div>
          <CourtesyCarReturnModalContainer />
          <Form
            form={form}
            autoComplete="no"
            layout="vertical"
            onFinish={handleFinish}
            initialValues={{
              ...data.cccontracts_by_pk,
              start: data.cccontracts_by_pk.start ? dayjs(data.cccontracts_by_pk.start) : null,
              scheduledreturn: data.cccontracts_by_pk.scheduledreturn
                ? dayjs(data.cccontracts_by_pk.scheduledreturn)
                : null,
              actualreturn: data.cccontracts_by_pk.actualreturn ? dayjs(data.cccontracts_by_pk.actualreturn) : null,
              driver_dlexpiry: data.cccontracts_by_pk.driver_dlexpiry
                ? dayjs(data.cccontracts_by_pk.driver_dlexpiry)
                : null,
              driver_dob: data.cccontracts_by_pk.driver_dob ? dayjs(data.cccontracts_by_pk.driver_dob) : null
            }}
          >
            <ContractDetailPageComponent
              contract={data ? data.cccontracts_by_pk : null}
              job={data ? data.cccontracts_by_pk.job : null}
              courtesyCar={data ? data.cccontracts_by_pk.courtesycar : null}
              refetch={refetch}
              form={form}
              saveLoading={saveLoading}
            />
          </Form>
        </div>
      </RbacWrapper>
    </FeatureWrapperComponent>
  );
}

export default connect(null, mapDispatchToProps)(ContractDetailPageContainer);
