'use client'

import { useState, useCallback, useEffect } from 'react'
import { useGenSupContentV2 } from './useIm'
import { useAtomValue, useSetAtom } from 'jotai'
import {
  msgListAtom,
  selectedConversationIdAtom,
  ExtendedMessage,
  isCoinInsufficientAtom,
} from '@/atoms/im'
import { useNimChat } from '@/context/NimChat/useNimChat'
import { ApiError } from '@/types/api'
import { COIN_INSUFFICIENT_ERROR_CODE } from './useWallet'

export interface ReplySuggestion {
  id: string
  text: string
  isSkeleton?: boolean // 标识是否为骨架屏
}

interface UseAiReplySuggestionsProps {
  aiId?: number
}

export const useAiReplySuggestions = ({ aiId }: UseAiReplySuggestionsProps = {}) => {
  // 简化状态管理 - 按页存储数据
  const [pageData, setPageData] = useState<Map<number, ReplySuggestion[]>>(new Map())
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages] = useState(3) // 固定3页
  const [isVisible, setIsVisible] = useState(false)
  const [lastAiMessageId, setLastAiMessageId] = useState<string>('') // 记录最后一条AI消息的ID
  const [batchNo, setBatchNo] = useState<string>('') // 当前批次号
  const [excContentList, setExcContentList] = useState<string[]>([]) // 已排除的内容列表
  const [loadingPages, setLoadingPages] = useState<Set<number>>(new Set()) // 正在加载的页面
  const setIsCoinInsufficient = useSetAtom(isCoinInsufficientAtom)

  const { mutateAsync: genSupContentV2 } = useGenSupContentV2()
  const { nim } = useNimChat()
  const msgList = useAtomValue(msgListAtom)
  const selectedConversationId = useAtomValue(selectedConversationIdAtom)

  // 获取当前会话的消息列表
  const currentMessages = selectedConversationId ? msgList.get(selectedConversationId) || [] : []

  // 获取最后一条非loading消息
  const getLastMessage = useCallback((): ExtendedMessage | null => {
    const normalMessages = currentMessages.filter((msg) => !msg.isLoadingMessage)
    return normalMessages.length > 0 ? normalMessages[normalMessages.length - 1] : null
  }, [currentMessages])

  // 判断消息是否来自AI（非用户发送）
  const isMessageFromAI = useCallback(
    (message: ExtendedMessage): boolean => {
      if (!nim || !selectedConversationId) return false
      const targetId = nim.V2NIMConversationIdUtil.parseConversationTargetId(selectedConversationId)
      return targetId === message.senderId
    },
    [nim, selectedConversationId]
  )

  // 获取所有数据（第1、2、3页） - 渐进式加载，让用户尽早看到数据
  const fetchAllData = useCallback(async () => {
    if (!aiId) return

    // 防止重复调用
    if (loadingPages.size > 0) {
      console.log('🚫 已有页面正在加载中，跳过重复请求')
      return
    }

    // 标记所有页面为加载中
    setLoadingPages(new Set([1, 2, 3]))

    // 清空旧数据
    setPageData(new Map())
    setExcContentList([])
    setBatchNo('')

    try {
      console.log('🤖 开始渐进式获取建议数据（3次请求）')
      let currentBatchNo = ''
      let currentExcList: string[] = []

      // 获取第1页 - 立即展示
      console.log('🤖 [1/3] 获取第1页数据')
      const firstResponse = await genSupContentV2({
        aiId,
        excContentList: [],
      })

      if (firstResponse && firstResponse.contentList && Array.isArray(firstResponse.contentList)) {
        const firstSuggestions = firstResponse.contentList.map((text, index) => ({
          id: `${firstResponse.batchNo}-0-${index}`,
          text,
        }))

        // 立即展示第1页数据
        setPageData(new Map([[1, firstSuggestions]]))
        setLoadingPages(new Set([2, 3])) // 第1页已加载完成

        currentBatchNo = firstResponse.batchNo
        currentExcList = [...firstResponse.contentList]
        setBatchNo(currentBatchNo)
        setExcContentList(currentExcList)

        console.log('✅ 第1页数据加载完成并立即展示')
      } else {
        throw new Error('第1页数据获取失败')
      }

      // 获取第2页 - 追加展示
      console.log('🤖 [2/3] 获取第2页数据')
      const secondResponse = await genSupContentV2({
        aiId,
        batchNo: currentBatchNo,
        excContentList: currentExcList,
      })

      if (
        secondResponse &&
        secondResponse.contentList &&
        Array.isArray(secondResponse.contentList)
      ) {
        const secondSuggestions = secondResponse.contentList.map((text, index) => ({
          id: `${currentBatchNo}-1-${index}`,
          text,
        }))

        // 追加第2页数据
        setPageData((prev) => new Map(prev).set(2, secondSuggestions))
        setLoadingPages(new Set([3])) // 第2页已加载完成

        currentExcList = [...currentExcList, ...secondResponse.contentList]
        setExcContentList(currentExcList)

        console.log('✅ 第2页数据加载完成并追加展示')
      } else {
        console.warn('⚠️ 第2页数据获取失败，继续获取第3页')
      }

      // 获取第3页 - 追加展示
      console.log('🤖 [3/3] 获取第3页数据')
      const thirdResponse = await genSupContentV2({
        aiId,
        batchNo: currentBatchNo,
        excContentList: currentExcList,
      })

      if (thirdResponse && thirdResponse.contentList && Array.isArray(thirdResponse.contentList)) {
        const thirdSuggestions = thirdResponse.contentList.map((text, index) => ({
          id: `${currentBatchNo}-2-${index}`,
          text,
        }))

        // 追加第3页数据
        setPageData((prev) => new Map(prev).set(3, thirdSuggestions))
        console.log('✅ 第3页数据加载完成并追加展示')
      } else {
        console.warn('⚠️ 第3页数据获取失败')
      }

      // 记录最后一条AI消息的ID
      const lastMessage = getLastMessage()
      if (lastMessage && isMessageFromAI(lastMessage)) {
        setLastAiMessageId(lastMessage.messageServerId)
      }

      console.log('🎉 所有建议数据加载完成')
    } catch (error) {
      if (error instanceof ApiError && error.errorCode === COIN_INSUFFICIENT_ERROR_CODE) {
        setIsCoinInsufficient(true)
        setIsVisible(false)
      } else {
        console.error('❌ 获取建议数据失败:', error)
      }
      // 清空数据
      setPageData(new Map())
    } finally {
      // 清除所有加载状态
      setLoadingPages(new Set())
    }
  }, [
    aiId,
    genSupContentV2,
    loadingPages.size,
    getLastMessage,
    isMessageFromAI,
    setIsCoinInsufficient,
  ])

  // 切换页面
  const handlePageChange = useCallback(
    (page: number) => {
      if (page >= 1 && page <= totalPages && page !== currentPage) {
        console.log('📄 切换到第', page, '页')
        setCurrentPage(page)
      }
    },
    [currentPage, totalPages]
  )

  // 检查是否需要获取新的建议
  const shouldFetchNewSuggestions = useCallback((): boolean => {
    const lastMessage = getLastMessage()
    if (!lastMessage) return false

    const isFromAI = isMessageFromAI(lastMessage)
    const isNewAIMessage = isFromAI && lastMessage.messageServerId !== lastAiMessageId

    return isFromAI && isNewAIMessage
  }, [getLastMessage, isMessageFromAI, lastAiMessageId])

  // 显示建议面板
  const showSuggestions = useCallback(() => {
    setIsVisible(true)

    // 检查是否需要获取新的建议
    if (shouldFetchNewSuggestions()) {
      console.log('🔄 检测到新的AI消息，重置到第1页并获取新建议')
      setCurrentPage(1) // 重置到第1页
      fetchAllData() // 重新获取所有数据
    } else if (pageData.size === 0) {
      console.log('📝 没有建议数据，重置到第1页并获取建议')
      setCurrentPage(1) // 重置到第1页
      fetchAllData()
    } else {
      console.log('♻️ 使用已有的建议数据，保持当前页:', currentPage)
      // 如果已有数据且没有新消息，保持用户当前的页面位置
    }
  }, [shouldFetchNewSuggestions, pageData.size, currentPage, fetchAllData])

  // 隐藏建议面板
  const hideSuggestions = useCallback(() => {
    setIsVisible(false)
  }, [])

  // 监听消息变化，当收到新AI消息且面板已打开时自动刷新
  useEffect(() => {
    if (!isVisible) return

    const lastMessage = getLastMessage()
    if (lastMessage && isMessageFromAI(lastMessage)) {
      if (lastMessage.messageServerId !== lastAiMessageId) {
        console.log('🔄 面板已打开，检测到新AI消息，自动刷新建议')
        // 不重置页面，保持用户当前浏览位置
        fetchAllData()
      }
    }
  }, [getLastMessage, isMessageFromAI, isVisible, lastAiMessageId, fetchAllData])

  // 获取当前页的建议数据
  const currentPageSuggestions = pageData.get(currentPage)
  const isCurrentPageLoading = loadingPages.has(currentPage)

  // 如果页面正在加载或没有数据，显示骨架屏
  const suggestions =
    isCurrentPageLoading || !currentPageSuggestions
      ? Array.from({ length: 3 }, (_, index) => ({
          id: `skeleton-${currentPage}-${index}`,
          text: '',
          isSkeleton: true,
        }))
      : currentPageSuggestions

  return {
    suggestions,
    currentPage,
    totalPages,
    isLoading: loadingPages.size > 0, // 只要有页面在加载就返回true
    isVisible,
    showSuggestions,
    hideSuggestions,
    handlePageChange,
  }
}
