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

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,
    generateOutline,
    generatePaper,
    chapterTagRender,
    getChaptersMarkdown,
    addChapter,
    updateChapter,
    removeChapter,
  } = usePaper()
  useEffect(() => {
    if (prePromptRef.current) {
      const width = prePromptRef.current.offsetWidth + 10
      setTextIndent(width)
    }
  }, [isModalOpen])
  const [isEditMessage, setIsEditMessage] = useState(false)
  useEffect(() => {
    if (messageScrollRef.current && !isEditMessage) {
      const scrollContainer = messageScrollRef.current
      scrollContainer.scrollTop = scrollContainer.scrollHeight
    }
  }, [messages, isEditMessage])

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

  const [, copyToClipboard] = useCopyToClipboard()

  // 复制内容
  const handleCopy = (msg) => {
    copyToClipboard(getChaptersMarkdown(msg.chapters))
  }

  // 生成论文
  const handleGeneratePaper = async (msg) => {
    setMessages((prevMessages) => {
      return [...prevMessages, { content: '正在生成长文...', role: 'ai', tips: '预计10分钟', queryID: msg.queryID }]
    })
    const paper = await generatePaper({
      userQuery: msg.userQuery,
      queryID: msg.queryID,
      outline: getChaptersMarkdown(msg.chapters),
    })
    setMessages((prevMessages) => {
      prevMessages.pop()
      return [...prevMessages, { content: '已为您生成初稿，请点击下载', role: 'ai', queryID: msg.queryID, paper }]
    })
  }
  let chapterMenuItems = [
    { key: 'add', label: '新增', icon: <PlusCircleOutlined style={{ fontSize: 14 }} /> },
    { key: 'remove', label: '删除', icon: <DeleteOutlined style={{ fontSize: 14 }} /> },
  ]

  const handleMenuClick = async (e, chapter, message) => {
    setIsEditMessage(true)
    if (e.key === 'add') addChapter(chapter, message)
    if (e.key === 'remove') removeChapter(chapter, message)
  }
  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) => {
                  return (
                    <div className="chapter-item" key={item.id}>
                      <div className="chapter-left">
                        <div className="chapter-left-title">{chapterTagRender(item, msg.chapters)}</div>
                        <div className="line-dot">
                          <div className="dot"></div>
                          <div className="line"></div>
                        </div>
                      </div>
                      <div className="chapter-right">
                        <div className="chapter-right-content">
                          <Input
                            className="chapter-title"
                            placeholder="请输入标题"
                            defaultValue={item.title}
                            variant="borderless"
                            onBlur={(e) => updateChapter(item, msg, { ...item, title: e.target.value })}
                          />
                          {item.level !== 1 && (
                            <Input
                              className="chapter-desc"
                              placeholder="请输入你的备注，如这个章节必须包含正反观点等。"
                              defaultValue={item.desc}
                              variant="borderless"
                              onBlur={(e) => updateChapter(item, msg, { ...item, desc: e.target.value })}
                            />
                          )}
                          {/* <h3>{item.title}</h3> */}
                          {/* <p>{item.desc}</p> */}
                        </div>
                        <div className="chapter-right-tools">
                          {item.level !== 1 && (
                            <Dropdown
                              menu={{ items: chapterMenuItems, onClick: (e) => handleMenuClick(e, item, msg) }}
                              getPopupContainer={(triggerNode) => triggerNode.parentNode}>
                              <Button type="text" icon={<CircleEllipsis color="#222" size={20} />}></Button>
                            </Dropdown>
                          )}
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
              <div className="message-tools">
                <Button
                  type="text"
                  size="small"
                  icon={<UndoOutlined />}
                  disabled={isLoading}
                  onClick={() => generateOutline(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)}>
                  复制内容
                </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) => {
            return <MessageRender msg={msg} key={msg.id}></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>
  )
}
