import { useQuery } from 'react-query';
import useAxios from './useAxios';
import { useLocation, useNavigate } from 'react-router-dom';
import useAuthState from '../../lib/state mangment/AuthState';

export default function useGetQueryPagination(KEY: string | string[], Api: string, params: any = {}, options: any = {}, dontSearchBy?: string) {
  const axios = useAxios();
  const location = useLocation();
  let pagination = location?.search || '';
  const language = localStorage.getItem("language") ?? "en"

  const { logout } = useAuthState();
  const navigate = useNavigate();

  if (dontSearchBy && pagination.includes(dontSearchBy)) {
    const searchParams = new URLSearchParams(pagination);
    searchParams.delete(dontSearchBy);
    pagination = searchParams.toString();
  }
  if (pagination && !pagination.startsWith('?')) {
    pagination = '?' + pagination;
  }

  // Check if pagination exists and append it to the API endpoint
  const paginationParams = pagination ? pagination + '&orderById=desc' : '?orderById=desc';
  const apiUrl = Api + paginationParams;

  return useQuery(
    [Array.isArray(KEY) ? KEY.join(',') : KEY, pagination,language], async () => {
      const response = await axios.get(apiUrl, { params });
      return response.data;
    },
    {
      onError: (error: any) => {
        if (error?.response?.status === 401 || error?.response?.status === 403) {
          logout();
          navigate("/auth");
        }
      },
      refetchOnWindowFocus: false,
      ...options
    }
  );
}
