import { ref } from 'vue'

export function useFormGuard() {
  const _snapshot = ref('')
  const showDiscardDialog = ref(false)
  let _pendingClose: (() => void) | null = null

  function snapshot(data: unknown) {
    _snapshot.value = JSON.stringify(data)
  }

  function tryClose(data: unknown, closeFn: () => void) {
    if (JSON.stringify(data) !== _snapshot.value) {
      _pendingClose = closeFn
      showDiscardDialog.value = true
    } else {
      closeFn()
    }
  }

  function confirmDiscard() {
    showDiscardDialog.value = false
    _pendingClose?.()
    _pendingClose = null
  }

  function cancelDiscard() {
    showDiscardDialog.value = false
    _pendingClose = null
  }

  return { showDiscardDialog, snapshot, tryClose, confirmDiscard, cancelDiscard }
}
