import { useState, useCallback } from 'react';
import { showToast } from '../toast';

export type SaveState = 'idle' | 'saving' | 'saved';

export function useSave(
	onSave: () => Promise<void>,
	successMsg: string,
	errorMsg: string,
	successHoldMs = 2200,
): { state: SaveState; execute: () => void } {
	const [state, setState] = useState<SaveState>('idle');

	const execute = useCallback(async () => {
		if (state !== 'idle') return;
		setState('saving');
		try {
			await onSave();
			showToast(successMsg);
			setState('saved');
			window.setTimeout(() => setState('idle'), Math.max(800, successHoldMs));
		} catch {
			showToast(errorMsg, 'error');
			setState('idle');
		}
	}, [state, onSave, successMsg, errorMsg, successHoldMs]);

	return { state, execute };
}
