import { useMemo, useEffect, useCallback } from 'react';
import { validateChart, sanitizeChartData, calculateSafeScaleRange, SafeMath } from '../utils/chart-validation.js';

/**
 * Hook for comprehensive chart validation and error handling
 */
function useChartValidation(data, config, options = {}) {
    const { autoSanitize = true, logWarnings = process.env.NODE_ENV === 'development', onValidationError, onValidationWarning, } = options;
    // Memoized validation result (pure computation only)
    const validation = useMemo(() => {
        return validateChart(data, config);
    }, [data, config]);
    // Side effects for validation errors and warnings
    useEffect(() => {
        if (validation.errors.length > 0 && onValidationError) {
            onValidationError(validation.errors);
        }
        if (validation.warnings.length > 0) {
            if (logWarnings) {
                console.warn('Chart validation warnings:', validation.warnings);
            }
            if (onValidationWarning) {
                onValidationWarning(validation.warnings);
            }
        }
    }, [validation, onValidationError, onValidationWarning, logWarnings]);
    // Sanitized data
    const sanitizedData = useMemo(() => {
        if (!autoSanitize || !Array.isArray(data)) {
            return Array.isArray(data) ? data : [];
        }
        return sanitizeChartData(data);
    }, [data, autoSanitize]);
    // Safe scale calculation
    const safeScale = useMemo(() => ({
        calculateRange: (options) => {
            const validData = autoSanitize ? sanitizedData : (Array.isArray(data) ? data : []);
            const validConfig = (config && typeof config === 'object') ? config : {};
            return calculateSafeScaleRange(validData, validConfig, options);
        }
    }), [sanitizedData, data, config, autoSanitize]);
    // Manual revalidation trigger
    const revalidate = useCallback(() => {
        // This will trigger re-computation of the validation memoized value
        // by updating a dependency (though in this case, we rely on the data/config changes)
    }, []);
    return {
        validation,
        sanitizedData,
        isValid: validation.isValid,
        hasWarnings: validation.warnings.length > 0,
        safeScale,
        safeMath: SafeMath,
        revalidate,
    };
}

export { useChartValidation };
