/**
 * Review Task Card Component
 *
 * 审核任务卡片组件 - 支持过程中审核和生成后审核
 *
 * 功能：
 * 1. 显示审核任务信息（问题类型、位置、严重程度）
 * 2. 支持用户操作：确认、修改、忽略
 * 3. 过程中审核：完成后自动销毁
 * 4. 生成后审核：保留记录
 */
import React, { useState, useEffect } from 'react'
import {
  Card,
  Tag,
  Button,
  Space,
  Alert,
  Modal,
  Input,
  Radio,
  Divider,
  Tooltip,
  Typography
} from 'antd'
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  EditOutlined,
  EyeInvisibleOutlined,
  WarningOutlined,
  InfoCircleOutlined
} from '@ant-design/icons'
import { message } from 'antd'
import api from '@/services/api'
import type { ReviewTask } from '@/services/reviewService'

const { Text, Paragraph } = Typography

interface ReviewTaskCardProps {
  task: ReviewTask
  projectId: string
  onActionComplete?: (taskId: string, action: string, response?: string) => void
}

const ReviewTaskCard: React.FC<ReviewTaskCardProps> = ({
  task,
  projectId,
  onActionComplete
}) => {
  const [actionModalVisible, setActionModalVisible] = useState(false)
  const [selectedAction, setSelectedAction] = useState<string>('')
  const [userResponse, setUserResponse] = useState('')
  const [modifiedContent, setModifiedContent] = useState('')

  // 严重程度颜色
  const severityColors: Record<string, string> = {
    low: 'green',
    medium: 'orange',
    high: 'red'
  }

  const severityLabels: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高'
  }

  // 模式标签
  const modeLabels: Record<string, string> = {
    process: '过程中审核',
    'post_creation': '生成后审核'
  }

  // 触发来源标签
  const triggerSourceLabels: Record<string, string> = {
    agent_auto: 'Agent自主',
    user_skill: '用户配置Skill',
    user_rule: '用户配置规则',
    manual: '手动请求'
  }

  // 操作标签
  const actionLabels: Record<string, string> = {
    confirm: '确认继续',
    modify: '修改内容',
    ignore: '忽略问题',
    other: '补充信息'
  }

  // 处理操作
  const handleAction = async (action: string) => {
    if (!taskId || action === 'other') {
      // 其他操作需要打开模态框
      setSelectedAction(action)
      setActionModalVisible(true)
      return
    }

    try {
      const response = await api.post(`/review-task/process/${task.id}/action`, {
        action,
        user_response: userResponse || undefined,
        modified_content: modifiedContent || undefined
      })

      message.success('操作已提交')

      if (onActionComplete) {
        onActionComplete(task.id, action, userResponse)
      }

      // 如果是确认或忽略，关闭卡片（过程中审核自动销毁）
      if (action === 'confirm' || action === 'ignore') {
        setActionModalVisible(false)
      }
    } catch (error) {
      message.error('操作失败')
    }
  }

  const handleSubmitAction = async () => {
    await handleAction(selectedAction)
  }

  // 生成后审核的操作处理
  const handlePostCreationAction = async (action: string) => {
    if (action === 'other') {
      setSelectedAction(action)
      setActionModalVisible(true)
      return
    }

    try {
      const response = await api.post(`/review-task/post-creation/${task.id}/action`, {
        action,
        user_response: userResponse || undefined,
        modified_content: modifiedContent || undefined
      })

      message.success('操作已提交')

      if (onActionComplete) {
        onActionComplete(task.id, action, userResponse)
      }

      if (action === 'confirm' || action === 'ignore') {
        setActionModalVisible(false)
      }
    } catch (error) {
      message.error('操作失败')
    }
  }

  // 根据模式选择处理函数
  const isProcessReview = task.mode === 'process'
  const actionHandler = isProcessReview ? handleAction : handlePostCreationAction
  const taskId = task.id

  // 渲染操作按钮
  const renderActionButtons = () => (
    <Space direction="vertical" style={{ width: '100%' }}>
      {task.available_actions.map(action => (
        <Button
          key={action}
          type={action === 'confirm' ? 'primary' : 'default'}
          icon={
            action === 'confirm' ? <CheckCircleOutlined /> :
            action === 'modify' ? <EditOutlined /> :
            action === 'ignore' ? <EyeInvisibleOutlined /> :
            <InfoCircleOutlined />
          }
          onClick={() => actionHandler(action)}
          style={{ width: '100%' }}
        >
          {actionLabels[action]}
        </Button>
      ))}
    </Space>
  )

  // 渲染位置信息
  const renderLocation = () => {
    const { episode_number, scene_number, section, line_number, content_snippet } = task.location || {}
    const parts = []

    if (episode_number) parts.push(`第 ${episode_number} 集`)
    if (scene_number) parts.push(`场景 ${scene_number}`)
    if (section) parts.push(`段落: ${section}`)
    if (line_number) parts.push(`行 ${line_number}`)

    return (
      <div style={{ marginBottom: 12 }}>
        <Text type="secondary">
          <span style={{ fontWeight: 'bold' }}>位置: </span>
          {parts.join(' · ')}
        </Text>
        {content_snippet && (
          <div style={{
            marginTop: 8,
            padding: 8,
            background: '#f5f5f5',
            borderRadius: 4,
            fontSize: 12
          }}>
            <Text type="secondary">
              <Tooltip title={content_snippet}>
                {content_snippet.length > 100
                  ? content_snippet.substring(0, 100) + '...'
                  : content_snippet}
              </Tooltip>
            </Text>
          </div>
        )}
      </div>
    )
  }

  // 渲染操作模态框
  const renderActionModal = () => (
    <Modal
      title="确认操作"
      open={actionModalVisible}
      onCancel={() => setActionModalVisible(false)}
      footer={[
        <Button key="cancel" onClick={() => setActionModalVisible(false)}>
          取消
        </Button>,
        <Button
          key="submit"
          type="primary"
          onClick={handleSubmitAction}
          disabled={selectedAction === 'other' && !userResponse.trim()}
        >
          确认
        </Button>
      ]}
    >
      <Space direction="vertical" style={{ width: '100%' }}>
        <Text strong>操作: {actionLabels[selectedAction]}</Text>
        <Divider />

        {selectedAction === 'modify' && (
          <>
            <Text>修改内容:</Text>
            <Input.TextArea
              rows={6}
              placeholder="输入修改后的内容..."
              value={modifiedContent}
              onChange={e => setModifiedContent(e.target.value)}
              style={{ marginTop: 8 }}
            />
          </>
        )}

        {selectedAction === 'other' && (
          <>
            <Text>补充信息:</Text>
            <Input.TextArea
              rows={4}
              placeholder="输入补充说明..."
              value={userResponse}
              onChange={e => setUserResponse(e.target.value)}
              style={{ marginTop: 8 }}
            />
          </>
        )}

        {task.suggestion && (
          <Alert
            message="建议"
            description={task.suggestion}
            type="info"
            showIcon
            style={{ marginTop: 16 }}
          />
        )}
      </Space>
    </Modal>
  )

  return (
    <Card
      size="small"
      bordered={true}
      style={{
        marginBottom: 16,
        borderLeftWidth: 4,
        borderLeftColor: severityColors[task.severity]
      }}
    >
      {/* 头部：状态标签 */}
      <Space style={{ width: '100%', marginBottom: 12 }} wrap>
        <Tag color={severityColors[task.severity]}>
          {severityLabels[task.severity]} 严重度
        </Tag>
        <Tag color="blue">
          {task.issue_type}
        </Tag>
        <Tag color="cyan">
          {modeLabels[task.mode] || task.mode}
        </Tag>
        {task.trigger_source && (
          <Tag color="default">
            来源: {triggerSourceLabels[task.trigger_source] || task.trigger_source}
          </Tag>
        )}
      </Space>

      {/* 问题描述 */}
      <Paragraph
        style={{
          marginBottom: 12,
          padding: 12,
          background: '#fffbe6',
          borderRadius: 4,
          border: '1px solid #ffd591'
        }}
      >
        {task.issue_description}
      </Paragraph>

      {/* 位置信息 */}
      {renderLocation()}

      {/* 操作按钮 */}
      {renderActionButtons()}

      {/* 操作模态框 */}
      {renderActionModal()}

      {/* 修改建议 */}
      {task.suggestion && (
        <Alert
          message="修改建议"
          description={task.suggestion}
          type="info"
          showIcon
          style={{ marginTop: 8 }}
        />
      )}
    </Card>
  )
}

export default ReviewTaskCard
