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

// AI搜索
export function useSearch() {
  const [messages, setMessages] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const query = async (userQuery) => {
    try {
      setIsLoading(true)
      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.log(error)
          }
        },
      })
    } catch (error) {
      console.log(error)
    } finally {
      setIsLoading(false)
    }
  }
  return { messages, setMessages, isLoading, query }
}

function parseInput(inputStr) {
  const result = []
  const regex = /^(#+)\s*(.+?)\s*(?=\n|【描述】|$)/g
  const descriptionRegex = /【描述】(.*)/

  const sections = []

  const lines = inputStr.split('\n')

  let level = 0
  let currentTitle = ''
  let currentChapter = ''

  for (let line of lines) {
    const headerMatch = line.match(regex)
    const descriptionMatch = line.match(descriptionRegex)

    if (headerMatch) {
      const header = headerMatch[0]
      const newLevel = header.match(/^#+/)[0].length
      const title = header.replace(/^#+\s*/, '').trim()

      // Handle level change
      if (newLevel > level) {
        // Increase section number for sub-levels
        if (level === 0) {
          sections.push(1)
        } else {
          sections.push(sections[sections.length - 1] + 1)
        }
      } else if (newLevel === level) {
        sections[sections.length - 1] = sections[sections.length - 1] + 1
      } else {
        sections.splice(newLevel, sections.length - newLevel)
      }

      // Generate chapter number
      currentChapter = sections.join('.')

      // Set level and title
      level = newLevel
      currentTitle = title
    }

    if (descriptionMatch) {
      const desc = descriptionMatch[1].trim()
      result.push({ title: currentTitle, level, desc, chapter: `第${currentChapter}章` })
    }
  }

  return result
}

// 生成论文大纲
export function usePaperOutline() {
  const [messages, setMessages] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const query = async (userQuery) => {
    try {
      setIsLoading(true)
      setMessages((prevMessages) => [...prevMessages, { content: userQuery, role: 'user' }])
      const currentMessage = { 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 = parseInput(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.log(error)
          }
        },
      })
    } catch (error) {
      console.log(error)
    } finally {
      setIsLoading(false)
    }
  }
  return { messages, setMessages, isLoading, query }
}

// 大纲生成论文
export function useOutlineToPaper() {
  const { queryWithPolling } = useDownload()
  const [isLoading, setIsLoading] = useState(false)
  const [paper, setPaper] = useState('')
  const query = async (data) => {
    try {
      setIsLoading(true)
      const { raw } = await outlineToPaper(data)
      setPaper(raw)
      const downloadLink = await queryWithPolling({
        docID: '280fe43ee63a580216fc700abb68a98271feac83' || raw.docID,
      })
      setPaper({ ...raw, downloadLink })
      return { ...raw, downloadLink }
    } catch (error) {
      console.log(error)
    } finally {
      setIsLoading(false)
    }
  }
  return { paper, setPaper, isLoading, query }
}

// 文档下载
export function useDownload() {
  const [downloadLink, setDownloadLink] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const timerRef = useRef(null)

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

  const query = async (data) => {
    try {
      setIsLoading(true)
      const { raw } = await download(data)
      if (raw) {
        setDownloadLink(raw.download_link)
        return raw.download_link
      }
    } catch (error) {
      console.error(error)
    } finally {
      setIsLoading(false)
    }
  }

  const queryWithPolling = async (data, interval = 3000) => {
    const poll = async (resolve, reject) => {
      try {
        const link = await query(data)
        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 { downloadLink, isLoading, query, queryWithPolling, clearTimer }
}
