/**
 * Review Platform Page
 *
 * 审核平台页面 - 审核卡片列表和详情
 *
 * 功能：
 * 1. 显示所有审核卡片
 * 2. 按状态筛选
 * 3. 统计数据展示
 * 4. 点击卡片查看详情
 * 5. 详情中执行审核操作（通过/驳回/修改）
 */
import React, { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import {
  Card,
  Row,
  Col,
  Statistic,
  List,
  Tag,
  Button,
  Space,
  Select,
  message,
  Typography,
  Empty,
  Spin,
  Badge,
  Modal,
  Alert,
  Descriptions,
  Progress,
  Input
} from 'antd'
import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  WarningOutlined,
  EyeOutlined,
  FilterOutlined,
  ReloadOutlined,
  CloseCircleOutlined,
  EditOutlined
} from '@ant-design/icons'
import { useReviewCardStore } from '@/stores/reviewCardStore'
import { ReviewCard, ReviewCardStatus } from '@/services/reviewCardService'

const { Title, Text, Paragraph } = Typography
const { TextArea } = Input

interface ReviewResultsProps {
  projectId?: string
}

// 状态映射
const statusConfig: Record<ReviewCardStatus, { label: string; color: string; icon: React.ReactNode }> = {
  [ReviewCardStatus.PENDING]: { label: '待处理', color: 'default', icon: <ClockCircleOutlined /> },
  [ReviewCardStatus.AWAITING_USER]: { label: '待确认', color: 'warning', icon: <WarningOutlined /> },
  [ReviewCardStatus.APPROVED]: { label: '已通过', color: 'success', icon: <CheckCircleOutlined /> },
  [ReviewCardStatus.REJECTED]: { label: '已驳回', color: 'error', icon: <CloseCircleOutlined /> }
}

// 严重程度映射
const severityConfig: Record<'low' | 'medium' | 'high', { label: string; color: string }> = {
  low: { label: '低', color: 'green' },
  medium: { label: '中', color: 'orange' },
  high: { label: '高', color: 'red' }
}

const ReviewResults: React.FC<ReviewResultsProps> = ({ projectId: propProjectId }) => {
  const { id: routeProjectId } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const projectId = propProjectId || routeProjectId

  const {
    cards,
    stats,
    statusFilter,
    loading,
    fetchCards,
    fetchStats,
    approveCard,
    rejectCard,
    modifyCard,
    setStatusFilter
  } = useReviewCardStore()

  const [selectedCard, setSelectedCard] = useState<ReviewCard | null>(null)
  const [detailVisible, setDetailVisible] = useState(false)
  const [actionLoading, setActionLoading] = useState(false)

  // 操作相关
  const [actionModalVisible, setActionModalVisible] = useState(false)
  const [actionType, setActionType] = useState<'approve' | 'reject' | 'modify'>('approve')
  const [userComment, setUserComment] = useState('')

  useEffect(() => {
    if (projectId) {
      fetchCards(projectId)
      fetchStats(projectId)
    }
  }, [projectId])

  // 刷新数据
  const handleRefresh = async () => {
    if (projectId) {
      await Promise.all([
        fetchCards(projectId),
        fetchStats(projectId)
      ])
      message.success('刷新成功')
    }
  }

  // 筛选变更
  const handleStatusChange = (value: ReviewCardStatus | 'all') => {
    setStatusFilter(value)
    if (projectId) {
      fetchCards(projectId, value === 'all' ? undefined : value)
    }
  }

  // 查看详情
  const handleViewDetail = (card: ReviewCard) => {
    setSelectedCard(card)
    setDetailVisible(true)
  }

  // 操作
  const handleAction = (type: 'approve' | 'reject' | 'modify') => {
    setActionType(type)
    setUserComment('')
    setActionModalVisible(true)
  }

  const handleActionSubmit = async () => {
    if (!selectedCard) return

    setActionLoading(true)
    try {
      if (actionType === 'approve') {
        await approveCard(selectedCard.id, userComment || undefined)
        message.success('已通过审核')
      } else if (actionType === 'reject') {
        await rejectCard(selectedCard.id, userComment || undefined)
        message.success('已驳回审核')
      } else if (actionType === 'modify') {
        await modifyCard(selectedCard.id, userComment || undefined)
        message.success('已标记为修改')
      }

      setActionModalVisible(false)
      setUserComment('')
      setDetailVisible(false)

      // 刷新数据
      if (projectId) {
        await Promise.all([
          fetchCards(projectId),
          fetchStats(projectId)
        ])
      }
    } catch (error: any) {
      message.error(`操作失败: ${error?.message || ''}`)
    } finally {
      setActionLoading(false)
    }
  }

  // 跳转到剧集创作
  const handleGoToEpisode = () => {
    if (selectedCard?.episode_numbers && selectedCard.episode_numbers.length > 0) {
      setDetailVisible(false)
      navigate(`/projects/${projectId}`, {
        state: { activeTab: 'episodes', episodeNumber: selectedCard.episode_numbers[0] }
      })
    }
  }

  // 过滤卡片
  const filteredCards = cards.filter(card => {
    const matchStatus = statusFilter === 'all' || card.status === statusFilter
    return matchStatus
  })

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto', padding: '24px' }}>
      {/* 头部操作栏 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={3} style={{ margin: 0 }}>审核平台</Title>
        <Space>
          <Select
            value={statusFilter}
            onChange={handleStatusChange}
            style={{ width: 150 }}
          >
            <Select.Option value="all">全部状态</Select.Option>
            {Object.entries(statusConfig).map(([key, config]) => (
              <Select.Option key={key} value={key}>
                {config.icon} {config.label}
              </Select.Option>
            ))}
          </Select>
          <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
            刷新
          </Button>
        </Space>
      </div>

      {/* 统计卡片 */}
      {stats && (
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={4}>
            <Card>
              <Statistic title="总计" value={stats.total} valueStyle={{ color: '#1890ff' }} />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic title="待处理" value={stats.pending} valueStyle={{ color: '#faad14' }} />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic title="待确认" value={stats.awaiting_user} valueStyle={{ color: '#ff4d4f' }} />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic title="已通过" value={stats.approved} valueStyle={{ color: '#52c41a' }} />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic title="已驳回" value={stats.rejected} valueStyle={{ color: '#f5222d' }} />
            </Card>
          </Col>
        </Row>
      )}

      {/* 卡片列表 */}
      <Card
        title={<><FilterOutlined /> 审核卡片列表</>}
        extra={<Badge count={filteredCards.length} showZero />}
      >
        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
          </div>
        ) : filteredCards.length === 0 ? (
          <Empty description="暂无审核卡片" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ) : (
          <List
            dataSource={filteredCards}
            renderItem={(card) => (
              <List.Item
                key={card.id}
                style={{
                  border: '1px solid #f0f0f0',
                  borderRadius: '8px',
                  marginBottom: '16px',
                  padding: '16px',
                  cursor: 'pointer',
                  transition: 'all 0.2s'
                }}
                onClick={() => handleViewDetail(card)}
                onMouseEnter={(e) => {
                  e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)'
                  e.currentTarget.style.borderColor = '#1890ff'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.boxShadow = 'none'
                  e.currentTarget.style.borderColor = '#f0f0f0'
                }}
              >
                <List.Item.Meta
                  avatar={
                    <Badge
                      status={severityConfig[card.severity as keyof typeof severityConfig]?.color as any}
                      text={
                        <div style={{ textAlign: 'center' }}>
                          <div style={{ fontSize: '24px', fontWeight: 'bold' }}>
                            {card.overall_score ? Math.round(card.overall_score) : '-'}
                          </div>
                          <div style={{ fontSize: '12px', color: '#999' }}>分</div>
                        </div>
                      }
                    />
                  }
                  title={
                    <Space>
                      <Text strong>EP{card.episode_numbers.join(', ')}</Text>
                      <Tag color={severityConfig[card.severity as keyof typeof severityConfig]?.color}>
                        {severityConfig[card.severity as keyof typeof severityConfig]?.label}
                      </Tag>
                      <Tag icon={statusConfig[card.status].icon} color={statusConfig[card.status].color}>
                        {statusConfig[card.status].label}
                      </Tag>
                      {card.issues.length > 0 && <Tag color="orange">{card.issues.length} 个问题</Tag>}
                    </Space>
                  }
                  description={
                    <div>
                      <Text type="secondary">{card.review_reason}</Text>
                      <div style={{ marginTop: '8px', fontSize: '12px', color: '#999' }}>
                        创建时间: {new Date(card.created_at).toLocaleString()}
                      </div>
                    </div>
                  }
                />
                <Button type="link" icon={<EyeOutlined />}>
                  查看详情
                </Button>
              </List.Item>
            )}
          />
        )}
      </Card>

      {/* 详情模态框 */}
      <Modal
        title={
          <Space>
            <span>审核卡片详情 - EP{selectedCard?.episode_numbers.join(', ')}</span>
            <Tag color={selectedCard ? severityConfig[selectedCard.severity]?.color : ''}>
              {selectedCard ? severityConfig[selectedCard.severity]?.label : ''}
            </Tag>
          </Space>
        }
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        width={900}
        footer={
          <Space>
            <Button onClick={() => setDetailVisible(false)}>关闭</Button>
            {selectedCard?.status === ReviewCardStatus.AWAITING_USER && (
              <>
                <Button danger onClick={() => handleAction('reject')}>驳回</Button>
                <Button onClick={() => handleAction('modify')}>标记修改</Button>
                <Button type="primary" onClick={() => handleAction('approve')}>通过</Button>
              </>
            )}
            {selectedCard?.episode_numbers && selectedCard.episode_numbers.length > 0 && (
              <Button icon={<EditOutlined />} onClick={handleGoToEpisode}>
                去剧集创作修改
              </Button>
            )}
          </Space>
        }
      >
        {selectedCard && (
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            {/* 基本信息 */}
            <Descriptions column={2} bordered size="small">
              <Descriptions.Item label="状态">
                <Tag icon={statusConfig[selectedCard.status].icon} color={statusConfig[selectedCard.status].color}>
                  {statusConfig[selectedCard.status].label}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="严重度">
                <Tag color={severityConfig[selectedCard.severity]?.color}>
                  {severityConfig[selectedCard.severity]?.label}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="总体评分" span={2}>
                {selectedCard.overall_score ? (
                  <Progress
                    percent={Math.round(selectedCard.overall_score)}
                    strokeColor={selectedCard.overall_score >= 80 ? '#52c41a' : selectedCard.overall_score >= 60 ? '#faad14' : '#f5222d'}
                  />
                ) : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="审核原因" span={2}>
                {selectedCard.review_reason}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间" span={2}>
                {new Date(selectedCard.created_at).toLocaleString()}
              </Descriptions.Item>
            </Descriptions>

            {/* 问题列表 */}
            {selectedCard.issues.length > 0 && (
              <Card title={`问题列表 (${selectedCard.issues.length})`} size="small">
                <List
                  dataSource={selectedCard.issues}
                  renderItem={(issue: any, index) => (
                    <List.Item key={index}>
                      <List.Item.Meta
                        avatar={
                          <Tag color={issue.severity === 'high' ? 'red' : issue.severity === 'medium' ? 'orange' : 'green'}>
                            {issue.severity === 'high' ? '高' : issue.severity === 'medium' ? '中' : '低'}
                          </Tag>
                        }
                        title={issue.type}
                        description={
                          <div>
                            <Paragraph style={{ margin: 0 }}>{issue.description}</Paragraph>
                            {issue.suggestion && (
                              <Alert type="info" message="建议" description={issue.suggestion} style={{ marginTop: 8 }} />
                            )}
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              </Card>
            )}

            {/* 剧集内容 */}
            {selectedCard.episode_outline && (
              <Card title="剧集大纲" size="small">
                <Paragraph style={{ whiteSpace: 'pre-wrap', margin: 0 }}>{selectedCard.episode_outline}</Paragraph>
              </Card>
            )}

            {selectedCard.episode_content && (
              <Card title="剧集内容" size="small">
                <Paragraph style={{ whiteSpace: 'pre-wrap', margin: 0, maxHeight: 300, overflowY: 'auto' }}>
                  {selectedCard.episode_content}
                </Paragraph>
              </Card>
            )}

            {/* 已有评论 */}
            {selectedCard.user_comment && (
              <Alert type="info" message="用户评论" description={selectedCard.user_comment} />
            )}
          </Space>
        )}
      </Modal>

      {/* 操作模态框 */}
      <Modal
        title={actionType === 'approve' ? '通过审核' : actionType === 'reject' ? '驳回审核' : '标记修改'}
        open={actionModalVisible}
        onOk={handleActionSubmit}
        onCancel={() => setActionModalVisible(false)}
        confirmLoading={actionLoading}
      >
        <TextArea
          placeholder="请输入评论（可选）"
          value={userComment}
          onChange={(e) => setUserComment(e.target.value)}
          rows={4}
          maxLength={500}
          showCount
        />
      </Modal>
    </div>
  )
}

export default ReviewResults
