import {useState,useEffect, useCallback} from "react";
import AuthRepository from "../repositories/AuthRepository";
import {cacheData, cacheProfileData, getCachedData, getCachedProfileData} from "../slices/apiDataManager";
import {useSelector} from "react-redux";
import eventBus from "../services/eventBus";
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

let hasFetched = false;
let hasReceived = false;

// export const useProfile = () => {
//   const loggedUser = useSelector( ( store ) => store.globalVariables.loginUser );
//   const [profile, setProfile] = useState(null);
//   const [loading, setLoading] = useState(false);
//   const [error, setError] = useState("");

//   const fetchData = async () => {
//     try {
//       setLoading(true);
//       let response = await AuthRepository.profile();
//       setProfile(response.data);
//       cacheProfileData(response.data);
//     } catch (error) {
//       setError("Failed to fetch data.");
//     } finally {
//       setLoading(false);
//     }
//   };

//   const validation = () => {
//     if (!hasFetched) {
//       hasFetched = true;
//       if (!loggedUser) {
//         fetchData();
//       } else {
//         setProfile(loggedUser);
//       }
//     }
  
//       setProfile(loggedUser);
//   }

//   useEffect(() => {
//     validation();
//   }, [loggedUser]);

//   const handler = useCallback(
//     (data) => {
//       if(!getCachedData("hasReceived")){
//         cacheData("hasReceived", true);
//       hasFetched = false;
//       validation();
//       }
//     },[]
//   );

//   useEffect(() => {
//     eventBus.on("assign_project_one", handler);
//     return () => eventBus.off("assign_project_one", handler);
//   }, [handler]);

//   return { profile, loading, error };
// };

export const useProfile = () => {
  const loggedUser = useSelector((store) => store.globalVariables.loginUser);
  const queryClient = useQueryClient();

  const {
    data: profile,
    error,
    isLoading,
    refetch,
  } = useQuery({
    queryKey: ["profile"],
    queryFn: async () => {
      const response = await AuthRepository.profile();
      cacheProfileData(response.data);
      return response.data;
    },
    initialData: loggedUser || undefined,
    enabled: !loggedUser,
    staleTime: 10 * 60 * 1000,
  });

  const handler = useCallback(() => {
    queryClient.invalidateQueries({ queryKey: ["profile"] });
  }, [queryClient]);

  useEffect(() => {
    eventBus.on("assign_project_one", handler);
    return () => eventBus.off("assign_project_one", handler);
  }, [handler]);

  return {
    profile,
    loading: isLoading,
    error,
    refetch,
  };
};
