import { useState, useEffect, useRef } from 'react'
import {
  SendOutlined,
  UploadOutlined,
  UndoOutlined,
  CopyOutlined,
  FileTextOutlined,
  FileWordOutlined,
  DownloadOutlined,
} from '@ant-design/icons'
import { ConfigProvider, Modal, Input, Button } from 'antd'
const { TextArea } = Input
import './AISearchModal.less'
import { usePaperOutline, useOutlineToPaper } from '@/hooks/useWenku'
import { useCopyToClipboard } from 'react-use'

export default function AIModal() {
  const [isModalOpen, setIsModalOpen] = useState(true)
  const [content, setContent] = useState('商业数据分析')
  const [textIndent, setTextIndent] = useState(0)
  const prePromptRef = useRef(null)
  const messageScrollRef = useRef(null)
  const { messages, setMessages, isLoading, query } = usePaperOutline()
  useEffect(() => {
    if (prePromptRef.current) {
      const width = prePromptRef.current.offsetWidth + 10
      setTextIndent(width)
    }
  }, [isModalOpen])

  useEffect(() => {
    if (messageScrollRef.current) {
      const scrollContainer = messageScrollRef.current
      scrollContainer.scrollTop = scrollContainer.scrollHeight
    }
  }, [messages])

  const prePrompt = '帮我生成一篇课题报告，主题是：'
  const handleEnterSearch = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSearch()
    }
  }
  const handleSearch = () => {
    query(prePrompt + content)
    setContent('')
  }

  const [, copyToClipboard] = useCopyToClipboard()

  // 复制内容
  const handleCopy = (content) => {
    copyToClipboard(content)
  }

  // 生成论文
  const { query: outlineToPaper } = useOutlineToPaper()

  const handleGeneratePaper = async (msg) => {
    setMessages((prevMessages) => {
      return [...prevMessages, { content: '正在生成长文...', role: 'ai', tips: '预计10分钟', queryID: msg.queryID }]
    })
    const paper = await outlineToPaper({ userQuery: msg.userQuery, queryID: msg.queryID, outline: msg.content })
    setMessages((prevMessages) => {
      prevMessages.pop()
      return [...prevMessages, { content: '已为您生成初稿，请点击查看', role: 'ai', queryID: msg.queryID, paper }]
    })
  }

  const MessageRender = ({ msg }) => {
    if (msg.role === 'ai') {
      if (msg.chapters && msg.chapters.length) {
        return (
          <div className={`message-item ${msg.role}`}>
            <div className="message-box">
              <div className="message-content">
                {msg.chapters.map((item, index) => {
                  return (
                    <div className="chapter-item" key={index}>
                      <div className="chapter-left">
                        <div className="chapter-left-title">{item.chapter}</div>
                        <div className="line-dot">
                          <div className="dot"></div>
                          <div className="line"></div>
                        </div>
                      </div>
                      <div className="chapter-right">
                        <div className="chapter-right-content">
                          <h3>{item.title}</h3>
                          <p>{item.desc}</p>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
              <div className="message-tools">
                <Button
                  type="text"
                  size="small"
                  icon={<UndoOutlined />}
                  disabled={isLoading}
                  onClick={() => query(msg.userQuery)}>
                  换个大纲
                </Button>
                <Button
                  type="text"
                  size="small"
                  icon={<FileTextOutlined />}
                  disabled={isLoading}
                  onClick={() => handleGeneratePaper(msg)}>
                  生成长文
                </Button>
                <Button type="text" size="small" icon={<CopyOutlined />} onClick={() => handleCopy(msg.content)}>
                  复制内容
                </Button>
              </div>
            </div>
          </div>
        )
      } else {
        return (
          <div className={`message-item ${msg.role}`}>
            <div className="message-box">
              <div className="message-content">
                {msg.content}
                {msg.paper?.downloadLink && (
                  <div className="message-file">
                    <div className="message-file-content">
                      <a href={msg.paper.downloadLink} target="_blank" rel="noreferrer">
                        <FileWordOutlined />
                        商业数据分析研究
                      </a>
                    </div>
                    <div className="message-file-tools">
                      <a href={msg.paper.downloadLink} target="_blank" rel="noreferrer">
                        <DownloadOutlined />
                      </a>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        )
      }
    } else {
      return (
        <div className={`message-item ${msg.role}`}>
          <div className="message-box">
            <div className="message-content">{msg.content}</div>
          </div>
        </div>
      )
    }
  }

  return (
    <ConfigProvider theme={{ components: { Modal: { headerBg: '#f7f8fa', contentBg: '#f7f8fa' } } }}>
      <Modal
        title="长文写作/课程大纲："
        open={isModalOpen}
        footer={null}
        onCancel={() => setIsModalOpen(false)}
        width={1000}>
        <div className="message-scroll" ref={messageScrollRef}>
          {messages.map((msg, index) => {
            return <MessageRender msg={msg} key={index}></MessageRender>
          })}
        </div>
        <div className="input-container">
          <div className="input-box">
            <div className="edit-area">
              {prePrompt && (
                <span className="pre-prompt" ref={prePromptRef}>
                  {prePrompt}
                </span>
              )}
              <TextArea
                className="content"
                autoSize
                value={content}
                placeholder="今天需要我做些什么？shift+enter换行"
                onChange={(e) => setContent(e.target.value)}
                onKeyDown={handleEnterSearch}
                style={{ textIndent }}
              />
            </div>
            <div className="input-tools">
              <Button type="text" icon={<UploadOutlined />} />
              <Button type="primary" size="large" icon={<SendOutlined />} onClick={handleSearch} loading={isLoading} />
            </div>
          </div>
          <div className="upload-list"></div>
        </div>
      </Modal>
    </ConfigProvider>
  )
}
