import { useState, useEffect } from 'react'
import { Modal, Upload, Select, Button, message } from 'antd'
import { UploadOutlined, InboxOutlined } from '@ant-design/icons'
import { uploadCover } from '../../services/dashboardService'

const { Dragger } = Upload

/**
 * 更换题图 Modal
 * 
 * 权限：仅 zhipianren / zebian 可用（由父组件控制显示/隐藏）
 * 
 * @param {boolean} open - Modal 是否显示
 * @param {Function} onClose - 关闭回调
 * @param {Function} onUploaded - 上传成功回调，传入新题图对象
 * @param {Array} episodes - 期次列表（用于下拉选择关联期次）
 */
function ChangeCoverModal({ open, onClose, onUploaded, episodes = [] }) {
  const [file, setFile] = useState(null)
  const [previewUrl, setPreviewUrl] = useState(null)
  const [selectedEpisode, setSelectedEpisode] = useState(null)
  const [uploading, setUploading] = useState(false)

  // 每次打开时重置状态
  useEffect(() => {
    if (open) {
      setFile(null)
      setPreviewUrl(null)
      setSelectedEpisode(null)
      setUploading(false)
    }
  }, [open])

  // 选择文件后生成预览
  const handleFileChange = (info) => {
    const rawFile = info.file.originFileObj || info.file
    if (!rawFile) return
    setFile(rawFile)
    const url = URL.createObjectURL(rawFile)
    setPreviewUrl(url)
  }

  const handleUpload = async () => {
    if (!file) {
      message.warning('请先选择图片')
      return
    }
    if (!selectedEpisode) {
      message.warning('请选择关联期次')
      return
    }

    setUploading(true)
    try {
      const ep = episodes.find(e => String(e.episode_number) === String(selectedEpisode))
      const result = await uploadCover(file, Number(selectedEpisode), ep?.program_name || `第${selectedEpisode}期`)
      message.success('题图上传成功')
      onUploaded({
        cover_path: result.cover_path,
        episode_number: Number(selectedEpisode),
        episode_title: ep?.program_name || `第${selectedEpisode}期`,
      })
    } catch (err) {
      const errMsg = err?.response?.data?.detail || '上传失败，请重试'
      message.error(errMsg)
    } finally {
      setUploading(false)
    }
  }

  const episodeOptions = episodes.map(ep => ({
    value: String(ep.episode_number),
    label: `第 ${ep.episode_number} 期 · ${ep.program_name}`,
  }))

  return (
    <Modal
      title="更换题图"
      open={open}
      onCancel={onClose}
      footer={null}
      width={480}
      destroyOnClose
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* 图片上传区域 */}
        <div>
          <p style={{ fontSize: 13, color: '#6b6b6b', marginBottom: 8 }}>上传海报图片（PNG/JPG/WEBP，不超过 5MB）</p>
          <Dragger
            accept=".png,.jpg,.jpeg,.webp"
            maxCount={1}
            beforeUpload={() => false}
            onChange={handleFileChange}
            showUploadList={false}
            style={{ borderRadius: 12 }}
          >
            {previewUrl ? (
              <div style={{ padding: '8px 0' }}>
                <img
                  src={previewUrl}
                  alt="预览"
                  style={{ maxWidth: '100%', maxHeight: 160, borderRadius: 8 }}
                />
                <p style={{ marginTop: 8, color: '#6b8e6b', fontSize: 13 }}>点击或拖拽更换图片</p>
              </div>
            ) : (
              <>
                <p className="ant-upload-drag-icon" style={{ marginBottom: 8 }}>
                  <InboxOutlined style={{ fontSize: 32, color: '#6b8e6b' }} />
                </p>
                <p style={{ color: '#6b6b6b', fontSize: 13 }}>点击或拖拽图片到此处上传</p>
              </>
            )}
          </Dragger>
        </div>

        {/* 关联期次下拉 */}
        <div>
          <p style={{ fontSize: 13, color: '#6b6b6b', marginBottom: 8 }}>关联期次</p>
          <Select
            placeholder="请选择期次"
            style={{ width: '100%' }}
            value={selectedEpisode}
            onChange={setSelectedEpisode}
            options={episodeOptions}
            showSearch
            filterOption={(input, option) =>
              option.label.toLowerCase().includes(input.toLowerCase())
            }
          />
        </div>

        {/* 操作按钮 */}
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <Button onClick={onClose} disabled={uploading}>取消</Button>
          <Button
            type="primary"
            icon={<UploadOutlined />}
            loading={uploading}
            onClick={handleUpload}
            disabled={!file || !selectedEpisode}
          >
            确认上传
          </Button>
        </div>
      </div>
    </Modal>
  )
}

export default ChangeCoverModal