import { useEffect, useRef } from 'react'; import { router } from '@inertiajs/react'; import { saveRawMaterialDraft, clearRawMaterialDraft, type RawMaterialDraftData, } from '@/lib/raw-material-draft'; type DraftType = 'create' | 'edit'; export function useRawMaterialDraftSave( type: DraftType, data: RawMaterialDraftData, userId?: number, rawMaterialId?: number, delay = 500, ) { const timeoutRef = useRef | null>(null); const dataRef = useRef(data); dataRef.current = data; const submittedRef = useRef(false); useEffect(() => { return router.on('before', () => { submittedRef.current = true; }); }, []); useEffect(() => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } timeoutRef.current = setTimeout(() => { if (!submittedRef.current) { saveRawMaterialDraft(type, dataRef.current, userId, rawMaterialId); } timeoutRef.current = null; }, delay); return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, [data, type, userId, rawMaterialId, delay]); useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } if (submittedRef.current) { clearRawMaterialDraft(type, userId, rawMaterialId); } else { saveRawMaterialDraft(type, dataRef.current, userId, rawMaterialId); } }; }, [type, userId, rawMaterialId]); }