import { useEffect, useCallback, useRef } from 'react'
import { usePathname, useRouter } from 'next/navigation'

// 需要保护的路径前缀
const PROTECTED_PATHS = ['/create', '/generate']

// 检查当前路径是否需要保护
const isProtectedPath = (pathname: string): boolean => {
  return PROTECTED_PATHS.some((prefix) => pathname.startsWith(prefix))
}

// 检查是否有未保存的数据
const hasUnsavedData = (): boolean => {
  if (typeof window === 'undefined') return false

  try {
    // 检查创建表单数据
    const createFormData = localStorage.getItem('create_form_data')
    if (createFormData) {
      const data = JSON.parse(createFormData)
      // 检查是否有任何步骤的数据
      if (
        data.type?.roleCode ||
        data.type?.characterCode ||
        data.type?.tagCode ||
        data.character?.nickname ||
        data.dialogue?.aiUserExt?.dialogue ||
        data.image?.imageUrl
      ) {
        return true
      }
    }

    // 检查编辑表单数据
    const editFormData = localStorage.getItem('edit_form_data')
    if (editFormData) {
      const data = JSON.parse(editFormData)
      if (data.imageUrl || data.avatarUrl || data.intro) {
        return true
      }
    }

    return false
  } catch (error) {
    console.error('检查未保存数据时出错:', error)
    return false
  }
}

export function useNavigationGuard() {
  const pathname = usePathname()

  // 显示确认对话框
  const showConfirmDialog = useCallback((message: string): Promise<boolean> => {
    return new Promise((resolve) => {
      const confirmed = window.confirm(message)
      resolve(confirmed)
    })
  }, [])

  // 监听浏览器后退/前进按钮
  useEffect(() => {
    const handleBeforeUnload = (event: BeforeUnloadEvent) => {
      if (isProtectedPath(pathname) && hasUnsavedData()) {
        event.preventDefault()
        event.returnValue = '您有未保存的更改，确定要离开吗？'
        return '您有未保存的更改，确定要离开吗？'
      }
    }

    const handlePopState = async (event: PopStateEvent) => {
      if (isProtectedPath(pathname) && hasUnsavedData()) {
        event.preventDefault()
        const confirmed = await showConfirmDialog(
          '您有未保存的更改，确定要离开吗？离开后数据将丢失。'
        )

        if (!confirmed) {
          // 阻止导航，恢复当前状态
          window.history.pushState(null, '', pathname)
          return
        }
        console.log('用户确认离开，清除表单数据')
        // 用户确认离开，清除表单数据
        localStorage.removeItem('create_form_data')
        localStorage.removeItem('edit_form_data')
      }
    }

    window.addEventListener('beforeunload', handleBeforeUnload)
    window.addEventListener('popstate', handlePopState)

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload)
      window.removeEventListener('popstate', handlePopState)
    }
  }, [pathname, showConfirmDialog])

  return {
    isProtectedPath: isProtectedPath(pathname),
    hasUnsavedData: hasUnsavedData(),
  }
}
