import { useRouter } from "next/navigation";
import {
  addPost,
  // deleteMultiplePosts,
  // deletePost,
  // publishMultiplePost,
  // publishPost,
  // revertPublishedPost,
  switchLockPost,
  // unpublishMultiplePost,
  // unpublishPost,
  // updatePost,
} from "@/services/posts";
import { setNotification as setNotif } from "@/utils/store/features/ui/notification.slice";
import { useDispatch } from "react-redux";
import {
  addModal,
  hideModalOnIndex,
} from "@/utils/store/features/ui/modal.slice";
import Confirm from "@/components/administrator/modals/Confirm/confirm";
import { useCallback } from "react";
import { postsServices } from "@/app/services/api/posts.services";

const usePostManagement = () => {
  const dispatch = useDispatch();
  const router = useRouter();

  const execute = useCallback(
    async ({
      call,
      onError,
      onSuccess,
      successAction,
      errorAction,
      finallyAction,
    }) => {
      try {
        const data = await call();

        dispatch(
          setNotif({
            status: true,
            message: onSuccess,
            timeout: 3000,
          })
        );

        if (successAction && typeof successAction === "function")
          successAction(data);

        return data;
      } catch (error) {
        console.log({ error });
        dispatch(
          setNotif({
            status: true,
            message: onError,
            type: "error",
            timeout: 3000,
          })
        );

        if (errorAction && typeof errorAction === "function")
          errorAction(error);
      } finally {
        if (finallyAction && typeof finallyAction === "function")
          finallyAction();
      }
    },
    [dispatch]
  );

  const createPost = async (idUser, callback) => {
    await execute({
      call: async () => {
        const result = await addPost(idUser);
        if (callback && typeof callback === "function") callback(result);
      },
      onError: "Creating Post Failed! Contact Administrator.",
      onSuccess: "Created Post Successfully! Redirecting...",
    });
  };

  const save = async (data, callback) => {
    await execute({
      call: async () => {
        const result = await postsServices.updatePost(data);
        if (callback && typeof callback === "function") callback(result);
      },
      onError: "Updating Post Failed! Contact Administrator.",
      onSuccess: "Updated Post Successfully!",
    });
  };

  const multipleUpdatePost = async (data, status, callback) => {
    await execute({
      call: async () => {
        const role = {
          // send multiple data property
          published: async () => await postsServices.publishMultiplePost(data),
          // send single data property (_id)
          draft: async () => {
            return await postsServices.unpublishMultiplePost(
              data.map((item) => item._id)
            );
          },
        };

        const result = await role[status]();
        if (callback && typeof callback === "function") callback(result);
      },
      onError: "Updating Posts Failed! Contact Administrator.",
      onSuccess: "Updated Posts Successfully!",
    });
  };

  const publish = async (data, callback) => {
    await execute({
      call: async () => {
        const result = await postsServices.publishPost(data);
        if (callback && typeof callback === "function") callback(result);
      },
      onError: "Publishing Post Failed! Contact Administrator.",
      onSuccess: "Published Post Successfully!",
    });
  };

  const unpublish = async (data, callback) => {
    await execute({
      call: async () => {
        const result = await postsServices.unpublishPost(data._id);
        if (callback && typeof callback === "function") callback(result);
      },
      onError: "Unpublishing Post Failed! Contact Administrator.",
      onSuccess: "Unpublished Post Successfully!",
    });
  };

  const revert = async (data, callback) => {
    execute({
      call: async () => {
        // const result = await revertPublishedPost(data._id);
        const result = await postsServices.revertPublish(data._id);
        // console.log({ result });
        if (callback && typeof callback === "function") callback(result);
      },
      onError: "Reverting Post Failed! Contact Administrator.",
      onSuccess: "Reverted Post Successfully!",
    });
  };

  const deleteconfirm = async (data, callback = () => {}) => {
    dispatch(
      addModal({
        status: true,
        component: Confirm,
        data: {
          confirmTitle: "Delete Post",
          confirmText: "Are you sure you want to delete this post?",
        },
        accept: {
          text: "Delete",
          action: async (config) => {
            await execute({
              call: async () => {
                const result = await postsServices.deletePost(data._id);
                if (callback && typeof callback === "function")
                  callback(result);
              },
              onError: "Deleting Post Failed! Contact Administrator.",
              onSuccess: "Deleted Post Successfully! Redirecting...",
              successAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
                setTimeout(() => {
                  router.push("/dashboard/posts");
                }, 3000);
              },
              errorAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
            });
          },
        },
      })
    );
  };

  const deleteconfirmMultiple = async (ids, callback = () => {}) => {
    dispatch(
      addModal({
        status: true,
        component: Confirm,
        data: {
          confirmTitle: "Delete Posts",
          confirmText: `Are you sure you want to delete ${ids.length} posts?`,
        },
        accept: {
          text: "Delete",
          action: async (config) => {
            await execute({
              call: async () => {
                const result = await postsServices.deleteMultiplePosts(ids);
                if (callback && typeof callback === "function")
                  callback(result);
              },
              onError: "Deleting Posts Failed! Contact Administrator.",
              onSuccess: "Deleted Posts Successfully!",
              successAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
              errorAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
            });
          },
        },
      })
    );
  };

  const handleClickToEdit = async (data, user) => {
    if (!data.isEditing || data?.onEditing?.user_id === user._id) {
      router.push(`/dashboard/posts/${data._id}`);
      return;
    }

    // const isMe = data.onEditing.user_id === user._id;

    // if (isMe) {
    //   return dispatch(
    //     setNotif({
    //       status: true,
    //       type: "error",
    //       message: "You are currently editing this post.",
    //       timeout: 3000,
    //     })
    //   );
    // }

    dispatch(
      addModal({
        status: true,
        component: Confirm,
        data: {
          confirmTitle: `${data.onEditing.status} the Post`,
          confirmText: `Are you sure you want to edit the post that ${data.onEditing.user.name} is currently editing?<br/>
If you edit this post, ${data.onEditing.user.name} will be forced out of the editor.`,
        },
        accept: {
          text: "Edit",
          action: async (config) => {
            await execute({
              call: async () => {
                const result = await switchLockPost(data._id, user._id);
              },
              onError: "Redirect to editor post failed! Contact Administrator.",
              onSuccess: "Redirect to editor ...",
              successAction: () => {
                router.push(`/dashboard/posts/${data._id}`);
                dispatch(hideModalOnIndex(config?.data?.index));
              },
              errorAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
            });
          },
        },
      })
    );
  };

  return {
    execute,
    createPost,
    save,
    multipleUpdatePost,
    publish,
    unpublish,
    revert,
    deleteconfirm,
    deleteconfirmMultiple,
    handleClickToEdit,
  };
};

export default usePostManagement;
