import {useNavigation} from 'expo-router'
import {usePreventRemove} from 'expo-router/react-navigation'

import {confirmDestructive} from '@/lib/dialogs'

// guard dirty edits behind a discard confirm; covers the cancel button
// and the sheet's swipe-down alike
export const useDiscardGuard = (dirty: boolean) => {
  const navigation = useNavigation()
  usePreventRemove(dirty, ({data}) => {
    void confirmDestructive({
      title: 'Discard changes?',
      message: 'Your edits will be lost.',
      actionLabel: 'Discard',
    }).then((ok) => {
      if (ok) navigation.dispatch(data.action)
    })
  })
}
