'use client'

import React, { useLayoutEffect, useRef } from 'react'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { useRouter } from 'next/navigation'

interface AbandonCreationDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onCancel: () => void
  onRegenerate: () => void
  actionType?: 'exit' | 'regenerate'
}

const AbandonCreationDialog = ({
  open,
  onOpenChange,
  onCancel,
  onRegenerate,
  actionType = 'regenerate',
}: AbandonCreationDialogProps) => {
  const router = useRouter()
  // 保存对话框打开时的 actionType，确保关闭动画期间按钮文案不变
  const actionTypeRef = useRef(actionType)
  const prevOpenRef = useRef(open)

  useLayoutEffect(() => {
    // 当对话框打开时，持续更新 ref 为当前的 actionType
    // 这样可以确保即使 actionType 在对话框打开后才更新，也能被捕获
    if (open) {
      actionTypeRef.current = actionType
    }
    prevOpenRef.current = open
  }, [open, actionType])

  const handleConfirm = () => {
    onRegenerate()
  }

  // 对话框打开时使用当前的 actionType（确保显示最新值），关闭动画期间使用 ref 保持文案不变
  const displayActionType = open ? actionType : actionTypeRef.current

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Discard Generation</AlertDialogTitle>
        </AlertDialogHeader>
        <AlertDialogDescription>
          If you choose to exit or regenerate, the current images will be lost and one generation
          attempt will be used.
        </AlertDialogDescription>
        <AlertDialogFooter>
          <AlertDialogCancel onClick={onCancel}>cancel</AlertDialogCancel>
          <AlertDialogAction onClick={handleConfirm}>
            {displayActionType === 'exit' ? 'Discard' : 'Regenerate'}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export default AbandonCreationDialog
