import { useEffect, useState } from 'react'
import { Modal, Input, Button, Flex, Spin } from 'antd'
import { useAIEdit } from '@/hooks/useBaiduAI'
const { TextArea } = Input

const actionMap = {
  rewrite: { name: '改写', prompt: '帮我改写以下文字内容：' },
  expand: { name: '扩写', prompt: '帮我在以下文字内容基础上进行扩写：' },
  abbreviate: { name: '润色', prompt: '帮我润色以下文字内容：' },
  summary: { name: '总结', prompt: '帮我总结以下文字内容：' },
  punctuation: { name: '标点校对', prompt: '帮我校对以下文字内容中的标点符号' },
  contentInspect: { name: '内容检查', prompt: '帮我检查以下文字内容中的敏感词和错别字' }
}

export default function AIModal({ editor, docAction }) {
  const [isModalOpen, setIsModalOpen] = useState(true)

  const [content, setContent] = useState('')
  const { text, fetch, isLoading } = useAIEdit()
  const actionText = actionMap[docAction]?.name
  const [selectionText, setSelectionText] = useState('')
  useEffect(() => {
    const selection = editor.getSelectionText()
    if (selection) {
      setSelectionText(selection)
      setContent(selection)
      fetch({ messages: [{ role: 'user', content: actionMap[docAction].prompt + selection }] })
    }
  }, [docAction, editor, fetch])

  useEffect(() => {
    setContent(text)
  }, [text])

  const handleFetch = () => {
    fetch({ messages: [{ role: 'user', content: actionMap[docAction].prompt + selectionText }] })
  }

  const handlePrimary = () => {
    editor.restoreSelection()
    editor.insertText(content)
    setIsModalOpen(false)
  }

  return (
    <Modal
      title={`以下是AI${actionText}结果：`}
      open={isModalOpen}
      footer={null}
      classNames={{
        header: 'editor-header-customer',
        body: 'editor-body-customer',
        wrapper: 'editor-wrapper-customer'
      }}
      onOk={handlePrimary}
      onCancel={() => setIsModalOpen(false)}>
      <Spin spinning={isLoading}>
        <TextArea autoSize={{ minRows: 4 }} value={content} onChange={e => setContent(e.target.value)} />
      </Spin>
      <br />
      <Flex gap="small" justify="center">
        <Button type="primary" onClick={handlePrimary}>
          替换内容
        </Button>
        <Button type="primary" onClick={handleFetch}>
          重新{actionText}
        </Button>
        <Button type="primary" onClick={() => setIsModalOpen(false)}>
          取消
        </Button>
      </Flex>
    </Modal>
  )
}
