import * as React from 'react';
import { toast } from 'sonner';

/**
 * When the current URL contains `?focus=N` on mount, scroll to the table row
 * with id="row-N" and pulse it briefly so the user can spot it. Works with
 * any page that renders rows via the shared DataTable (which auto-adds the
 * `row-{id}` element id to each row).
 *
 * The focus id is captured **once** on first mount into a ref, so a sibling
 * useEffect that later rewrites the URL (e.g. a debounced filter sync)
 * cannot lose the deep-link target.
 *
 * Pass the data array as `deps` so the hook re-attempts the scroll after
 * Inertia rehydrates rows.
 */
export function useFocusRow(deps: unknown[] = []) {
    // Captured one-shot from the URL on first render. Once we have it,
    // subsequent URL rewrites by the host page don't erase the target.
    const focusRef = React.useRef<string | null>(
        typeof window === 'undefined'
            ? null
            : new URLSearchParams(window.location.search).get('focus'),
    );
    const doneRef = React.useRef(false);

    React.useEffect(() => {
        if (typeof window === 'undefined') return;
        if (doneRef.current) return;
        const focus = focusRef.current;
        if (!focus) return;

        // Try a few times — TanStack Table may not have mounted rows yet
        // immediately after Inertia hands off data.
        let attempts = 0;
        const maxAttempts = 8; // ~2s @ 250ms
        const tick = () => {
            const el = document.getElementById(`row-${focus}`);
            if (el) {
                doneRef.current = true;
                el.scrollIntoView({ behavior: 'smooth', block: 'center' });
                el.classList.add('bg-yellow-100');
                el.style.transition = 'background-color 1.5s ease-out';
                setTimeout(() => el.classList.remove('bg-yellow-100'), 2500);
                return;
            }
            attempts++;
            if (attempts >= maxAttempts) {
                doneRef.current = true;
                toast.info('Ligne non visible avec les filtres actuels — élargissez la plage de dates.');
                return;
            }
            setTimeout(tick, 250);
        };
        setTimeout(tick, 200);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, deps);
}
