import Joi from "joi";
import React 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 { MakeGeneralIdRef } from "../../../../utils/GeneralIdRef";
import roleService from "../serrvices/rolesService";
import Loading from "../../../../components/common/Loading";
import {
  renderError,
  renderButton,
  renderUserPicker,
} from "../../../../components/common/formHelpers";
import { useFormWithGuard } from "../../../../components/common/useFormRouter";

interface LocAddUserToRoleProps {
  isEditMode: boolean;
}

const AddUserToRole: React.FC<LocAddUserToRoleProps> = ({ isEditMode }) => {
  const { domainId, roleId } = useParams<{
    domainId: string;
    roleId: string;
  }>();
  const { t } = useTranslation(Namespaces.Common);

  const labelUserId = t("User");
  const labelApply = t("Save");
  const labelSave = t("SaveAndClose");

  const form = useFormWithGuard({
    loaded: true,
    data: {
      userId: undefined,
    },
    errors: {},
    redirect: "",
  });

  form.schema = {
    userId: Joi.any().required().label(labelUserId),
  };

  const doSubmit = async (buttonName: string) => {
    try {
      const { userId } = form.state.data;
      const userIdValue = userId as any;
      const response = await roleService.postRoleUser(
        userIdValue,
        MakeGeneralIdRef(BigInt(roleId!)),
      );
      if (response) {
        toast.info(t("UserAddedToRole"));

        if (buttonName === "save")
          form.setState({
            redirect: `/domains/edit/${domainId}#securityRoles/${roleId}/users`,
          });

        form.markAsSaved();
      }
    } catch (ex: any) {
      form.handleGeneralError(ex);
    }
  };

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

  const { loaded, redirect } = form.state;
  if (redirect) return <Navigate to={redirect} />;

  return (
    <Loading loaded={loaded}>
      <form onSubmit={handleSubmit}>
        {renderError("_general", form.state.errors)}
        {renderUserPicker(
          "userId",
          labelUserId,
          form.state.data,
          form.state.errors,
          form.handleUserPickerChange,
        )}

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

export default AddUserToRole;
