import { useState } from 'react'
import { SendOutlined, DownloadOutlined, CheckOutlined, PictureOutlined } from '@ant-design/icons'
import { saveAs } from 'file-saver'
import { ConfigProvider, Modal, Input, Button, Image, message, Row, Col, Card, Spin, Radio } from 'antd'
import { SlateTransforms, SlateEditor, SlateElement } from '@wangeditor/editor'
const { TextArea } = Input
import './AISearchModal.less'
import './AIImageModal.less'
import { useImage } from '@ezijing/ai-react'
import { uploadFileByUrl } from '@/utils/oss'

export default function AIImageModal(props) {
  const { editor } = props
  const [isModalOpen, setIsModalOpen] = useState(true)
  const [prompt, setPrompt] = useState('')
  const [size, setSize] = useState('2048x2048')
  const [style, setStyle] = useState('default')
  const [generatedImages, setGeneratedImages] = useState([])

  // 使用 @ezijing/ai-react 的 useImage 钩子
  const { isLoading, error, generateImage } = useImage({
    provider: 'volcano',
    onSuccess: (response) => {
      console.log('图片生成成功:', response)
      if (response.urls && response.urls.length > 0) {
        // 每次生成一张图片，添加到列表最前面，最多保留12张
        setGeneratedImages((prev) => {
          const newImages = [...response.urls, ...prev]
          return newImages.slice(0, 12)
        })
        message.success('图片生成成功！')
      }
    },
    onError: (error) => {
      console.error('图片生成失败:', error)
      message.error(`图片生成失败: ${error}`)
    },
  })

  // 图片比例选项
  const sizeOptions = [
    { label: '1:1', value: '2048x2048' },
    { label: '3:4', value: '1728x2304' },
    { label: '4:3', value: '2304x1728' },
    { label: '16:9', value: '2848x1600' },
    { label: '9:16', value: '1600x2848' },
    { label: '3:2', value: '2496x1664' },
    { label: '2:3', value: '1664x2496' },
    { label: '21:9', value: '3136x1344' },
  ]

  // 风格选项
  const styleOptions = [
    { label: '默认', value: 'default' },
    { label: '写实', value: 'realistic' },
    { label: '动漫', value: 'anime' },
    { label: '油画', value: 'oil_painting' },
    { label: '水彩', value: 'watercolor' },
    { label: '素描', value: 'sketch' },
  ]

  const handleEnterSearch = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      if (!isLoading) {
        handleGenerateImage()
      }
    }
  }

  const handleGenerateImage = async () => {
    if (!prompt.trim()) {
      message.error('请输入图片描述！')
      return
    }

    // 将风格信息添加到提示词中
    let promptWithStyle = prompt
    if (style !== 'default') {
      const styleMap = {
        realistic: '写实风格',
        anime: '动漫风格',
        oil_painting: '油画风格',
        watercolor: '水彩风格',
        sketch: '素描风格',
      }
      const styleText = styleMap[style] || style
      promptWithStyle = `${styleText}，${prompt}`
    }

    try {
      await generateImage({
        prompt: promptWithStyle,
        size,
        // 接口只支持生成一张图片，没有n参数
      })
    } catch (error) {
      console.error('生成图片失败:', error)
      message.error('生成图片失败，请稍后重试')
    }
  }

  // 移除空段落
  const removeEmptyParagraph = (editor) => {
    const nodeEntries = SlateEditor.nodes(editor, {
      match: (node) => {
        if (SlateElement.isElement(node)) {
          if (node.type === 'paragraph') {
            return true
          }
        }
        return false
      },
      universal: true,
    })
    for (let nodeEntry of nodeEntries) {
      const [node] = nodeEntry
      if (node.children && node.children.length === 1 && node.children[0].text === '') {
        SlateTransforms.removeNodes(editor)
      }
    }
  }

  // 上传图片到OSS并插入编辑器 (标准图片)
  const handleInsertImage = async (imageUrl) => {
    try {
      message.loading('正在上传图片...', 0)
      const ossUrl = await uploadFileByUrl(imageUrl)
      message.destroy()

      if (editor) {
        editor.restoreSelection()
        removeEmptyParagraph(editor)

        const oImg = {
          type: 'paragraph',
          textAlign: 'center',
          children: [
            {
              type: 'image',
              src: ossUrl,
              alt: prompt || 'AI生成的图片',
              href: '',
              children: [{ text: '' }],
            },
          ],
        }
        const oP = {
          type: 'paragraph',
          textAlign: 'center',
          fontSize: '14px',
          children: [{ text: prompt || 'AI生成的图片' }],
        }

        SlateTransforms.insertNodes(editor, [oImg, oP])
        message.success('图片已插入编辑器！')
        setIsModalOpen(false)
      } else {
        message.error('编辑器未找到')
      }
    } catch (error) {
      message.destroy()
      console.error('上传图片失败:', error)
      message.error('上传图片失败，请稍后重试')
    }
  }

  // 下载图片
  const handleDownloadImage = (imageUrl) => {
    saveAs(imageUrl, `ai_image_${Date.now()}.jpg`)
  }

  const GeneratedImageCard = ({ imageUrl, index }) => (
    <Card
      hoverable
      className="generated-image-card"
      cover={
        <div className="image-container">
          <Image
            src={imageUrl}
            alt={`AI生成图片 ${index + 1}`}
            style={{ width: '100%', height: '200px', objectFit: 'cover' }}
            preview={{ src: imageUrl }}
          />
        </div>
      }
      size="small">
      <div className="image-actions">
        <Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownloadImage(imageUrl)}>
          下载
        </Button>
        <Button type="primary" size="small" icon={<CheckOutlined />} onClick={() => handleInsertImage(imageUrl)}>
          插入
        </Button>
      </div>
    </Card>
  )

  return (
    <ConfigProvider theme={{ components: { Modal: { headerBg: '#f7f8fa', contentBg: '#f7f8fa' } } }}>
      <Modal title="AI图片生成" open={isModalOpen} footer={null} onCancel={() => setIsModalOpen(false)} width={1200}>
        <div className="ai-image-generator">
          {/* 输入区域 */}
          <div className="input-container">
            <div className="input-box">
              <div className="edit-area">
                <TextArea
                  className="content"
                  autoSize={{ minRows: 3, maxRows: 6 }}
                  value={prompt}
                  placeholder="描述你想要生成的图片，例如：一只可爱的小猫在花园里玩耍，阳光明媚，风格温馨"
                  onChange={(e) => setPrompt(e.target.value)}
                  onKeyDown={handleEnterSearch}
                />
              </div>
              <div className="input-tools">
                <Button type="primary" icon={<SendOutlined />} onClick={handleGenerateImage} loading={isLoading}>
                  生成图片
                </Button>
              </div>
            </div>

            {/* 选项区域 */}
            <div className="options-container" style={{ marginTop: 16 }}>
              <Row gutter={[16, 16]}>
                <Col span={12}>
                  <div className="option-group">
                    <div className="option-label">图片比例:</div>
                    <Radio.Group
                      options={sizeOptions}
                      onChange={(e) => setSize(e.target.value)}
                      value={size}
                      optionType="button"
                      buttonStyle="solid"
                    />
                  </div>
                </Col>
                <Col span={12}>
                  <div className="option-group">
                    <div className="option-label">图片风格:</div>
                    <Radio.Group
                      options={styleOptions}
                      onChange={(e) => setStyle(e.target.value)}
                      value={style}
                      optionType="button"
                      buttonStyle="solid"
                    />
                  </div>
                </Col>
              </Row>
            </div>
          </div>

          {/* 错误提示 */}
          {error && (
            <div className="error-message" style={{ marginTop: 16, color: '#ff4d4f' }}>
              错误: {error}
            </div>
          )}

          {/* 生成结果区域 */}
          <div className="results-container" style={{ marginTop: 24 }}>
            <div className="results-title">生成结果</div>

            {isLoading ? (
              <div className="loading-container">
                <Spin tip="AI正在生成图片，请稍候..." size="large">
                  <div style={{ height: '200px' }} />
                </Spin>
              </div>
            ) : generatedImages.length > 0 ? (
              <Row gutter={[16, 16]}>
                {generatedImages.map((imageUrl, index) => (
                  <Col span={6} key={`${imageUrl}-${index}`}>
                    <GeneratedImageCard imageUrl={imageUrl} index={index} />
                  </Col>
                ))}
              </Row>
            ) : (
              <div className="empty-results">
                <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
                  <PictureOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                  <div>输入描述并点击生成按钮，AI将为你创作图片</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </Modal>
    </ConfigProvider>
  )
}
