import { useState, useRef, useEffect } from 'react'
import { Modal, Input, Button, message, Spin, Row, Col, Space, Divider, Checkbox, Tabs, Empty } from 'antd'
import {
  VideoCameraOutlined,
  CheckOutlined,
  DownloadOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { SlateTransforms } from '@wangeditor/editor'
import { saveAs } from 'file-saver'
import { uploadFileByUrl } from '@/utils/oss'
import useDigitalHuman from '@/hooks/useDigitalHuman'
import './AIDigitalHumanModal.less'

const { TextArea } = Input

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

  // 核心选择状态
  const [selectedFigure, setSelectedFigure] = useState(null)
  const [selectedVoice, setSelectedVoice] = useState(null)
  // 已移除字幕、透明背景和背景图片 URL 相关配置

  const [textValue, setTextValue] = useState('')
  const [playingVoiceId, setPlayingVoiceId] = useState(null)

  const { figures, femaleVoices, maleVoices, loadingFigures, isGenerating, generatedVideo, generateVideo } =
    useDigitalHuman()

  // 初始化默认选择
  useEffect(() => {
    if (!selectedFigure && figures.length > 0) {
      setSelectedFigure(figures[0])
    }
    if (!selectedVoice && femaleVoices.length > 0) {
      setSelectedVoice(femaleVoices[0])
    }
  }, [figures, femaleVoices, selectedFigure, selectedVoice])

  const handleVoicePlay = (voice) => {
    if (playingVoiceId === voice.id) {
      audioRef.current.pause()
      setPlayingVoiceId(null)
    } else {
      audioRef.current.src = voice.previewUrl
      audioRef.current.play()
      setPlayingVoiceId(voice.id)
      audioRef.current.onended = () => setPlayingVoiceId(null)
    }
  }

  const handleGenerate = async () => {
    if (!selectedFigure) return message.warning('请选择数字人形象')
    if (!textValue.trim()) return message.warning('请输入播报文本')
    if (!selectedVoice) return message.warning('请选择音色')

    try {
      await generateVideo({
        figureId: selectedFigure.id,
        figureName: selectedFigure.name,
        driveType: 'TEXT',
        text: textValue.trim(),
        voiceId: selectedVoice?.id,
        width: 720,
        height: 1280,
      })
    } catch (error) {}
  }

  const handleInsert = async () => {
    if (!generatedVideo) return
    try {
      message.loading({ content: '处理中...', key: 'inserting' })
      const ossUrl = await uploadFileByUrl(generatedVideo.url)
      if (editor) {
        editor.restoreSelection()
        const nodes = [
          { type: 'video', src: ossUrl, children: [{ text: '' }] },
          {
            type: 'paragraph',
            textAlign: 'center',
            fontSize: '14px',
            children: [{ text: `${generatedVideo.figureName} - AI播报` }],
          },
        ]
        SlateTransforms.insertNodes(editor, nodes)
        message.success({ content: '已插入文章', key: 'inserting' })
        setIsModalOpen(false)
      }
    } catch (error) {
      message.error({ content: '插入失败', key: 'inserting' })
    }
  }

  return (
    <Modal
      title="数字人 AI 视频生成"
      open={isModalOpen}
      onCancel={() => setIsModalOpen(false)}
      footer={null}
      width={1000}
      centered
      destroyOnClose>
      <div className="ai-digital-human">
        <Row gutter={[24, 16]}>
          <Col span={24}>
            {/* 形象选择 */}
            <div className="section-box">
              <div className="section-title">1. 选择数字人形象</div>
              {loadingFigures && figures.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  <Spin tip="同步云端形象中..." />
                </div>
              ) : figures.length > 0 ? (
                <div className="figure-list">
                  {figures.map((fig) => (
                    <div
                      key={fig.id}
                      className={`figure-item ${selectedFigure?.id === fig.id ? 'active' : ''}`}
                      onClick={() => setSelectedFigure(fig)}>
                      <div className="avatar-wrapper">
                        {fig.avatar ? (
                          <img
                            src={fig.avatar}
                            className="figure-avatar"
                            onError={(e) => {
                              e.target.style.display = 'none'
                              e.target.nextSibling.style.display = 'flex'
                            }}
                          />
                        ) : null}
                        <div className="avatar-fallback" style={{ display: fig.avatar ? 'none' : 'flex' }}>
                          <UserOutlined />
                        </div>
                      </div>
                      <div className="figure-name">{fig.name}</div>
                    </div>
                  ))}
                </div>
              ) : (
                <Empty description="暂无可用形象" />
              )}
            </div>

            {/* 驱动配置 */}
            <div className="section-box">
              <div className="section-title">2. 配置播报内容与音色</div>
              <div className="drive-content">
                <TextArea
                  placeholder="请输入要播报的文本内容..."
                  rows={4}
                  value={textValue}
                  onChange={(e) => setTextValue(e.target.value)}
                  style={{ marginBottom: 12 }}
                />
                <div className="voice-selection">
                  <div className="sub-title">精选配音:</div>
                  <Tabs
                    size="small"
                    items={[
                      {
                        key: 'female',
                        label: '女声',
                        children: (
                          <div className="voice-grid">
                            {femaleVoices.map((v) => (
                              <div
                                key={v.id}
                                className={`voice-item ${selectedVoice?.id === v.id ? 'active' : ''}`}
                                onClick={() => setSelectedVoice(v)}>
                                <div className="v-info">
                                  <span className="v-name">{v.name}</span>
                                  <span className="v-style">{v.style}</span>
                                </div>
                                <Button
                                  type="text"
                                  shape="circle"
                                  icon={playingVoiceId === v.id ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                                  onClick={(e) => {
                                    e.stopPropagation()
                                    handleVoicePlay(v)
                                  }}
                                />
                              </div>
                            ))}
                          </div>
                        ),
                      },
                      {
                        key: 'male',
                        label: '男声',
                        children: (
                          <div className="voice-grid">
                            {maleVoices.map((v) => (
                              <div
                                key={v.id}
                                className={`voice-item ${selectedVoice?.id === v.id ? 'active' : ''}`}
                                onClick={() => setSelectedVoice(v)}>
                                <div className="v-info">
                                  <span className="v-name">{v.name}</span>
                                  <span className="v-style">{v.style}</span>
                                </div>
                                <Button
                                  type="text"
                                  shape="circle"
                                  icon={playingVoiceId === v.id ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                                  onClick={(e) => {
                                    e.stopPropagation()
                                    handleVoicePlay(v)
                                  }}
                                />
                              </div>
                            ))}
                          </div>
                        ),
                      },
                    ]}
                  />
                </div>
              </div>

              {/* 已彻底移除背景图片 URL 相关输入 */}
            </div>
          </Col>

          <Col span={24}>
            <div className="preview-panel">
              <div className="section-title">生成状态</div>
              <div className="results-container">
                {isGenerating ? (
                  <div className="generating-box">
                    <Spin size="large" />
                    <div className="gen-text">视频正在录制中...</div>
                    <div className="gen-hint">预计 1 分钟左右完成</div>
                  </div>
                ) : generatedVideo ? (
                  <div className="final-video-box">
                    <video src={generatedVideo.url} controls autoPlay />
                    <div className="video-actions">
                      <Button
                        block
                        size="large"
                        icon={<DownloadOutlined />}
                        onClick={() => saveAs(generatedVideo.url, 'ai_video.mp4')}>
                        下载视频
                      </Button>
                      <Button block type="primary" size="large" icon={<CheckOutlined />} onClick={handleInsert}>
                        插入编辑器
                      </Button>
                    </div>
                  </div>
                ) : (
                  <div className="empty-preview">
                    <VideoCameraOutlined style={{ fontSize: 64, opacity: 0.1 }} />
                    <p>等待配置完成后点击开始</p>
                  </div>
                )}
              </div>
              <Divider style={{ margin: '12px 0' }} />
              <Button
                type="primary"
                size="large"
                block
                icon={<VideoCameraOutlined />}
                onClick={handleGenerate}
                loading={isGenerating}
                className="submit-btn">
                开始生成 AI 视频
              </Button>
            </div>
          </Col>
        </Row>
      </div>
    </Modal>
  )
}
