import { useState, useEffect, useCallback } from "react";
import {
  Mutation,
  useMutation,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";
import { Link, useNavigate } from "react-router-dom";
import AuthRepository from "../repositories/AuthRepository.jsx";
import { useDispatch, useSelector } from "react-redux";
import {
  closeAuthModal,
  openAuthModal,
} from "../slices/localVariablesSlice.jsx";
import { removeSession } from "../utils/authUtils.js";

export const useTenants = () => {
  return useQuery({
    queryKey: ["tenantlist"],
    queryFn: async () => await AuthRepository.getTenantList(),
  });
};

export const useSelectTenant = (onSuccessCallBack) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (tenantId) => {
      const res = await AuthRepository.selectTenant(tenantId);
      return res.data;
    },

    onSuccess: (data) => {
      if (localStorage.getItem("jwtToken")) {
        localStorage.setItem("jwtToken", data.token);
        localStorage.setItem("refreshToken", data.refreshToken);
      } else {
        sessionStorage.setItem("jwtToken", data.token);
        sessionStorage.setItem("refreshToken", data.refreshToken);
      }

      if (onSuccessCallBack) onSuccessCallBack();
    },

    onError: (error) => {
      showToast(error.message || "Error while creating project", "error");
      localStorage.removeItem("jwtToken");
      localStorage.removeItem("refreshToken");
      localStorage.removeItem("ctnt");
    },
  });
};

export const useAuthModal = () => {
  const dispatch = useDispatch();
  const { isOpen } = useSelector((state) => state.localVariables.AuthModal);

  return {
    isOpen,
    onOpen: () => dispatch(openAuthModal()),
    onClose: () => dispatch(closeAuthModal()),
  };
};


export const useLogout = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async () => {
      let payload = { refreshToken: localStorage.getItem("refreshToken") || sessionStorage.getItem("refreshToken") };
      return await AuthRepository.logout(payload);
    },

    onSuccess: (data) => {
      removeSession()

      window.location.href = "/auth/login";
      if (onSuccessCallBack) onSuccessCallBack();
    },

    onError: (error) => {
      showToast(error.message || "Error while creating project", "error");
      removeSession()
    },
  });
};
