import React from "react";
import usePostManagement from "./usePostManagement";
import { useDispatch } from "react-redux";
import Confirm from "@/components/administrator/modals/Confirm/confirm";
import {
  addModal,
  hideModalOnIndex,
} from "@/utils/store/features/ui/modal.slice";
import { grantTokenById, revokeTokenById } from "@/services/users";

const useUserToken = () => {
  const dispatch = useDispatch();
  const { execute } = usePostManagement();

  const revokeToken = async (id, callback) => {
    dispatch(
      addModal({
        status: true,
        component: Confirm,
        data: {
          confirmTitle: "Revoke User",
          confirmText: "Are you sure you want to revoke this user?",
        },
        accept: {
          text: "Revoke",
          action: async (config) => {
            await execute({
              call: async () => {
                const result = await revokeTokenById(id);
                if (callback && typeof callback === "function")
                  callback(result);
              },
              onError: "Revoking User Failed! Contact Administrator.",
              onSuccess: "Revoked User Successfully!",
              successAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
              errorAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
            });
          },
        },
      })
    );
  };

  const grantToken = async (id, callback) => {
    await execute({
      call: async () => {
        const result = await grantTokenById(id);
        if (callback && typeof callback === "function") callback(result);
      },
      onError: "Granting User Failed! Contact Administrator.",
      onSuccess: "Granting User Successfully!",
    });
  };

  return { revokeToken, grantToken };
};

export default useUserToken;
