import { useState, useEffect, useRef } from 'react'
import { SendOutlined, UndoOutlined, CopyOutlined, LinkOutlined } from '@ant-design/icons'
import { ConfigProvider, Modal, Input, Button } from 'antd'
const { TextArea } = Input
import './AISearchModal.less'
import { useSearch } 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, isLoading, query } = useSearch()

  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()
      !isLoading && handleSearch()
    }
  }
  const handleSearch = () => {
    query(prePrompt + content)
    setContent('')
  }

  const [, copyToClipboard] = useCopyToClipboard()

  const handleCopy = (content) => {
    copyToClipboard(content)
  }

  const MessageRender = ({ msg }) => {
    if (msg.role === 'ai') {
      const copyMessageContent = msg.searchReferList
        ?.map((refer, index) => `${index + 1}.《${refer.title}》\n${refer.abstract}\n`)
        .join('\n')
      return (
        msg.searchReferList?.length > 0 && (
          <div className={`message-item ${msg.role}`}>
            <div className="message-box">
              <div className="message-content">
                {msg.searchReferList.map((refer, index) => {
                  return (
                    <div key={index} className="result-item">
                      <p>
                        <strong>
                          {index + 1}.《{refer.title}》
                        </strong>
                      </p>
                      <p>
                        {refer.abstract}
                        <a href={refer.orgUrl} target="_blank" rel="noreferrer">
                          <LinkOutlined />
                        </a>
                      </p>
                    </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={<CopyOutlined />} onClick={() => handleCopy(copyMessageContent)}>
                  复制内容
                </Button>
              </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="请输入关键词"
                onChange={(e) => setContent(e.target.value)}
                onKeyDown={handleEnterSearch}
                style={{ textIndent }}
              />
            </div>
            <div className="input-tools">
              <Button type="primary" size="large" icon={<SendOutlined />} onClick={handleSearch} loading={isLoading} />
            </div>
          </div>
        </div>
      </Modal>
    </ConfigProvider>
  )
}
