import { useState, useEffect, useCallback, useRef } from 'react';

export function useApi(endpoint, options = {}) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    const optionsRef = useRef(options || {});
    const method = options?.method;

    useEffect(() => {
        optionsRef.current = options || {};
    }, [options]);

    const fetchData = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            const requestOptions = optionsRef.current || {};
            const config = window.InvizoConfig || { 
                apiUrl: 'http://localhost/wp-json/invizo-subs/v1/', 
                nonce: '' 
            };
            
            const response = await fetch(`${config.apiUrl}${endpoint}`, {
                ...requestOptions,
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': config.nonce,
                    ...(requestOptions.headers || {})
                }
            });

            if (!response.ok) {
                throw new Error(`Error: ${response.statusText}`);
            }

            const result = await response.json();
            setData(result);
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }, [endpoint]);

    useEffect(() => {
        if (method === 'GET' || !method) {
            fetchData();
        }
    }, [fetchData, method]);

    return { data, loading, error, refetch: fetchData };
}

export async function apiFetch(endpoint, options = {}) {
    const config = window.InvizoConfig || { apiUrl: '', nonce: '' };
    const response = await fetch(`${config.apiUrl}${endpoint}`, {
        ...options,
        headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': config.nonce,
            ...(options.headers || {})
        }
    });
    if (!response.ok) {
        const errBody = await response.json().catch(() => ({}));
        const msg =
            (typeof errBody.message === 'string' && errBody.message) ||
            (typeof errBody.code === 'string' && errBody.code) ||
            `HTTP error! status: ${response.status}`;
        throw new Error(msg);
    }
    return await response.json();
}
