import { useState, useEffect } from 'react';
import { stepValidator } from '../../features/context/TOD.FormulaireData';

const ErrorHandling = ({ children, verify, value, errorMessage = "This field is required" }) => {
    const [error, setError] = useState(null);
    const [isDirty, setIsDirty] = useState(false);

    useEffect(() => {
        const currentValidator = stepValidator.value;
        
        stepValidator.value = () => {
            const isValid = verify(value);
            setError(isValid ? null : errorMessage);
            setIsDirty(true);
            return isValid && (currentValidator ? currentValidator() : true);
        };

        return () => {
            stepValidator.value = currentValidator;
        };
    }, [verify, value, errorMessage]);

    return (
        <div className="error-handling-wrapper">
            {children}
            {isDirty && error && (
                <div className="error-message">
                    {error}
                </div>
            )}
        </div>
    );
};

export default ErrorHandling; 