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

const actionMap = {
  rewrite: '改写',
  expand: '扩写',
  abbreviate: '缩写',
  summary: '总结',
};

export default function AIWrite({ editor, docAction, ...rest }) {
  const [content, setContent] = useState('');
  const { text, fetch, isLoading } = useAIEdit();
  const actionText = actionMap[docAction];
  const [selectionText, setSelectionText] = useState('');
  useEffect(() => {
    if (rest.open) {
      const selection = editor.getSelectionText();
      if (selection) {
        setSelectionText(selection);
        setContent(selection);
        fetch({ content: selection, doc_action: docAction, full_text: false });
      }
    }
  }, [rest.open]);

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

  const handleFetch = () => {
    fetch({ content: selectionText, doc_action: docAction, full_text: false });
  };

  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>
  );
}
