import { useRef, useState } from 'react'
import { SendOutlined, DownloadOutlined, CheckOutlined, VideoCameraOutlined } from '@ant-design/icons'
import { saveAs } from 'file-saver'
import { ConfigProvider, Modal, Input, Button, message, Row, Col, Card, Spin, Radio, InputNumber } from 'antd'
import { SlateTransforms, SlateEditor, SlateElement } from '@wangeditor/editor'
import { useVideo } from '@ezijing/ai-react'
import { uploadFileByUrl } from '@/utils/oss'
import './AISearchModal.less'
import './AIVideoModal.less'

const { TextArea } = Input

export default function AIVideoModal(props) {
  const { editor } = props
  const [isModalOpen, setIsModalOpen] = useState(true)
  const [prompt, setPrompt] = useState('')
  const [ratio, setRatio] = useState('16:9')
  const [duration, setDuration] = useState(5)
  const [generatedVideos, setGeneratedVideos] = useState([])
  const lastGenerateParamsRef = useRef({ prompt: '', ratio: '16:9', duration: 5 })

  const ratioOptions = [
    { label: '16:9', value: '16:9' },
    { label: '4:3', value: '4:3' },
    { label: '1:1', value: '1:1' },
    { label: '3:4', value: '3:4' },
    { label: '9:16', value: '9:16' },
    { label: '21:9', value: '21:9' },
  ]

  const { isLoading, error, generateVideo } = useVideo({
    provider: 'volcano',
    onSuccess: (response) => {
      console.log('视频生成成功:', response)
      if (response.url) {
        const { prompt: usedPrompt, ratio: usedRatio, duration: usedDuration } = lastGenerateParamsRef.current
        setGeneratedVideos((prev) => {
          const nextVideos = [
            {
              id: response.id || response.url,
              url: response.url,
              prompt: usedPrompt,
              ratio: usedRatio,
              duration: usedDuration,
            },
            ...prev,
          ]
          return nextVideos.slice(0, 8)
        })
        message.success('视频生成成功！')
      }
    },
    onError: (videoError) => {
      console.error('视频生成失败:', videoError)
      message.error(`视频生成失败: ${videoError}`)
    },
  })

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

  const handleGenerateVideo = async () => {
    if (!prompt.trim()) {
      message.error('请输入视频描述！')
      return
    }

    const normalizedDuration = Math.min(12, Math.max(2, Math.round(Number(duration) || 5)))
    const normalizedPrompt = prompt.trim()
    setDuration(normalizedDuration)
    lastGenerateParamsRef.current = {
      prompt: normalizedPrompt,
      ratio,
      duration: normalizedDuration,
    }

    try {
      await generateVideo({
        prompt: normalizedPrompt,
        ratio,
        duration: normalizedDuration,
      })
    } catch (videoError) {
      console.error('生成视频失败:', videoError)
      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)
      }
    }
  }

  // 上传并插入视频 (标准视频)
  const handleInsertVideo = async (videoUrl, videoPrompt) => {
    try {
      message.loading('正在上传视频...', 0)
      const ossUrl = await uploadFileByUrl(videoUrl)
      message.destroy()

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

        const nodes = [
          {
            type: 'video',
            src: ossUrl,
            children: [{ text: '' }],
          },
          {
            type: 'paragraph',
            textAlign: 'center',
            fontSize: '14px',
            children: [{ text: videoPrompt || 'AI生成的视频' }],
          },
        ]
        SlateTransforms.insertNodes(editor, nodes)
        message.success('视频已插入编辑器！')
        setIsModalOpen(false)
      } else {
        message.error('编辑器未找到')
      }
    } catch (uploadError) {
      message.destroy()
      console.error('上传视频失败:', uploadError)
      message.error('上传视频失败，请稍后重试')
    }
  }

  const handleDownloadVideo = (videoUrl) => {
    saveAs(videoUrl, `ai_video_${Date.now()}.mp4`)
  }

  const GeneratedVideoCard = ({ videoItem, index }) => (
    <Card
      hoverable
      className="generated-video-card"
      cover={
        <div className="video-container">
          <video src={videoItem.url} controls preload="metadata" />
        </div>
      }
      size="small">
      <div className="video-meta">{videoItem.prompt || `AI生成视频 ${index + 1}`}</div>
      <div className="video-meta">
        比例: {videoItem.ratio || '16:9'} | 时长: {videoItem.duration || 5}s
      </div>
      <div className="video-actions">
        <Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownloadVideo(videoItem.url)}>
          下载
        </Button>
        <Button
          type="primary"
          size="small"
          icon={<CheckOutlined />}
          onClick={() => handleInsertVideo(videoItem.url, videoItem.prompt)}>
          插入
        </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-video-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={handleEnterGenerate}
                />
              </div>
              <div className="input-tools">
                <Button type="primary" icon={<SendOutlined />} onClick={handleGenerateVideo} loading={isLoading}>
                  生成视频
                </Button>
              </div>
            </div>

            <div className="options-container" style={{ marginTop: 16 }}>
              <Row gutter={[16, 16]}>
                <Col span={16}>
                  <div className="option-group">
                    <div className="option-label">视频比例:</div>
                    <Radio.Group
                      options={ratioOptions}
                      onChange={(e) => setRatio(e.target.value)}
                      value={ratio}
                      optionType="button"
                      buttonStyle="solid"
                    />
                  </div>
                </Col>
                <Col span={8}>
                  <div className="option-group">
                    <div className="option-label">视频时长(2-12秒):</div>
                    <InputNumber
                      min={2}
                      max={12}
                      step={1}
                      precision={0}
                      value={duration}
                      onChange={(value) => setDuration(Number.isFinite(value) ? Math.round(value) : 5)}
                      style={{ width: '100%' }}
                    />
                  </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: '220px' }} />
                </Spin>
              </div>
            ) : generatedVideos.length > 0 ? (
              <Row gutter={[16, 16]}>
                {generatedVideos.map((videoItem, index) => (
                  <Col span={8} key={videoItem.id || `${videoItem.url}-${index}`}>
                    <GeneratedVideoCard videoItem={videoItem} index={index} />
                  </Col>
                ))}
              </Row>
            ) : (
              <div className="empty-results">
                <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
                  <VideoCameraOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                  <div>输入描述并点击生成按钮，AI将为你创作视频</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </Modal>
    </ConfigProvider>
  )
}
