'use client'

import { Button } from '@/components/ui/button'
import { useDoRtcOperation } from '@/hooks/useIm'
import { useChatConfig } from '../../context/chatConfig'
import { RtcOperation } from '@/services/im'
import React, { useState } from 'react'
import { useNimChat, useNimMsgContext } from '@/context/NimChat/useNimChat'
import { CustomMessageType } from '@/types/im'
import { useAtom, useAtomValue, useSetAtom } from 'jotai'
import {
  hasReceivedAiGreetingAtom,
  hasStartAICallAtom,
  isCallAtom,
  selectedConversationIdAtom,
} from '@/atoms/im'
import { useQueryClient } from '@tanstack/react-query'
import { walletKeys } from '@/lib/query-keys'

const ChatEndButton = ({
  roomId,
  taskId,
  onLeave,
  callStartTime,
  abortController,
}: {
  roomId: string
  taskId: string
  onLeave: () => Promise<void>
  callStartTime: number | null
  abortController: AbortController | null
}) => {
  const { aiId, handleUserMessage } = useChatConfig()
  const { mutateAsync: doRtcOperation } = useDoRtcOperation()
  const [loading, setLoading] = useState(false)
  const { nim } = useNimChat()
  const { sendMessageActive } = useNimMsgContext()
  const selectedConversationId = useAtomValue(selectedConversationIdAtom)
  const hasReceivedAiGreeting = useAtomValue(hasReceivedAiGreetingAtom)
  const setIsCall = useSetAtom(isCallAtom)
  const [hasStartAICall, setHasStartAICall] = useAtom(hasStartAICallAtom)
  const queryClient = useQueryClient()

  const handleEndCall = async () => {
    try {
      setLoading(true)
      const duration = Date.now() - (callStartTime || 0)
      // 如果已开始AI通话，则停止AI通话
      try {
        if (hasStartAICall) {
          await doRtcOperation({
            data: {
              roomId: roomId,
              optType: RtcOperation.STOP,
              aiId: aiId,
              taskId: taskId,
              duration,
            },
          })
        } else {
          await doRtcOperation({
            data: {
              roomId: roomId,
              optType: RtcOperation.CANCEL,
              aiId: aiId,
              taskId: taskId,
              duration,
            },
          })
        }
        setHasStartAICall(false)
      } catch (error) {
        setHasStartAICall(false)
      }

      await onLeave()

      if (!hasReceivedAiGreeting) {
        const text = 'Call Canceled'
        const msg = nim.V2NIMMessageCreator.createCustomMessage(
          text,
          JSON.stringify({
            type: CustomMessageType.CALL_CANCEL,
            duration: Date.now() - (callStartTime || 0),
          })
        )
        sendMessageActive({
          msg,
          conversationId: selectedConversationId || '',
          isLoading: false,
        })

        // 通知用户发送了消息，重置自动聊天定时器
        handleUserMessage()
      }
      setIsCall(false)
      await queryClient.invalidateQueries({ queryKey: walletKeys.getWalletBalance() })
    } catch (error) {
      console.log(error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <Button
      size="large"
      className="min-w-[80px]"
      variant="destructive"
      loading={loading}
      onClick={handleEndCall}
    >
      <i className="iconfont icon-hang-up !text-[24px]" />
    </Button>
  )
}

export default ChatEndButton
