'use client'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { useNimConversation, useNimMsgContext } from '@/context/NimChat/useNimChat'
import { useAtomValue, useSetAtom } from 'jotai'
import { selectedConversationIdAtom } from '@/atoms/im'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { useQueryClient } from '@tanstack/react-query'
import { imKeys } from '@/lib/query-keys'
import { useChatConfig } from '../../../context/chatConfig'
import { useDeleteConversations } from '@/hooks/useIm'

const DeleteMessageDialog = ({
  open,
  onOpenChange,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
}) => {
  const { aiId } = useChatConfig()
  const { removeConversationById } = useNimConversation()
  const { clearHistoryMessage } = useNimMsgContext()
  const selectedConversationId = useAtomValue(selectedConversationIdAtom)
  const [loading, setLoading] = useState(false)
  const setSelectedConversationId = useSetAtom(selectedConversationIdAtom)
  const router = useRouter()
  const queryClient = useQueryClient()

  const { mutateAsync: deleteConversations } = useDeleteConversations()

  const handleDeleteMessage = async () => {
    if (!selectedConversationId) return
    setLoading(true)
    await removeConversationById(selectedConversationId)
    await clearHistoryMessage(selectedConversationId)
    await deleteConversations({ aiIdList: [aiId] })
    setSelectedConversationId(null)
    router.push('/chat')
    queryClient.invalidateQueries({ queryKey: imKeys.imUserInfo(aiId) })
    setLoading(false)
    onOpenChange(false)
  }

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete</AlertDialogTitle>
        </AlertDialogHeader>
        <AlertDialogDescription>
          Deletion is permanent. Your accumulated Affection points and the character's memories will
          not be affected. Please confirm deletion.
        </AlertDialogDescription>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction variant="destructive" disabled={loading} onClick={handleDeleteMessage}>
            Delete
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export default DeleteMessageDialog
