/**
 * 执行监控页面 - 实时显示 Agent 执行进度
 */
import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import {
  Card, Steps, Button, Space, Progress, Tag, Spin, Timeline,
  Alert, Modal, Typography, Collapse, Divider, Select, message
} from 'antd'
import {
  PlayCircleOutlined, PauseCircleOutlined, CheckCircleOutlined,
  LoadingOutlined, EyeOutlined, ArrowRightOutlined, HomeOutlined
} from '@ant-design/icons'
import { useProjectStore, Episode } from '@/stores/projectStore'
import { MarkdownRenderer } from '@/components/MarkdownRenderer'

const { Text, Title, Paragraph } = Typography
const { Step } = Steps
const { Option } = Select

export const ExecutionMonitor = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const { currentProject, episodes, executeEpisode, fetchProject } = useProjectStore()

  // 执行状态
  const [executing, setExecuting] = useState(false)
  const [currentEpisode, setCurrentEpisode] = useState(1)
  const [currentPhase, setCurrentPhase] = useState(0)
  const [currentPhaseStatus, setCurrentPhaseStatus] = useState<'idle' | 'running' | 'completed' | 'error'>('idle')
  const [executionLog, setExecutionLog] = useState<string[]>([])
  const [selectedEpisode, setSelectedEpisode] = useState<Episode | null>(null)

  // Agent 执行的 5 个阶段
  const phases = [
    { title: '加载全局上下文', description: '读取世界观、人物、历史记忆' },
    { title: '结构分析', description: '分析场景构成、关键事件' },
    { title: '大纲生成', description: '生成本集大纲' },
    { title: '对话创作', description: '使用 Skill 创作剧本' },
    { title: '一致性审核', description: '检查一致性并更新记忆' }
  ]

  useEffect(() => {
    if (id) {
      fetchProject(id)
    }
  }, [id])

  // 模拟执行过程（实际应该通过 WebSocket 或轮询获取）
  const handleExecute = async (episodeNum: number) => {
    setExecuting(true)
    setCurrentEpisode(episodeNum)
    setCurrentPhase(0)
    setCurrentPhaseStatus('running')
    setExecutionLog([])

    // 模拟各阶段执行
    for (let phase = 0; phase < phases.length; phase++) {
      setCurrentPhase(phase)
      setCurrentPhaseStatus('running')
      setExecutionLog(prev => [...prev, `[阶段 ${phase + 1}] ${phases[phase].title} 开始...`])

      // 模拟耗时
      await new Promise(resolve => setTimeout(resolve, 1000))

      setCurrentPhaseStatus('completed')
      setExecutionLog(prev => [...prev, `[阶段 ${phase + 1}] ${phases[phase].title} 完成 ✓`])
    }

    // 实际调用 API
    try {
      await executeEpisode(id!, episodeNum)
      setExecutionLog(prev => [...prev, `\n✅ EP${episodeNum} 创作完成！`])
      message.success(`EP${episodeNum} 创作完成！`)
    } catch (error) {
      setExecutionLog(prev => [...prev, `\n❌ 创作失败: ${(error as Error).message}`])
      setCurrentPhaseStatus('error')
    } finally {
      setExecuting(false)
    }
  }

  const handleBatchExecute = async () => {
    for (let ep = 1; ep <= 3; ep++) {
      await handleExecute(ep)
    }
  }

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      'idle': 'default',
      'running': 'processing',
      'completed': 'success',
      'error': 'error'
    }
    return colors[status] || 'default'
  }

  if (!currentProject && !executing) {
    return (
      <div style={{ padding: '50px', textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    )
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 头部 */}
      <Card style={{ marginBottom: '16px' }}>
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Space>
              <Title level={3} style={{ margin: 0 }}>{currentProject?.name}</Title>
              <Button icon={<HomeOutlined />} onClick={() => navigate('/projects')}>
                返回项目列表
              </Button>
            </Space>
          </div>
        </Space>
      </Card>

      {/* 执行控制 */}
      <Card title="执行控制" style={{ marginBottom: '16px' }}>
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          <Alert
            message="执行说明"
            description="Agent 将按照固定的 5 阶段工作流自动创作剧集。你可以单集执行或批量执行。"
            type="info"
            showIcon
          />

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <span style={{ marginRight: '16px' }}>当前执行: EP{currentEpisode}</span>
              <Select
                value={currentEpisode}
                onChange={(e) => setCurrentEpisode(e.value)}
                style={{ width: 120 }}
                disabled={executing}
              >
                {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(n => (
                  <Option key={n} value={n}>EP{n}</Option>
                ))}
              </Select>
            </div>
            <Space>
              <Button
                size="large"
                type="primary"
                icon={executing ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                onClick={() => handleExecute(currentEpisode)}
                disabled={executing}
              >
                {executing ? '执行中...' : '执行单集'}
              </Button>
              <Button
                size="large"
                onClick={handleBatchExecute}
                disabled={executing}
              >
                批量执行 (EP1-EP3)
              </Button>
            </Space>
          </div>
        </Space>
      </Card>

      {/* 执行进度 */}
      <Card title="执行进度" style={{ marginBottom: '16px' }}>
        <Steps
          current={currentPhase}
          status={currentPhaseStatus as any}
          style={{ marginBottom: '24px' }}
        >
          {phases.map((phase, idx) => (
            <Step
              key={idx}
              title={phase.title}
              description={phase.description}
              icon={idx === currentPhase && executing ? <LoadingOutlined /> : undefined}
            />
          ))}
        </Steps>

        {/* 执行日志 */}
        <Card size="small" title="执行日志" style={{ background: '#1a1a1a', border: 'none' }}>
          <pre style={{
            color: '#00ff00',
            fontFamily: 'monospace',
            fontSize: '12px',
            maxHeight: '200px',
            overflowY: 'auto',
            margin: 0,
            whiteSpace: 'pre-wrap'
          }}>
            {executionLog.length > 0 ? executionLog.join('\n') : '等待执行...'}
          </pre>
        </Card>
      </Card>

      {/* 已完成剧集 */}
      <Card title="已完成剧集" style={{ marginBottom: '16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '16px' }}>
          <span>完成进度: {episodes.length} / {currentProject?.totalEpisodes || 30}</span>
          <Progress
            percent={Math.round((episodes.length / (currentProject?.totalEpisodes || 30)) * 100)}
            style={{ width: '300px' }}
          />
        </div>

        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '12px' }}>
          {episodes.map(episode => (
            <Card
              key={episode.id}
              size="small"
              title={`EP${episode.number}: ${episode.title || '未命名'}`}
              style={{ width: 'calc(33.333% - 8px)', cursor: 'pointer' }}
              onClick={() => setSelectedEpisode(episode)}
              hoverable
            >
              <Space direction="vertical" size="small">
                <div>
                  <Tag color={getStatusColor(episode.status)}>
                    {episode.status === 'completed' ? '已完成' : episode.status}
                  </Tag>
                  {episode.qualityScore && (
                    <span>分数: {episode.qualityScore}</span>
                  )}
                </div>
                {episode.issues.length > 0 && (
                  <Tag color="warning">{episode.issues.length} 个问题</Tag>
                )}
                <Button
                  type="link"
                  size="small"
                  icon={<EyeOutlined />}
                  onClick={(e) => {
                    e.stopPropagation()
                    setSelectedEpisode(episode)
                  }}
                >
                  查看内容
                </Button>
              </Space>
            </Card>
          ))}
        </div>
      </Card>

      {/* 剧集内容弹窗 */}
      <Modal
        title={`EP${selectedEpisode?.number} - ${selectedEpisode?.title}`}
        open={!!selectedEpisode}
        onCancel={() => setSelectedEpisode(null)}
        footer={null}
        width={900}
      >
        {selectedEpisode && (
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            {selectedEpisode.outline && (
              <div>
                <Title level={5}>大纲</Title>
                <p>{selectedEpisode.outline}</p>
              </div>
            )}

            <Divider />

            <div>
              <Title level={5}>剧本内容</Title>
              <div style={{
                maxHeight: '65vh',
                overflowY: 'auto',
                borderRadius: '4px',
                background: '#fafafa',
                padding: '12px'
              }}>
                <MarkdownRenderer content={selectedEpisode.content} />
              </div>
            </div>

            <Divider />

            <div>
              <Title level={5}>质量信息</Title>
              <Space direction="vertical">
                {selectedEpisode.qualityScore && (
                  <div>质量分数: {selectedEpisode.qualityScore}</div>
                )}
                {selectedEpisode.issues.length > 0 && (
                  <div>
                    <Title level={5}>问题列表:</Title>
                    {selectedEpisode.issues.map((issue, idx) => (
                      <div key={idx}>
                        <Tag color={issue.severity === 'high' ? 'red' : 'orange'}>
                          {issue.severity}
                        </Tag>
                        {issue.description}
                      </div>
                    ))}
                  </div>
                )}
              </Space>
            </div>
          </Space>
        )}
      </Modal>
    </div>
  )
}
