'use client'

import { useState, useCallback } from 'react'
import { useRouter } from 'next/navigation'

interface UseImageGenerationGuardProps {
  isGenerating: boolean
  batchNo: string | null
  allImagesCompleted?: boolean
  onRegenerate?: () => void
}

export const useImageGenerationGuard = ({
  isGenerating,
  batchNo,
  allImagesCompleted = true,
  onRegenerate,
}: UseImageGenerationGuardProps) => {
  const router = useRouter()
  const [showAbandonDialog, setShowAbandonDialog] = useState(false)
  const [actionType, setActionType] = useState<'exit' | 'regenerate'>('regenerate')
  const [pendingNavigation, setPendingNavigation] = useState<(() => void) | null>(null)

  // 检查是否正在生成图片
  const isImageGenerationInProgress = isGenerating || !!batchNo

  // 处理返回按钮点击
  const handleBackClick = useCallback(() => {
    if (isImageGenerationInProgress) {
      setActionType('exit')
      setShowAbandonDialog(true)
      setPendingNavigation(() => () => router.back())
    } else {
      router.back()
    }
  }, [isImageGenerationInProgress, router])

  // 处理生成按钮点击时的确认
  const handleGenerateClick = useCallback(
    (originalGenerate: () => void) => {
      if (isImageGenerationInProgress) {
        setActionType('regenerate')
        setShowAbandonDialog(true)
        setPendingNavigation(() => originalGenerate)
      } else {
        originalGenerate()
      }
    },
    [isImageGenerationInProgress]
  )

  // 处理弹窗取消
  const handleDialogCancel = useCallback(() => {
    setShowAbandonDialog(false)
    setPendingNavigation(null)
    // 重置 actionType 为默认值
    setActionType('regenerate')
  }, [])

  // 处理重新生成或退出确认
  const handleRegenerate = useCallback(() => {
    setShowAbandonDialog(false)

    // 根据 actionType 执行不同的逻辑
    if (actionType === 'exit') {
      // 退出操作：只执行导航
      if (pendingNavigation) {
        pendingNavigation()
      }
    } else if (actionType === 'regenerate') {
      // 重新生成操作：执行重新生成回调
      if (onRegenerate) {
        onRegenerate()
      }
      // 如果有导航回调（比如生成按钮的回调），也执行它
      if (pendingNavigation) {
        pendingNavigation()
      }
    }

    setPendingNavigation(null)
    setActionType('regenerate')
  }, [actionType, pendingNavigation, onRegenerate])

  return {
    showAbandonDialog,
    actionType,
    handleBackClick,
    handleGenerateClick,
    handleDialogCancel,
    handleRegenerate,
    isImageGenerationInProgress,
  }
}
