import { router, usePage } from "@inertiajs/react";
import { useCallback, useMemo } from "react";

export interface QueryParams {
    search?: string;
    sort?: string;
    order?: 'asc' | 'desc';
    page?: number;
    per_page?: number;
    [key: string]: any; // Allow other potential query params
}

export function useQueryParams(): [QueryParams, (params: Partial<QueryParams>) => void] {
    const { url, props } = usePage();

    // Parse dari usePage props yang mungkin berisi query params, 
    // fallback ke window location jika tersedia
    const currentParams = useMemo(() => {
        let finalUrl = url;

        // Jika kita di browser, gunakan URL sebenarnya
        if (typeof window !== 'undefined') {
            finalUrl = window.location.href;
        }

        const currentUrl = new URL(finalUrl, window?.location?.origin || 'http://localhost');
        const searchParams = currentUrl.searchParams;
        const params: QueryParams = {};

        // Convert URLSearchParams to typed object
        for (const [key, value] of searchParams.entries()) {
            if (key === 'page' || key === 'per_page') {
                params[key] = parseInt(value, 10);
            } else if (key === 'order') {
                params[key] = value as 'asc' | 'desc';
            } else {
                params[key] = value;
            }
        }

        return params;
    }, [url, props]); // Dependency pada url dan props agar reactive

    const updateParams = useCallback((newParams: Partial<QueryParams>) => {
        // Get current params fresh untuk menghindari stale closure
        const freshUrl = typeof window !== 'undefined' ? window.location.href : url;
        const currentUrl = new URL(freshUrl, window?.location?.origin || 'http://localhost');
        const currentSearchParams = currentUrl.searchParams;
        const freshParams: QueryParams = {};

        for (const [key, value] of currentSearchParams.entries()) {
            if (key === 'page' || key === 'per_page') {
                freshParams[key] = parseInt(value, 10);
            } else if (key === 'order') {
                freshParams[key] = value as 'asc' | 'desc';
            } else {
                freshParams[key] = value;
            }
        }

        // Merge new params dengan fresh params
        const finalParams = { ...freshParams };

        // Apply new params, dengan logic khusus untuk undefined (hapus dari URL)
        Object.entries(newParams).forEach(([key, value]) => {
            if (value === undefined || value === null || value === '') {
                // Hapus parameter dari URL jika value undefined/null/empty
                delete finalParams[key];
            } else {
                finalParams[key] = value;
            }
        });

        // Remove page if we're updating other filters (except when explicitly setting page)
        if (newParams.page === undefined && (newParams.search !== undefined || newParams.sort !== undefined || newParams.per_page !== undefined)) {
            delete finalParams.page;
        }

        // Use current base URL without query string
        const baseUrl = url.split('?')[0];

        // Tanpa menggunakan 'only' untuk memastikan data update
        router.get(baseUrl, finalParams, {
            preserveState: true,
            preserveScroll: true,
            replace: true,
            onSuccess: () => {
                //
            },
            onError: (error) => {
                console.error('Error updating params:', error);
            }
        });
    }, [url]);

    return [currentParams, updateParams];
}