/**
 * 剧集内容预览和编辑组件
 *
 * 提供：
 * - 内容预览（Markdown 渲染）
 * - 在线编辑
 * - 审核功能（通过/拒绝）
 * - 导出功能
 * - 版本历史
 */
import { useState, useEffect } from 'react'
import {
  Modal,
  Card,
  Button,
  Space,
  Alert,
  Input,
  Tag,
  Divider,
  Row,
  Col,
  Statistic,
  Progress,
  Dropdown,
  message,
  Tabs,
  List,
  Switch
} from 'antd'
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  DownloadOutlined,
  SaveOutlined,
  EyeOutlined,
  EditOutlined,
  HistoryOutlined,
  FileTextOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined
} from '@ant-design/icons'
import TextArea from 'antd/es/input/TextArea'

import { episodeContentService, EpisodeContent, ContentStatus, ExportFormat } from '@/services/episodeContentService'
import { MarkdownRenderer } from '@/components/MarkdownRenderer'

const { TabPane } = Tabs
const { Text } = Input

interface ContentEditorProps {
  visible: boolean
  projectId: string
  episodeNumber?: number
  content?: EpisodeContent
  onClose: () => void
  onSave?: () => void
}

export const ContentEditor: React.FC<ContentEditorProps> = ({
  visible,
  projectId,
  episodeNumber,
  content: initialContent,
  onClose,
  onSave
}) => {
  // 内容状态
  const [content, setContent] = useState<EpisodeContent | null>(initialContent || null)
  const [editing, setEditing] = useState(false)
  const [editValue, setEditValue] = useState('')
  const [saving, setSaving] = useState(false)

  // 预览模式
  const [isFullscreen, setIsFullscreen] = useState(false)

  // 加载内容
  useEffect(() => {
    if (visible && episodeNumber && !initialContent) {
      loadContent()
    } else if (initialContent) {
      setContent(initialContent)
      setEditValue(initialContent.content)
    }
  }, [visible, episodeNumber, initialContent])

  const loadContent = async () => {
    if (!episodeNumber) return

    try {
      const data = await episodeContentService.getContent(projectId, episodeNumber)
      setContent(data)
      setEditValue(data.content)
    } catch (error) {
      message.error(`加载内容失败: ${(error as Error).message}`)
    }
  }

  // 保存编辑
  const handleSave = async () => {
    if (!content) return

    setSaving(true)
    try {
      await episodeContentService.updateContent(content.id, {
        content: editValue
      })

      message.success('保存成功')
      setEditing(false)

      // 重新加载内容
      await loadContent()

      if (onSave) {
        onSave()
      }
    } catch (error) {
      message.error(`保存失败: ${(error as Error).message}`)
    } finally {
      setSaving(false)
    }
  }

  // 审核内容
  const handleReview = async (approved: boolean, comment?: string) => {
    if (!content) return

    try {
      await episodeContentService.reviewContent(content.id, {
        approved,
        comment
      })

      message.success(approved ? '已通过审核' : '已拒绝')

      // 重新加载内容
      await loadContent()

      if (onSave) {
        onSave()
      }
    } catch (error) {
      message.error(`审核失败: ${(error as Error).message}`)
    }
  }

  // 导出内容
  const handleExport = async (format: ExportFormat) => {
    try {
      const result = await episodeContentService.exportContents(projectId, {
        format,
        episode_numbers: content?.episode_number ? [content.episode_number] : undefined
      })

      if (result.content) {
        // 创建下载链接
        const blob = new Blob([result.content], { type: 'text/plain;charset=utf-8' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = result.filename || `episode_${content?.episode_number}.${format}`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        URL.revokeObjectURL(url)

        message.success('导出成功')
      } else {
        message.info(result.message || '导出功能待完善')
      }
    } catch (error) {
      message.error(`导出失败: ${(error as Error).message}`)
    }
  }

  // 导出菜单
  const exportMenu = {
    items: [
      { key: 'markdown', label: '导出为 Markdown (.md)' },
      { key: 'txt', label: '导出为文本 (.txt)' },
      { key: 'pdf', label: '导出为 PDF (.pdf)' },
      { key: 'docx', label: '导出为 Word (.docx)' }
    ],
    onClick: ({ key }: { key: string }) => {
      handleExport(key as ExportFormat)
    }
  }

  // 状态标签颜色
  const getStatusColor = (status: ContentStatus) => {
    const colors = {
      draft: 'default',
      generating: 'processing',
      pending_review: 'warning',
      approved: 'success',
      rejected: 'error'
    }
    return colors[status] || 'default'
  }

  // 状态标签文字
  const getStatusText = (status: ContentStatus) => {
    const texts = {
      draft: '草稿',
      generating: '生成中',
      pending_review: '待审核',
      approved: '已通过',
      rejected: '已拒绝'
    }
    return texts[status] || status
  }

  if (!content) {
    return (
      <Modal
        title="加载中..."
        open={visible}
        onCancel={onClose}
        footer={null}
      >
        <Card loading />
      </Modal>
    )
  }

  return (
    <Modal
      title={
        <Space>
          <FileTextOutlined />
          <span>第 {content.episode_number} 集 - {content.title || '无标题'}</span>
          <Tag color={getStatusColor(content.status)}>{getStatusText(content.status)}</Tag>
        </Space>
      }
      open={visible}
      onCancel={onClose}
      width={1000}
      footer={
        <Space style={{ width: '100%', justifyContent: 'space-between' }}>
          <Space>
            {content.status === 'pending_review' && (
              <>
                <Button
                  type="primary"
                  icon={<CheckCircleOutlined />}
                  onClick={() => handleReview(true)}
                >
                  通过
                </Button>
                <Button
                  danger
                  icon={<CloseCircleOutlined />}
                  onClick={() => handleReview(false)}
                >
                  拒绝
                </Button>
              </>
            )}
          </Space>

          <Space>
            <Dropdown menu={exportMenu}>
              <Button icon={<DownloadOutlined />}>
                导出
              </Button>
            </Dropdown>
            <Button onClick={onClose}>关闭</Button>
          </Space>
        </Space>
      }
    >
      <Space direction="vertical" style={{ width: '100%' }} size="middle">
        {/* 统计信息 */}
        <Row gutter={16}>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="集数"
                value={content.episode_number}
                prefix="#"
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="质量分数"
                value={content.quality_score || 0}
                suffix="/ 100"
                precision={1}
                valueStyle={{ color: content.quality_score && content.quality_score >= 80 ? '#3f8600' : '#cf1322' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="版本"
                value={content.version}
                prefix="v"
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="状态"
                value={getStatusText(content.status)}
                valueStyle={{ fontSize: 16, color: getStatusColor(content.status) === 'success' ? '#3f8600' : getStatusColor(content.status) === 'error' ? '#cf1322' : undefined }}
              />
            </Card>
          </Col>
        </Row>

        {/* 审核问题 */}
        {content.review_issues && content.review_issues.length > 0 && (
          <Alert
            message={`发现 ${content.review_issues.length} 个审核问题`}
            description={
              <List
                size="small"
                dataSource={content.review_issues}
                renderItem={(issue: any) => (
                  <List.Item>
                    <Tag color={issue.severity === 'high' ? 'error' : 'warning'}>
                      {issue.dimension}
                    </Tag>
                    <Text>{issue.description}</Text>
                  </List.Item>
                )}
              />
            }
            type="warning"
            showIcon
          />
        )}

        {/* 内容预览/编辑 */}
        <Card
          title="内容"
          extra={
            <Space>
              {!editing && (
                <Button
                  icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                  onClick={() => setIsFullscreen(!isFullscreen)}
                >
                  {isFullscreen ? '退出全屏' : '全屏'}
                </Button>
              )}
              {editing ? (
                <>
                  <Button
                    type="primary"
                    icon={<SaveOutlined />}
                    loading={saving}
                    onClick={handleSave}
                  >
                    保存
                  </Button>
                  <Button onClick={() => {
                    setEditing(false)
                    setEditValue(content.content)
                  }}>
                    取消
                  </Button>
                </>
              ) : (
                <Button
                  icon={<EditOutlined />}
                  onClick={() => setEditing(true)}
                >
                  编辑
                </Button>
              )}
            </Space>
          }
        >
          {editing ? (
            <TextArea
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              rows={20}
              style={{ fontFamily: 'monospace', fontSize: '13px' }}
            />
          ) : (
            <div style={{
              maxHeight: isFullscreen ? 'calc(100vh - 200px)' : '65vh',
              overflowY: 'auto',
              borderRadius: '4px'
            }}>
              <MarkdownRenderer content={content.content} />
            </div>
          )}
        </Card>

        {/* 元数据 */}
        <Card size="small" title="元数据">
          <Row gutter={16}>
            <Col span={8}>
              <Text type="secondary">创建时间:</Text>
              <br />
              <Text>{new Date(content.created_at).toLocaleString('zh-CN')}</Text>
            </Col>
            <Col span={8}>
              <Text type="secondary">更新时间:</Text>
              <br />
              <Text>{new Date(content.updated_at).toLocaleString('zh-CN')}</Text>
            </Col>
            <Col span={8}>
              <Text type="secondary">创建者:</Text>
              <br />
              <Text>{content.created_by}</Text>
            </Col>
          </Row>
        </Card>
      </Space>
    </Modal>
  )
}
