import { useRef, useState } from 'react';
import type { HTMLEditor } from '../lib';

export type SaveType = 'manual' | 'auto' | null;

export const useEditState = () => {
  const [isSaving, setIsSaving] = useState(false);
  const [saveType, setSaveType] = useState<SaveType>(null);
  const [canUndo, setCanUndo] = useState(false);
  const [canRedo, setCanRedo] = useState(false);

  const redo = useRef(() => { });
  const undo = useRef(() => { });

  const handleHistoryChangeEvent = (instance: HTMLEditor) => {
    if (!instance) return null
    const canRedo = instance.EditorRegistry.canRedo()
    const canUndo = instance.EditorRegistry.canUndo()
    setCanRedo(canRedo)
    setCanUndo(canUndo)
    redo.current = () => {
      instance.EditorRegistry.redo()
    }
    undo.current = () => {
      instance.EditorRegistry.undo()
    }
  }

  return {
    isSaving,
    setIsSaving,
    saveType,
    setSaveType,
    handleHistoryChangeEvent,
    canRedo,
    setCanRedo,
    canUndo,
    setCanUndo,
    redo,
    undo,
  }
}