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,
  closeModal,
  openAuthModal,
  openModal,
  setSelfTenant,
  toggleModal,
} from "../slices/localVariablesSlice.jsx";
import { removeSession } from "../utils/authUtils.js";
import { cacheProfileData } from "../slices/apiDataManager.jsx";
import { blockUI } from "../utils/blockUI.js";
import showToast from "../services/toastService";

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

export const useModal = (modalType) => {
  const dispatch = useDispatch();

  const modalState = useSelector(
    (state) => state.localVariables.modals[modalType] || {}
  );

  const { isOpen = false, data = null } = modalState;

  const onOpen = (payload = {}) =>
    dispatch(openModal({ modalType, data: payload }));

  const onClose = () => dispatch(closeModal({ modalType }));

  const onToggle = () => dispatch(toggleModal({ modalType }));

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


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

// -------------------APIHook-------------------------------------

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(
        `${error?.response?.data?.errors || ""} ${
          error?.response?.data?.message || ""
        } ${error?.response?.data?.statusCode || ""}`.trim() ||
          error?.message ||
          "Something went wrong, please try again!",
        "error"
      );

      if (onFailureCallBack) onFailureCallBack();
    },
  });
};

export const useSelfGetSubscription = (onSuccessCallBack,onFailureCallBack) => {
  const dispatch = useDispatch();
  return useMutation({
    mutationFn: async (payload) => {
      blockUI();
      const resp = await AuthRepository.selfCreateSubscription(payload);
      return resp.data;
    },
    onSuccess: (response, variables) => {
      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();
  const navigate = useNavigate();
  const dispatch = useDispatch();

  return useMutation({
    mutationFn: async () => {
      const refreshToken =
        localStorage.getItem("refreshToken") ||
        sessionStorage.getItem("refreshToken");

      if (!refreshToken) return; // no call if already removed

      return await AuthRepository.logout({ refreshToken });
    },

    onMutate: async () => {
      // Cancel all ongoing queries
      await queryClient.cancelQueries();
    },

    onSuccess: () => {
      queryClient.clear();
      removeSession();
      dispatch(cacheProfileData(null));
      navigate("/auth/login", { replace: true });
    },

    onError: () => {
      removeSession();
      queryClient.clear();
      navigate("/auth/login", { replace: true });
    },
  });
};
