import { useQuery } from "react-query";
import axios from "axios";
import Cookies from "js-cookie";

import { StarMessageListRes } from "../../types/StarMessageListTypes";
import { useAppSelector } from "../../utils/hooks";
import { useLocation } from "react-router-dom";

export const useStarMessageList = () => {
  const token = Cookies.get("whoxa_web_token");
  const CurrentConversation = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const location = useLocation();

  const updatedFields: any = {};

  // if (!MessageOptions.show_all_star_messages) {
  //   alert(MessageOptions.show_all_star_messages);
  //   updatedFields.chat_id = CurrentConversation.chat_id;
  // }
  let api_name = [];

  if (location.pathname != "/star-messages") {
    updatedFields.chat_id = CurrentConversation.chat_id;
    api_name = ["chat/starred-messages", CurrentConversation.chat_id];
  } else {
    api_name = ["chat/starred-messages"];
  }
  // console.log(
  //   CurrentConversation.chat_id,
  //   "CurrentConversation.chat_id",
  // );

  return useQuery<StarMessageListRes, Error>(
    // ["star-message-list", CurrentConversation.chat_id],
    api_name,
    async () => {
      let response = await axios.post<StarMessageListRes>(
        `${import.meta.env.VITE_API_URL}chat/starred-messages`,
        updatedFields,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );
      // // Filter out messages that are either deleted for everyone or for the current user
      // response.data.StarMessageList = response.data.StarMessageList.filter(
      //   (starMessage) =>
      //     starMessage.Chat.delete_from_everyone == false && // Exclude messages deleted for everyone
      //     !starMessage.Chat.delete_for_me.includes(userData.user_id.toString()), // Exclude messages deleted for the current user
      // );
      return response.data;
    },
    {
      // Set cache time to prevent re-fetching on route changes
      staleTime: Infinity, // Data will never be considered stale
      cacheTime: Infinity, // Data will never be removed from cache
    },
  );
};
