import { useState, useEffect, useRef } from 'react'
import { aiSearch, paperOutline, outlineToPaper, download } from '@/api/wenku'
import { useAsyncTask } from './useAsyncTask'
import { nanoid } from 'nanoid'

// AI搜索
export function useSearch() {
  const [messages, setMessages] = useState([])

  const { isLoading, execute } = useAsyncTask(async (userQuery) => {
    setMessages((prevMessages) => [...prevMessages, { content: userQuery, role: 'user' }])
    const currentMessage = { content: '', searchReferList: [], role: 'ai', userQuery }

    await aiSearch({
      body: JSON.stringify({ userQuery }),
      onmessage(message) {
        try {
          const data = JSON.parse(message.data)
          const content = data.raw?.content || ''
          const searchReferList = data.raw?.searchReferList || []
          currentMessage.content += content
          if (searchReferList.length) {
            currentMessage.searchReferList.push(...searchReferList)
            setMessages((prevMessages) => {
              const lastMessage = prevMessages[prevMessages.length - 1]
              if (lastMessage?.role === 'ai') {
                return [...prevMessages.slice(0, -1), currentMessage]
              }
              return [...prevMessages, currentMessage]
            })
          }
        } catch (error) {
          console.error('Error parsing message:', error)
        }
      },
    })
  })

  return { messages, setMessages, isLoading, query: execute }
}

/**
 * 论文生成全流程管理
 */
export function usePaper() {
  const [messages, setMessages] = useState([])
  const [paper, setPaper] = useState(null)
  const [downloadLink, setDownloadLink] = useState('')
  const timerRef = useRef(null)

  const clearTimer = () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current)
      timerRef.current = null
    }
  }

  const parseMarkdown = (text) => {
    const lines = text.split('\n')
    const result = []
    let currentSection = null

    lines.forEach((line) => {
      const match = line.match(/^(#+)\s+(.*)/)
      if (match) {
        const level = match[1].length
        const title = match[2]
        currentSection = {
          id: nanoid(),
          title,
          level,
          content: line,
        }
        result.push(currentSection)
      } else if (line.startsWith('【描述】')) {
        if (currentSection) {
          currentSection.desc = line.replace('【描述】', '').trim()
          currentSection.content += '\n' + line
        }
      } else if (currentSection) {
        currentSection.content += '\n' + line
      }
    })

    return result
  }

  const getChaptersMarkdown = (chapters) => {
    return chapters
      .map((chapter) => {
        const level = '#'.repeat(chapter.level)
        return `${level} ${chapter.title}\n${chapter.desc ?? ''}`
      })
      .join('\n')
  }

  const chapterTagRender = (chapter, chapters) => {
    let chapterCount = 0 // 用于记录章节编号
    let sectionCount = 0 // 用于记录当前章节下的小节编号

    for (let i = 0; i < chapters.length; i++) {
      const ch = chapters[i]
      // 一级章节
      if (ch.level === 1) {
        if (ch === chapter) {
          return '标题' // 一级章节显示“标题”
        }
      }
      // 二级章节
      else if (ch.level === 2) {
        chapterCount++ // 一级章节增加
        sectionCount = 0 // 重置二级章节计数
        if (ch === chapter) {
          return `第${chapterCount}章` // 返回“第X章”
        }
      }
      // 三级章节
      else if (ch.level === 3) {
        sectionCount++ // 二级章节增加
        if (ch === chapter) {
          return `${chapterCount}.${sectionCount}` // 返回“小节编号 X.Y”
        }
      }
    }
    return ''
  }

  // 新增章节
  const addChapter = (chapter, message) => {
    const newChapter = {
      title: '',
      level: chapter.level,
      desc: '',
    }
    setMessages((prevMessages) => {
      const messageIndex = prevMessages.findIndex((msg) => msg === message)

      // 找到目标章节在数组中的索引
      const chapterIndex = message.chapters.findIndex((item) => item === chapter)

      // 如果找不到章节，直接添加到末尾
      if (chapterIndex === -1) {
        const updatedMessages = [...prevMessages]
        updatedMessages[messageIndex] = {
          ...prevMessages[messageIndex],
          chapters: [...message.chapters, newChapter],
        }
        return updatedMessages
      }

      // 在当前章节后直接插入新章节
      const updatedChapters = [...message.chapters]
      updatedChapters.splice(chapterIndex + 1, 0, newChapter)

      // 更新消息数组
      const updatedMessages = [...prevMessages]
      updatedMessages[messageIndex] = {
        ...prevMessages[messageIndex],
        chapters: updatedChapters,
      }

      return updatedMessages
    })
  }
  // 更新章节
  const updateChapter = (chapter, message, updatedData) => {
    console.log(updatedData)
    setMessages((prevMessages) => {
      const messageIndex = prevMessages.findIndex((msg) => msg === message)

      // 找到要更新的章节在数组中的索引
      const chapterIndex = message.chapters.findIndex((item) => item === chapter)

      // 如果找不到章节，返回原数组
      if (chapterIndex === -1) {
        return prevMessages
      }

      // 创建更新后的章节数组
      const updatedChapters = [...message.chapters]

      // 更新章节数据，保持原有属性不变
      updatedChapters[chapterIndex] = {
        ...chapter, // 保留原有属性
        ...updatedData, // 使用新的数据覆盖
        level: chapter.level, // 确保level不被意外修改
      }

      // 更新消息数组
      const updatedMessages = [...prevMessages]
      updatedMessages[messageIndex] = {
        ...prevMessages[messageIndex],
        chapters: updatedChapters,
      }

      return updatedMessages
    })
  }
  // 删除章节
  const removeChapter = (chapter, message) => {
    setMessages((prevMessages) => {
      const messageIndex = prevMessages.findIndex((msg) => msg === message)

      // 找到要删除的章节在数组中的索引
      const chapterIndex = message.chapters.findIndex((item) => item === chapter)

      // 如果找不到章节，返回原数组
      if (chapterIndex === -1) {
        return prevMessages
      }

      // 获取当前章节的层级
      const targetLevel = chapter.level

      // 找到下一个同级或更高级章节的索引
      const nextSameLevelIndex = message.chapters.findIndex((item, index) => {
        return index > chapterIndex && item.level <= targetLevel
      })

      // 过滤章节:
      // 1. 保留目标章节之前的所有章节
      // 2. 删除目标章节
      // 3. 删除到下一个同级章节之前的所有子章节
      const filteredChapters = message.chapters.filter((item, index) => {
        if (index < chapterIndex) {
          // 保留目标章节之前的章节
          return true
        } else if (index === chapterIndex) {
          // 删除目标章节
          return false
        } else if (nextSameLevelIndex === -1) {
          // 如果没有下一个同级章节，只保留层级小于等于目标章节的
          return item.level <= targetLevel
        } else {
          // 如果有下一个同级章节，删除其之前的所有子章节
          return index >= nextSameLevelIndex
        }
      })

      // 更新消息数组
      const updatedMessages = [...prevMessages]
      updatedMessages[messageIndex] = {
        ...prevMessages[messageIndex],
        chapters: filteredChapters,
      }

      return updatedMessages
    })
  }

  const { isLoading: isOutlineLoading, execute: generateOutline } = useAsyncTask(async (userQuery) => {
    setMessages((prevMessages) => [...prevMessages, { id: nanoid(), content: userQuery, role: 'user' }])
    const currentMessage = { id: nanoid(), content: '', role: 'ai', userQuery, chapters: [], logID: '', queryID: '' }

    await paperOutline({
      body: JSON.stringify({ userQuery }),
      onmessage(message) {
        try {
          const data = JSON.parse(message.data)
          const content = data.raw?.data || ''
          if (data.logID) currentMessage.logID = data.logID
          if (data.queryID) currentMessage.queryID = data.queryID
          currentMessage.content += content
          currentMessage.chapters = parseMarkdown(currentMessage.content)
          if (content) {
            setMessages((prevMessages) => {
              const lastMessage = prevMessages[prevMessages.length - 1]
              if (lastMessage?.role === 'ai') {
                return [...prevMessages.slice(0, -1), currentMessage]
              }
              return [...prevMessages, currentMessage]
            })
          }
        } catch (error) {
          console.error('Error parsing message:', error)
        }
      },
    })
  })

  const { isLoading: isPaperLoading, execute: generatePaper } = useAsyncTask(async (data) => {
    const { raw } = await outlineToPaper(data)
    setPaper(raw)
    const downloadLink = await downloadWithPolling({
      docID: raw.docID,
    })
    setPaper({ ...raw, downloadLink })
    return { ...raw, downloadLink }
  })

  const { isLoading: isDownloadLoading, execute: downloadPaper } = useAsyncTask(async (docID) => {
    const { raw } = await download({ docID })
    if (raw) {
      setDownloadLink(raw.download_link)
      return raw.download_link
    }
  })

  const downloadWithPolling = async (data, interval = 3000) => {
    const poll = async (resolve, reject) => {
      try {
        const link = await downloadPaper(data.docID)
        if (link) {
          resolve(link)
          return
        }
      } catch (error) {
        reject(error)
        return
      }

      timerRef.current = setTimeout(() => poll(resolve, reject), interval)
    }

    return new Promise(poll)
  }

  useEffect(() => {
    return () => clearTimer()
  }, [])

  return {
    messages,
    setMessages,
    paper,
    downloadLink,
    isLoading: isOutlineLoading || isPaperLoading || isDownloadLoading,
    generateOutline,
    generatePaper,
    downloadPaper,
    chapterTagRender,
    getChaptersMarkdown,
    addChapter,
    updateChapter,
    removeChapter,
  }
}
