/**
 * 任务进度追踪器组件
 *
 * 用于显示异步任务的执行进度
 * 支持：
 * - 多阶段进度显示
 * - 实时进度更新
 * - 错误显示
 * - 完成状态
 */
import { useEffect, useState } from 'react'
import { Card, Steps, Progress, Alert, Space, Tag, Button } from 'antd'
import {
  CheckCircleOutlined,
  SyncOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  ReloadOutlined
} from '@ant-design/icons'
import api from '@/services/api'

const { Step } = Steps

export interface TaskStage {
  id: string
  name: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  progress?: number
  error?: string
}

export interface TaskProgress {
  taskId: string
  type: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  stages?: TaskStage[]
  currentStage?: string
  progress: {
    current: number
    total: number
    message: string
    stage?: string
  }
  result?: any
  error?: string
  createdAt: string
  updatedAt: string
}

interface TaskProgressTrackerProps {
  taskId: string
  onComplete?: (result: any) => void
  onError?: (error: string) => void
  stages?: Array<{ id: string; name: string; description?: string }>
  pollInterval?: number
}

export const TaskProgressTracker = ({
  taskId,
  onComplete,
  onError,
  stages,
  pollInterval = 1000
}: TaskProgressTrackerProps) => {
  const [taskProgress, setTaskProgress] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  // 轮询任务进度
  useEffect(() => {
    let mounted = true
    let pollTimer: NodeJS.Timeout

    const fetchProgress = async () => {
      try {
        // 后端返回的是 TaskResponse 对象，包含 status, progress 等字段
        const data = await api.get<any>(`/tasks/${taskId}`)
        console.log('TaskProgressTracker - fetched data:', data)

        if (!mounted) return

        setTaskProgress(data)
        setLoading(false)

        // 任务完成或失败时停止轮询
        if (data.status === 'completed') {
          onComplete?.(data.result)
          return
        }
        if (data.status === 'failed') {
          onError?.(data.error || '任务执行失败')
          return
        }

        // 继续轮询
        pollTimer = setTimeout(fetchProgress, pollInterval)
      } catch (err) {
        console.error('获取任务进度失败:', err)
        if (mounted) {
          setLoading(false)
        }
      }
    }

    fetchProgress()

    return () => {
      mounted = false
      if (pollTimer) {
        clearTimeout(pollTimer)
      }
    }
  }, [taskId, pollInterval])

  // 获取状态图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />
      case 'running':
        return <SyncOutlined spin style={{ color: '#1677ff' }} />
      case 'failed':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
      default:
        return <ClockCircleOutlined style={{ color: '#d9d9d9' }} />
    }
  }

  // 获取状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return '#52c41a'
      case 'running':
        return '#1677ff'
      case 'failed':
        return '#ff4d4f'
      default:
        return '#d9d9d9'
    }
  }

  // 计算进度百分比
  const getProgressPercent = () => {
    if (!taskProgress) return 0
    // taskProgress 是 TaskResponse 对象，包含 progress 字段
    // progress 是 TaskProgress 对象，包含 current 和 total 字段
    const progressData = taskProgress.progress || { current: 0, total: 100 }
    const { current, total } = progressData
    return total > 0 ? Math.round((current / total) * 100) : 0
  }

  if (loading) {
    return (
      <Card loading bordered={false}>
        <div style={{ padding: '20px 0' }}>加载任务进度...</div>
      </Card>
    )
  }

  if (!taskProgress) {
    return (
      <Alert
        message="任务不存在"
        description="无法找到任务信息"
        type="error"
        showIcon
      />
    )
  }

  const { status, progress, error } = taskProgress

  return (
    <Card
      title="任务执行进度"
      extra={
        <Tag color={getStatusColor(status)}>
          {status === 'completed' && '已完成'}
          {status === 'running' && '执行中'}
          {status === 'failed' && '失败'}
          {status === 'pending' && '等待中'}
        </Tag>
      }
    >
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        {/* 进度条 */}
        <div>
          <div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
            <span>{progress.message || '正在处理...'}</span>
            <span>{getProgressPercent()}%</span>
          </div>
          <Progress
            percent={getProgressPercent()}
            status={
              status === 'failed' ? 'exception' :
              status === 'completed' ? 'success' :
              'active'
            }
          />
        </div>

        {/* 错误信息 */}
        {status === 'failed' && error && (
          <Alert
            message="执行失败"
            description={error}
            type="error"
            showIcon
          />
        )}

        {/* 完成信息 */}
        {status === 'completed' && (
          <Alert
            message="执行完成"
            description="任务已成功完成"
            type="success"
            showIcon
          />
        )}

        {/* 任务详情 */}
        <div style={{ fontSize: '12px', color: '#666' }}>
          <div>任务ID: {taskProgress.taskId || taskProgress.id}</div>
          <div>任务类型: {taskProgress.type}</div>
          <div>创建时间: {taskProgress.createdAt ? new Date(taskProgress.createdAt).toLocaleString() : new Date(taskProgress.created_at).toLocaleString()}</div>
        </div>
      </Space>
    </Card>
  )
}


/**
 * 多阶段进度追踪器
 */
interface StageProgressTrackerProps {
  taskId: string
  stages: Array<{ id: string; name: string; description?: string }>
  onComplete?: (result: any) => void
  onError?: (error: string) => void
  pollInterval?: number
}

export const StageProgressTracker = ({
  taskId,
  stages,
  onComplete,
  onError,
  pollInterval = 1000
}: StageProgressTrackerProps) => {
  const [taskProgress, setTaskProgress] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let mounted = true
    let pollTimer: NodeJS.Timeout

    const fetchProgress = async () => {
      try {
        const data = await api.get<TaskProgress>(`/tasks/${taskId}`)
        if (!mounted) return

        setTaskProgress(data)
        setLoading(false)

        if (data.status === 'completed') {
          onComplete?.(data.result)
          return
        }
        if (data.status === 'failed') {
          onError?.(data.error || '任务执行失败')
          return
        }

        pollTimer = setTimeout(fetchProgress, pollInterval)
      } catch (err) {
        console.error('获取任务进度失败:', err)
        if (mounted) {
          setLoading(false)
        }
      }
    }

    fetchProgress()

    return () => {
      mounted = false
      if (pollTimer) {
        clearTimeout(pollTimer)
      }
    }
  }, [taskId, pollInterval])

  // 获取当前阶段索引
  const getCurrentStageIndex = () => {
    if (!taskProgress || !taskProgress.currentStage) return -1
    return stages.findIndex(s => s.id === taskProgress.currentStage)
  }

  // 获取阶段状态
  const getStageStatus = (stageId: string): 'wait' | 'process' | 'finish' | 'error' => {
    if (!taskProgress) return 'wait'

    if (taskProgress.status === 'failed') {
      return 'error'
    }

    const currentIndex = getCurrentStageIndex()
    const stageIndex = stages.findIndex(s => s.id === stageId)

    if (stageIndex < currentIndex) return 'finish'
    if (stageIndex === currentIndex) return 'process'
    return 'wait'
  }

  if (loading) {
    return (
      <Card loading bordered={false}>
        <div style={{ padding: '20px 0' }}>加载进度...</div>
      </Card>
    )
  }

  if (!taskProgress) {
    return (
      <Alert
        message="任务不存在"
        type="error"
        showIcon
      />
    )
  }

  return (
    <Card title="任务执行进度">
      <Steps
        current={getCurrentStageIndex()}
        status={taskProgress.status === 'failed' ? 'error' : 'process'}
      >
        {stages.map((stage, index) => (
          <Step
            key={stage.id}
            title={stage.name}
            description={stage.description}
            status={getStageStatus(stage.id)}
          />
        ))}
      </Steps>

      {/* 进度条 */}
      <div style={{ marginTop: '24px' }}>
        <Progress
          percent={Math.round(
            (taskProgress.progress.current / taskProgress.progress.total) * 100
          )}
          status={
            taskProgress.status === 'failed' ? 'exception' :
            taskProgress.status === 'completed' ? 'success' :
            'active'
          }
        />
        <div style={{ marginTop: '8px', textAlign: 'center', color: '#666' }}>
          {taskProgress.progress.message}
        </div>
      </div>

      {/* 错误信息 */}
      {taskProgress.status === 'failed' && taskProgress.error && (
        <Alert
          message="执行失败"
          description={taskProgress.error}
          type="error"
          showIcon
          style={{ marginTop: '16px' }}
        />
      )}
    </Card>
  )
}


/**
 * 任务结果展示组件
 */
interface TaskResultProps {
  result: any
  taskType: string
}

export const TaskResultDisplay = ({ result, taskType }: TaskResultProps) => {
  const getResultContent = () => {
    switch (taskType) {
      case 'generate_characters':
        return (
          <div>
            <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>人物设定</div>
            <div style={{
              whiteSpace: 'pre-wrap',
              background: '#f5f5f5',
              padding: '12px',
              borderRadius: '4px',
              maxHeight: '60vh',
              overflowY: 'auto',
              wordBreak: 'break-word',
              lineHeight: '1.6'
            }}>
              {result?.characters || result}
            </div>
          </div>
        )

      case 'generate_outline':
        return (
          <div>
            <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>剧情大纲</div>
            <div style={{
              whiteSpace: 'pre-wrap',
              background: '#f5f5f5',
              padding: '12px',
              borderRadius: '4px',
              maxHeight: '60vh',
              overflowY: 'auto',
              wordBreak: 'break-word',
              lineHeight: '1.6'
            }}>
              {result?.outline || result}
            </div>
          </div>
        )

      case 'generate_world':
        return (
          <div>
            <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>世界观设定</div>
            <div style={{
              whiteSpace: 'pre-wrap',
              background: '#f5f5f5',
              padding: '12px',
              borderRadius: '4px',
              maxHeight: '60vh',
              overflowY: 'auto',
              wordBreak: 'break-word',
              lineHeight: '1.6'
            }}>
              {result?.worldSetting || result}
            </div>
          </div>
        )

      default:
        return (
          <pre style={{
            background: '#f5f5f5',
            padding: '12px',
            borderRadius: '4px',
            maxHeight: '60vh',
            overflowY: 'auto',
            wordBreak: 'break-word',
            fontSize: '13px',
            lineHeight: '1.6'
          }}>
            {JSON.stringify(result, null, 2)}
          </pre>
        )
    }
  }

  return (
    <Card title="生成结果">
      {getResultContent()}
    </Card>
  )
}

export default TaskProgressTracker
