"use client";

import React, { useCallback, useEffect } from "react";
import { usePathname } from "next/navigation";

import { useDispatch } from "react-redux";
import axios from "axios";

import { useInterval } from "@/hooks/useInterval";
import { addModal } from "@/utils/store/features/ui/modal.slice";
import PostSwitched from "@/components/administrator/modals/PostSwitched/post.switched";

const PostHeartBeat = ({ uid, visibility, children }) => {
  const pathname = usePathname();
  const dispatch = useDispatch();

  const execute = useCallback(async () => {
    try {
      const post_id = pathname.split("/").pop();
      const response = await axios.post(
        `/api/posts/heartbeat?post_id=${post_id}&uid=${uid}`
      );
    } catch (error) {
      console.log({ error });
      dispatch(
        addModal({
          status: true,
          component: PostSwitched,
          data: error?.response?.data || {},
          cannotClose: true,
        })
      );
      throw error;
    }
  }, [pathname, uid, dispatch]);

  useInterval(
    async () => {
      await execute();
    },
    5000,
    visibility
  );

  useEffect(() => {
    const realeseLock = () => {
      const post_id = pathname.split("/").pop();

      navigator.sendBeacon(`/api/posts/realese?post_id=${post_id}&uid=${uid}`);
    };

    // beforeunload
    window.addEventListener("beforeunload", realeseLock);

    return () => {
      // if realeseLock is uncomment on this block, will error
      // realeseLock();
      window.removeEventListener("beforeunload", realeseLock);
    };
  }, []);

  return <>{children}</>;
};

export default PostHeartBeat;
