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

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

  const requestGeoLocation = useCallback(
    async ({ action, callback }) => {
      dispatch(
        addModal({
          status: true,
          component: Confirm,
          data: {
            confirmTitle: "Geolocation",
            confirmText: `Please Enable Geolocation to use this feature.<br /> Open setting and enable Geolocation.`,
          },
          cannotClose: true,
          accept: {
            text: "Request",
            action: async (config) => {
              await execute({
                call: async () => {
                  const result = await action();

                  if (!result) throw new Error("Geolocation Request Failed!");

                  if (callback && typeof callback === "function")
                    callback(result);
                },
                onError: "Please Enable Geolocation to use this feature.",
                onSuccess: "Geolocation Request Successfully!",
                successAction: () => {
                  dispatch(hideModalOnIndex(config?.data?.index));
                },
              });
            },
          },
        })
      );
    },
    [dispatch, execute]
  );

  return { requestGeoLocation };
};

export default useLogin;
