import { useEffect, useRef, useState } from 'react';
const DEFAULT_AUTOSAVE = {
    enabled: true,
    delay: 500,
};
/**
 * autosave functionality for extensions with edit block
 */
export const useAutoSave = ({ autoSave, initialValue, onClose, onSave, }) => {
    const { enabled: autoSaveEnabled, delay: autoSaveDelay } = autoSave ?? DEFAULT_AUTOSAVE;
    const isAutoSaveEnabled = Boolean(autoSaveEnabled);
    const [value, setValue] = useState(initialValue || '');
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const autoSaveTimeoutRef = useRef();
    const handleClearTimeout = () => {
        if (autoSaveTimeoutRef.current) {
            clearTimeout(autoSaveTimeoutRef.current);
        }
    };
    const handleChange = (newValue) => {
        setValue(newValue);
        const hasChanges = newValue !== initialValue;
        setHasUnsavedChanges(hasChanges);
        if (isAutoSaveEnabled && hasChanges) {
            handleClearTimeout();
            const delay = autoSaveDelay ?? DEFAULT_AUTOSAVE.delay;
            autoSaveTimeoutRef.current = setTimeout(() => {
                onSave(newValue);
                setHasUnsavedChanges(false);
            }, delay);
        }
    };
    const handleManualSave = () => {
        handleClearTimeout();
        onSave(value);
        onClose();
    };
    // сleanup timeout on unmount
    useEffect(() => {
        return () => {
            handleClearTimeout();
        };
    }, []);
    const isSaveDisabled = isAutoSaveEnabled && !hasUnsavedChanges;
    return {
        value,
        hasUnsavedChanges,
        handleChange,
        handleManualSave,
        handleClearTimeout,
        isAutoSaveEnabled,
        isSaveDisabled,
    };
};
//# sourceMappingURL=useAutoSave.js.map
