import {useEffect, useRef} from 'react';
import type {RefObject} from 'react';
import {Post} from '@modules/post/interfaces';

import {useNewPost} from './useNewPost';
import {buildDraft} from '../utils';

type Props = {
  isEditing: boolean;
  skipSaveRef: RefObject<boolean>;
  saveDraft: (draft: Partial<Post>) => void;
};

export const useSaveDraftOnUnmount = ({
  isEditing,
  skipSaveRef,
  saveDraft,
}: Props) => {
  const newPostContext = useNewPost();
  const newPostContextRef = useRef(newPostContext);
  newPostContextRef.current = newPostContext;
  const isEditingRef = useRef(isEditing);
  isEditingRef.current = isEditing;

  useEffect(() => {
    const skipRef = skipSaveRef;
    return () => {
      if (isEditingRef.current || skipRef.current) {
        return;
      }
      saveDraft(buildDraft(newPostContextRef.current));
    };
    // Empty deps: unmount-only cleanup; refs hold latest snapshot.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
};
