'use client'

import { createContext, useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import { conversationListAtom, imSyncedAtom, selectedConversationIdAtom } from '@/atoms/im'
import { useAtom, useAtomValue, useSetAtom } from 'jotai'
import { useNimChat, useNimConversation } from '@/context/NimChat/useNimChat'
import { useGetIMUserInfo } from '@/hooks/useIm'
import { AiUserImBaseInfoOutput, HeartbeatLevel } from '@/services/im'
import {
  isChatBackgroundDrawerOpenAtom,
  isChatButtleDrawerOpenAtom,
  isChatModelDrawerOpenAtom,
  isChatProfileDrawerOpenAtom,
  isChatProfileEditDrawerOpenAtom,
  isCrushLevelDrawerOpenAtom,
  isCrushLevelRetrieveDrawerOpenAtom,
  isSendGiftsDrawerOpenAtom,
  playVoiceAtom,
  createDrawerOpenState,
} from '@/atoms/chat'
import Empty from '@/components/ui/empty'
import { useAutoChatTimer } from '@/hooks/useAutoChatTimer'

export * from './useChatConfig'

const ChatConfigContext = createContext<{
  aiId: number
  aiInfo: AiUserImBaseInfoOutput | undefined
  currentHeartbeatLevel: HeartbeatLevel | undefined
  handleUserMessage: () => void
}>({
  aiId: 0,
  aiInfo: {} as AiUserImBaseInfoOutput,
  currentHeartbeatLevel: undefined,
  handleUserMessage: () => {},
})

const initialState = {
  openedDrawer: [],
}

export const ChatConfigProvider = ({ children }: { children: React.ReactNode }) => {
  const { aiId } = useParams()
  const { nim } = useNimChat()
  const { insertConversationActive } = useNimConversation()
  const [selectedConversationId, setSelectedConversationId] = useAtom(selectedConversationIdAtom)
  const resetIsGiftsDrawerOpen = useSetAtom(isSendGiftsDrawerOpenAtom)
  const resetIsCrushLevelDrawerOpen = useSetAtom(isCrushLevelDrawerOpenAtom)
  const resetIsCrushLevelRetrieveDrawerOpen = useSetAtom(isCrushLevelRetrieveDrawerOpenAtom)
  const resetIsChatProfileDrawerOpen = useSetAtom(isChatProfileDrawerOpenAtom)
  const resetIsChatProfileEditDrawerOpen = useSetAtom(isChatProfileEditDrawerOpenAtom)
  const resetIsChatBackgroundDrawerOpen = useSetAtom(isChatBackgroundDrawerOpenAtom)
  const resetIsChatModelDrawerOpen = useSetAtom(isChatModelDrawerOpenAtom)
  const resetIsChatButtleDrawerOpen = useSetAtom(isChatButtleDrawerOpenAtom)
  const resetIsAutoPlayVoice = useSetAtom(playVoiceAtom)

  const imSynced = useAtomValue(imSyncedAtom)

  // 自动聊天定时器状态
  const [hasUserSentMessage, setHasUserSentMessage] = useState(false)

  const { data: aiInfo, error } = useGetIMUserInfo({ aiId: Number(aiId) })
  const { aiUserHeartbeatRelation } = aiInfo || {}
  const { heartbeatLevel } = aiUserHeartbeatRelation || {}
  const currentHeartbeatLevel = heartbeatLevel

  // 使用自动聊天定时器
  const { handleUserMessage } = useAutoChatTimer({
    aiId: Number(aiId),
    isActive: !!aiId && !!imSynced,
    hasUserSentMessage,
    onUserMessage: () => setHasUserSentMessage(true),
  })

  // 当aiId变化时，重置用户发送消息状态
  useEffect(() => {
    setHasUserSentMessage(false)
  }, [aiId])

  useEffect(() => {
    if (!aiInfo) return
    resetIsAutoPlayVoice({
      isAutoPlayVoice: !!aiInfo?.isAutoPlayVoice,
      voiceType: aiInfo?.voiceType || '',
      dialogueSpeechRate: aiInfo?.dialogueSpeechRate || 0,
      dialoguePitch: aiInfo?.dialoguePitch || 0,
    })
  }, [aiInfo])

  // 初始化会话
  useEffect(() => {
    if (!aiId || !imSynced) return
    const initConversation = async () => {
      try {
        await insertConversationActive({
          receiverId: `${aiId}@r@t`,
        })
      } catch (error) {
        console.error('初始化会话失败:', error)
      }
    }

    initConversation()

    return () => {
      setSelectedConversationId(null)
      resetIsGiftsDrawerOpen(createDrawerOpenState(false))
      resetIsCrushLevelDrawerOpen(createDrawerOpenState(false))
      resetIsCrushLevelRetrieveDrawerOpen(createDrawerOpenState(false))
      resetIsChatProfileDrawerOpen(createDrawerOpenState(false))
      resetIsChatProfileEditDrawerOpen(createDrawerOpenState(false))
      resetIsChatBackgroundDrawerOpen(createDrawerOpenState(false))
      resetIsChatModelDrawerOpen(createDrawerOpenState(false))
      resetIsChatButtleDrawerOpen(createDrawerOpenState(false))
      resetIsAutoPlayVoice({
        isAutoPlayVoice: false,
        voiceType: '',
        dialogueSpeechRate: 0,
        dialoguePitch: 0,
      })
    }
  }, [aiId, insertConversationActive, imSynced])

  useEffect(() => {
    if (!aiId) return
    if (localStorage.getItem('image-2-background-set')) {
      resetIsChatBackgroundDrawerOpen(createDrawerOpenState(true))
      localStorage.removeItem('image-2-background-set')
    }
  }, [aiId])

  // 清空会话未读数
  useEffect(() => {
    if (!selectedConversationId) return
    nim?.V2NIMConversationService.clearUnreadCountByIds([selectedConversationId])
  }, [selectedConversationId])

  if (error) {
    return (
      <div className="flex h-full w-full items-center justify-center">
        <Empty title="This character has been deleted and is no longer available for access or interaction." />
      </div>
    )
  }

  return (
    <ChatConfigContext.Provider
      value={{
        aiId: Number(aiId),
        aiInfo,
        currentHeartbeatLevel,
        handleUserMessage,
      }}
    >
      {children}
    </ChatConfigContext.Provider>
  )
}

export default ChatConfigContext
