'use client';
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import get from "lodash/get";
import isEmpty from "lodash/isEmpty";
import size from "lodash/size";


import FetchAPIData from '@/server_api/api-functions/apifetch';
import useReport from '@/src/server_api/hooks/useReport';
import { productFilterKeys } from '@/utils/products';

export interface UseApiProps {
    pagePath?: any;
    apiEndpoint: any;
    hostName?: any;
    enableFetchApi: boolean;
    onSuccessCallback?: any;
    searchParams?: Record<string, any>;
    useFilterKeys?: boolean;
    getBlockValues?: boolean;
    pageLimit?: number;
    fetchRandom?: boolean;
    forceRefetch?: boolean;
    skipAuth?: boolean;
}

const useApi = ({
    pagePath = false,
    hostName,
    apiEndpoint,
    searchParams = {},
    useFilterKeys = false,
    enableFetchApi = false,
    onSuccessCallback,
    pageLimit = 10,
    getBlockValues = false,
    fetchRandom = false,
    forceRefetch = false,
    skipAuth = false,
}: UseApiProps) => {

    const uRS = useReport({
        fetchFunction: pagePath ? () => refetch() : undefined,
        pagePath: pagePath || "",
        page: searchParams?.page || 1,
        limit: pageLimit,
    });

    const activeURS = useFilterKeys ? uRS : {
        getCombinedParams: () => ({}),
        setRowsCount: () => { },
        filterValues: {}
    };

    const fetchAPIData = () => {
        return FetchAPIData.fetchAPIData({
            apiEndpoint,
            skipAuth,
            ...searchParams,
            ...activeURS.getCombinedParams(),
        }, hostName);
    };

    const [randomSuffix] = useState(() => fetchRandom ? Math.random() : '');

    const queryKey = useFilterKeys
        ? [apiEndpoint, searchParams?.page, searchParams?.sortorder, ...productFilterKeys.map((key: any) => activeURS.filterValues?.[key] || ''), JSON.stringify(searchParams), randomSuffix]
        : [apiEndpoint, searchParams?.page, searchParams?.sortorder, JSON.stringify(searchParams), randomSuffix];

    const { data, isLoading, refetch, error } = useQuery({
        queryKey,
        // staleTime: Infinity,
        refetchInterval: false,
        refetchOnWindowFocus: false,
        staleTime: forceRefetch ? 0 : Infinity,
        refetchOnMount: forceRefetch,
        refetchOnReconnect: false,
        refetchIntervalInBackground: false,
        queryFn: async () => {
            const retVal: any = await fetchAPIData();
            if (retVal.status) {
                if (onSuccessCallback) {
                    onSuccessCallback(retVal.requestedData, get(retVal, 'relationTargets'));
                }
                if (useFilterKeys) {
                    activeURS.setRowsCount(retVal.totalCount || 0);
                }
            }
            return retVal
        },

        enabled: Boolean(queryKey && enableFetchApi)
    });

    return {
        data: !getBlockValues
            ? get(data, 'requestedData')
            : !isEmpty(data) &&
                !isEmpty(get(data, 'requestedData')) &&
                size(get(data, 'requestedData.blockValues')) > 0
                ? get(data, 'requestedData.blockValues')
                : undefined,
        totalCount: data?.requestedData?.totalCount || data?.totalCount || 0,
        summary: get(data, 'summary'),
        isLoading,
        refetch,
        error,
        relationTargets: get(data, 'relationTargets', null),
        apiEndpoint,
        queryKey,
        uRS: activeURS as any,
    };
};

export default useApi;
