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,
  setSelfTenant,
} from "../slices/localVariablesSlice.jsx";
import { removeSession } from "../utils/authUtils.js";
import showToast from "../services/toastService.tsx";
import eventBus from "../services/eventBus.js";

// ----------------------------Modal--------------------------

export const useModal = (modalType) => {
  const dispatch = useDispatch();
  const isOpen = useSelector(
    (state) => state.localVariables.modals[modalType]?.isOpen
  );

  const onOpen = (data = {}) => dispatch(openModal({ modalType, data }));
  const onClose = () => dispatch(closeModal({ modalType }));
  const onToggle = () => dispatch(toggleModal({ modalType }));

  return { isOpen, onOpen, onClose, onToggle };
};

export const useSubscription = (frequency) => {
  return useQuery({
    queryKey: ["subscriptionPlans", frequency],
    queryFn: async () => {
      const resp = await AuthRepository.getSubscription(frequency);
      return resp.data;
    },
    enabled: frequency !== null && frequency !== undefined
  });
};

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 useCreateSelfTenant = (onSuccessCallBack, onFailureCallBack) => {
  const dispatch = useDispatch();
  return useMutation({
    mutationFn: async (payload) => {
      const resp = await AuthRepository.createSuscription(payload);
      return resp.data;
    },
    onSuccess: (response, variables) => {
      
      dispatch(
        setSelfTenant({
          tenantEnquireId: response?.id,
          planId: null,
          details:response
        })
      );
      if (onSuccessCallBack) onSuccessCallBack(response);
    },
    onError: (error) => {
      showToast("Somthing worng went happend", "error");
      if (onFailureCallBack) onFailureCallBack();
    },
  });
};

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();
    },
  });
};
