import { useCallback, useState } from 'react'
import { useNavigate } from 'react-router-dom'

interface UseSafeNavigationOptions {
  onBeforeNavigate?: () => Promise<void>
  hasUnsavedChanges?: boolean
  isSaving?: boolean
}

interface UseSafeNavigationReturn {
  safeNavigate: (to: string | number) => Promise<void>
  isNavigating: boolean
}

export function useSafeNavigation({
  onBeforeNavigate,
  hasUnsavedChanges = false,
  isSaving = false,
}: UseSafeNavigationOptions): UseSafeNavigationReturn {
  const navigate = useNavigate()
  const [isNavigating, setIsNavigating] = useState(false)

  const safeNavigate = useCallback(
    async (to: string | number) => {
      if (isNavigating || isSaving) return

      try {
        setIsNavigating(true)

        // Если есть несохраненные изменения, сохраняем их перед переходом
        if (hasUnsavedChanges && onBeforeNavigate) {
          await onBeforeNavigate()
        }

        // Выполняем навигацию
        if (typeof to === 'string') {
          navigate(to)
        } else {
          navigate(to)
        }
      } catch (error) {
        console.error('Ошибка при навигации:', error)
        // В случае ошибки не переходим
      } finally {
        setIsNavigating(false)
      }
    },
    [navigate, onBeforeNavigate, hasUnsavedChanges, isSaving, isNavigating]
  )

  return {
    safeNavigate,
    isNavigating,
  }
}
