import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { IconButton } from '@/components/ui/button'
import { CreateFormData, useCreateFormStorage } from '@/hooks/create'
import { useRouter } from 'next/navigation'
import { useState } from 'react'

const CloseIconButton = () => {
  const router = useRouter()
  const { clearFormData, getFormData } = useCreateFormStorage()
  const [isOpen, setIsOpen] = useState(false)

  // 判断是否需要弹窗
  const isNeedAlert = () => {
    const formData = JSON.parse(getFormData() || '{}') as CreateFormData
    const { type, character, dialogue, image } = formData || {}
    // 检查 type 数据是否有值
    const hasTypeData = type && (type.roleCode || type.characterCode || type.tagCode)

    // 检查 character 数据是否有值
    const hasCharacterData =
      character &&
      (character.nickname ||
        character.sex !== undefined ||
        character.birthday ||
        character.aiUserExt?.userProfile)

    // 检查 dialogue 数据是否有值
    const hasDialogueData =
      dialogue &&
      (dialogue.aiUserExt?.userDialogueStyle ||
        dialogue.aiUserExt?.prologue ||
        dialogue.aiUserExt?.voice?.content)

    // 检查 image 数据是否有值
    const hasImageData =
      image && (image.imageUrl || image.avatarUrl || image.intro || image.imageDesc)

    return hasTypeData || hasCharacterData || hasDialogueData || hasImageData
  }

  // 如果当前页面没有值，则跳转到 type 页面
  // useEffect(() => {
  //   console.log('pathname', pathname)
  //   const hasValue = isNeedAlert();
  //   if (!hasValue && pathname !== '/create/type' && pathname.includes('/create/')) {
  //     router.push('/create/type');
  //   }
  // }, [isNeedAlert, pathname])

  const handleClick = () => {
    if (isNeedAlert()) {
      setIsOpen(true)
    } else {
      handleClose()
    }
  }

  const handleClose = () => {
    clearFormData()
    localStorage.removeItem('create-image-generate-batch')
    router.push(localStorage.getItem('before_creator_navigation') || '/')
  }

  return (
    <>
      <IconButton variant="ghost" size="small" onClick={handleClick}>
        <i className="iconfont icon-close" />
      </IconButton>
      <AlertDialog open={isOpen} onOpenChange={setIsOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Unsaved changes</AlertDialogTitle>
            <AlertDialogDescription>
              Your changes haven't been saved. Do you want to exit anyway?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleClose}>Exit</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}

export default CloseIconButton
