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: '帮我总结以下文字内容：' }
}

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

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

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

  const handlePrimary = () => {
    editor.restoreSelection()
    editor.insertText(text)
    rest.onCancel()
  }

  return (
    <Modal
      title={`以下是AI${actionText}结果：`}
      {...rest}
      footer={null}
      classNames={{
        header: 'editor-header-customer',
        body: 'editor-body-customer',
        wrapper: 'editor-wrapper-customer'
      }}>
      <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={rest.onCancel}>
          取消
        </Button>
      </Flex>
    </Modal>
  )
}
