import { useMutation, useQuery } from "@apollo/client/react";
import { Form } from "antd";
import dayjs from "../../utils/day";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useParams } from "react-router-dom";
import AlertComponent from "../../components/alert/alert.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { QUERY_CC_BY_PK, UPDATE_CC } from "../../graphql/courtesy-car.queries";
import { addRecentItem, setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { CreateRecentItem } from "../../utils/create-recent-item";
import UndefinedToNull from "./../../utils/undefinedtonull";
import CourtesyCarDetailPageComponent from "./courtesy-car-detail.page.component";
import NotFound from "../../components/not-found/not-found.component";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import queryString from "query-string";
import { pageLimit } from "../../utils/config";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function CourtesyCarDetailPageContainer({ setBreadcrumbs, addRecentItem, setSelectedHeader }) {
  const searchParams = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder } = searchParams;
  const notification = useNotification();

  const { t } = useTranslation();
  const [updateCourtesyCar] = useMutation(UPDATE_CC);
  const [form] = Form.useForm();
  const { ccId } = useParams();
  const [saveLoading, setSaveLoading] = useState(false);
  const { loading, error, data } = useQuery(QUERY_CC_BY_PK, {
    variables: {
      id: ccId,
      offset: page ? (page - 1) * pageLimit : 0,
      limit: pageLimit,
      order: [
        {
          [sortcolumn || "start"]: sortorder ? (sortorder === "descend" ? "desc" : "asc") : "desc"
        }
      ]
    },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  useEffect(() => {
    setSelectedHeader("courtesycarsall");

    document.title = loading
      ? InstanceRenderManager({
          imex: t("titles.imexonline"),
          rome: t("titles.romeonline")
        })
      : error
        ? InstanceRenderManager({
            imex: t("titles.imexonline"),
            rome: t("titles.romeonline")
          })
        : t("titles.courtesycars-detail", {
            app: InstanceRenderManager({
              imex: "$t(titles.imexonline)",
              rome: "$t(titles.romeonline)"
            }),
            id: (data?.courtesycars_by_pk && data.courtesycars_by_pk.fleet_number) || ""
          });
    setBreadcrumbs([
      { link: "/manage/courtesycars", label: t("titles.bc.courtesycars") },
      {
        link: `/manage/courtesycars/${(data?.courtesycars_by_pk && data.courtesycars_by_pk.id) || ""}`,
        label: t("titles.bc.courtesycars-detail", {
          number: (data?.courtesycars_by_pk && data.courtesycars_by_pk.fleetnumber) || ""
        })
      }
    ]);

    if (data?.courtesycars_by_pk)
      addRecentItem(
        CreateRecentItem(
          ccId,
          "courtesycar",
          data.courtesycars_by_pk.fleet_number || data.courtesycars_by_pk.vin,
          `/manage/courtesycars/${ccId}`
        )
      );
  }, [t, data, error, loading, setBreadcrumbs, ccId, addRecentItem, setSelectedHeader]);

  const handleFinish = async (values) => {
    setSaveLoading(true);

    const result = await updateCourtesyCar({
      variables: {
        cc: { ...UndefinedToNull(values, ["readiness"]) },
        ccId: ccId
      },
      refetchQueries: ["QUERY_CC_BY_PK"],
      awaitRefetchQueries: true
    });

    if (result.errors) {
      notification.error({
        title: t("courtesycars.errors.saving", { error: error })
      });
    }

    notification.success({
      title: t("courtesycars.successes.saved")
    });

    setSaveLoading(false);
  };

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

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

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

  return (
    <RbacWrapper action="courtesycar:detail">
      <Form
        form={form}
        autoComplete="no"
        onFinish={handleFinish}
        layout="vertical"
        initialValues={
          data
            ? {
                ...data.courtesycars_by_pk,
                purchasedate: data.courtesycars_by_pk.purchasedate ? dayjs(data.courtesycars_by_pk.purchasedate) : null,
                servicestartdate: data.courtesycars_by_pk.servicestartdate
                  ? dayjs(data.courtesycars_by_pk.servicestartdate)
                  : null,
                serviceenddate: data.courtesycars_by_pk.serviceenddate
                  ? dayjs(data.courtesycars_by_pk.serviceenddate)
                  : null,
                leaseenddate: data.courtesycars_by_pk.leaseenddate ? dayjs(data.courtesycars_by_pk.leaseenddate) : null,
                nextservicedate: data.courtesycars_by_pk.nextservicedate
                  ? dayjs(data.courtesycars_by_pk.nextservicedate)
                  : null,
                registrationexpires: data.courtesycars_by_pk.registrationexpires
                  ? dayjs(data.courtesycars_by_pk.registrationexpires)
                  : null,
                insuranceexpires: data.courtesycars_by_pk.insuranceexpires
                  ? dayjs(data.courtesycars_by_pk.insuranceexpires)
                  : null
              }
            : {}
        }
      >
        <CourtesyCarDetailPageComponent
          contracts={data ? data.courtesycars_by_pk.cccontracts : []}
          form={form}
          saveLoading={saveLoading}
          totalContracts={data ? data.courtesycars_by_pk.cccontracts_aggregate.aggregate.count : 0}
        />
      </Form>
    </RbacWrapper>
  );
}

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