import Joi from "joi";
import React, { useEffect } from "react";
import { Navigate, useParams } from "react-router-dom";
import { toast } from "react-toastify";
import { useTranslation } from "react-i18next";
import { Namespaces } from "../../../../i18n/i18n";
import { InputType } from "../../../../components/common/Input";
import { MakeGeneralIdRef } from "../../../../utils/GeneralIdRef";
import mailTemplatesService from "../serrvices/mailTemplatesService";
import {
  renderError,
  renderButton,
  renderInput,
  renderTemplateEditor,
} from "../../../../components/common/formHelpers";
import { useFormWithGuard } from "../../../../components/common/useFormRouter";

interface EmailTemplateEditorProps {
  domainId?: string;
  currentMailType: string;
}

const EmailTemplateEditor: React.FC<EmailTemplateEditorProps> = ({
  domainId,
  currentMailType,
}) => {
  const { t } = useTranslation(Namespaces.Common);
  const paramsData = useParams<{ domainId: string }>();
  const finalDomainId = domainId || paramsData.domainId;

  const labelName = t("Subject");
  const labelDefinition = t("Definition");
  const labelApply = t("Save");
  const labelSave = t("SaveAndClose");

  const form = useFormWithGuard({
    loaded: false,
    data: {
      currentMailType: undefined,
      isOverridden: false,
      subject: "",
      definition: "",
    },
    errors: {},
    redirect: "",
  });

  form.schema = {
    currentMailType: Joi.optional(),
    isOverridden: Joi.optional(),
    subject: Joi.string().required().max(450).label(labelName),
    definition: Joi.string().required().label(labelDefinition),
  };

  useEffect(() => {
    const loadTemplate = async () => {
      try {
        if (!finalDomainId || !currentMailType) return;

        // Reset form state while loading
        form.setState({
          loaded: false,
          data: {
            currentMailType: undefined,
            isOverridden: false,
            subject: "",
            definition: "",
          },
        });

        const domainIdValue = BigInt(finalDomainId);
        var mailTemplate = await mailTemplatesService.getTemplate(
          MakeGeneralIdRef(domainIdValue),
          currentMailType,
        );

        if (mailTemplate !== null) {
          form.setState({
            loaded: true,
            data: {
              currentMailType: currentMailType,
              isOverridden: mailTemplate.isOverridden,
              subject: mailTemplate.subject,
              definition: mailTemplate.templateDefinition,
            },
          });
        }
      } catch (ex: any) {
        form.handleGeneralError(ex);
      }
    };

    void loadTemplate();
  }, [finalDomainId, currentMailType]); // eslint-disable-line react-hooks/exhaustive-deps

  const doSubmit = async (buttonName: string) => {
    try {
      const { subject, definition } = form.state.data;
      if (!finalDomainId) return;
      const domainGeneralIdRef = MakeGeneralIdRef(BigInt(finalDomainId));
      const subjectStr = typeof subject === "string" ? subject : "";
      const definitionStr = typeof definition === "string" ? definition : "";
      const response = await mailTemplatesService.postTemplate(
        domainGeneralIdRef,
        currentMailType,
        subjectStr,
        definitionStr,
      );
      if (response) {
        toast.info(t("EmailTemplateSaved"));
        if (buttonName === labelSave) form.setState({ redirect: "/domains" });
      }
    } catch (ex: any) {
      form.handleGeneralError(ex);
    }
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    form.handleSubmit(e, doSubmit);
  };

  const { redirect } = form.state;
  const { isOverridden } = form.state.data;
  const isOverriddenValue = Boolean(isOverridden);
  if (redirect) return <Navigate to={redirect} />;

  return (
    <>
      <div style={{ position: "relative" }}>
        {isOverriddenValue && (
          <p>{t("ThisTemplateIsCustomForThisDomainOnly")}</p>
        )}
        {!isOverriddenValue && (
          <p>{t("TheDetailsBelowAreLoadedFromMasterTemplate")}</p>
        )}

        <form
          onSubmit={handleSubmit}
          template-name={currentMailType}
          key={currentMailType}
        >
          {renderError("_general", form.state.errors)}
          {renderInput(
            "subject",
            labelName,
            form.state.data,
            form.state.errors,
            InputType.text,
            false,
            "",
            "",
            0,
            true,
            undefined,
            form.handleChange,
          )}
          {renderTemplateEditor(
            "mailTemplate-editor",
            "definition",
            labelDefinition,
            form.state.data,
            false,
            form.handleTemplateEditorChange,
          )}

          {renderButton(labelApply, form.state.errors, "apply")}
          {renderButton(labelSave, form.state.errors, "save")}
        </form>
      </div>
    </>
  );
};

export default EmailTemplateEditor;
