/**
 * Review Results Page
 * Display review results with scores, issues, and actions
 */
import React, { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  List,
  Tag,
  Button,
  Space,
  Alert,
  Tabs,
  Modal,
  Form,
  Select,
  message,
  Divider,
  Typography,
  Empty,
  Spin
} from 'antd'
import {
  ArrowLeftOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  ToolOutlined,
  DownloadOutlined,
  ReloadOutlined,
  WarningOutlined
} from '@ant-design/icons'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, Legend, ResponsiveContainer, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar } from 'recharts'
import { useReviewStore } from '@/stores/reviewStore'
import { SeverityLevel, Issue } from '@/services/reviewService'

const { TabPane } = Tabs
const { Title, Text, Paragraph } = Typography

const ReviewResults: React.FC = () => {
  const { id: projectId } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const {
    currentResult,
    configuration,
    loading,
    error,
    executeReview,
    fetchLatestResult,
    ignoreIssue,
    unignoreIssue,
    autoFixIssue,
    applyBatchDecisions,
    exportReport
  } = useReviewStore()

  const [selectedEpisode, setSelectedEpisode] = useState<number | undefined>()
  const [batchActionModalVisible, setBatchActionModalVisible] = useState(false)
  const [selectedSeverity, setSelectedSeverity] = useState<SeverityLevel | 'all'>('all')

  // Parse query params for initial episode selection
  useEffect(() => {
    const params = new URLSearchParams(window.location.search)
    const epParam = params.get('episode')
    if (epParam) {
      setSelectedEpisode(parseInt(epParam, 10))
    }
  }, [])

  useEffect(() => {
    if (projectId) {
      fetchLatestResult(projectId, selectedEpisode)
    }
  }, [projectId, selectedEpisode])

  const severityColors: Record<SeverityLevel, string> = {
    low: 'green',
    medium: 'orange',
    high: 'red'
  }

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

  const getScoreColor = (score: number) => {
    if (score >= 80) return '#52c41a'
    if (score >= 60) return '#faad14'
    return '#f5222d'
  }

  const handleExecuteReview = async () => {
    if (!projectId) return
    try {
      await executeReview(projectId, selectedEpisode)
      message.success('审核完成')
    } catch (error) {
      message.error('审核失败')
    }
  }

  const handleIgnoreIssue = async (issueId: string) => {
    if (!projectId) return
    try {
      await ignoreIssue(projectId, issueId)
      message.success('已忽略问题')
    } catch (error) {
      message.error('操作失败')
    }
  }

  const handleUnignoreIssue = async (issueId: string) => {
    if (!projectId) return
    try {
      await unignoreIssue(projectId, issueId)
      message.success('已恢复问题')
    } catch (error) {
      message.error('操作失败')
    }
  }

  const handleAutoFix = async (issueId: string) => {
    if (!projectId) return
    try {
      await autoFixIssue(projectId, issueId)
      message.success('自动修复完成')
    } catch (error) {
      message.error('自动修复失败')
    }
  }

  const handleBatchAction = async (action: 'accept' | 'reject' | 'ignore') => {
    if (!projectId || !currentResult) return
    try {
      const decisions = currentResult.issues
        .filter(issue => !issue.ignored)
        .filter(issue => selectedSeverity === 'all' || issue.severity === selectedSeverity)
        .map(issue => ({ issueId: issue.id, action }))

      await applyBatchDecisions(projectId, decisions)
      message.success(`批量${action === 'accept' ? '接受' : action === 'reject' ? '拒绝' : '忽略'}完成`)
      setBatchActionModalVisible(false)
    } catch (error) {
      message.error('批量操作失败')
    }
  }

  const handleExportReport = async (format: 'json' | 'pdf' | 'markdown') => {
    if (!projectId || !currentResult) return
    try {
      await exportReport(projectId, currentResult.id || 'latest', format, false)
      message.success('导出成功')
    } catch (error) {
      message.error('导出失败')
    }
  }

  const groupedIssues = currentResult?.issues.reduce((acc, issue) => {
    if (!acc[issue.severity]) {
      acc[issue.severity] = []
    }
    if (!issue.ignored) {
      acc[issue.severity].push(issue)
    }
    return acc
  }, {} as Record<SeverityLevel, Issue[]>) || {}

  const visibleIssues = currentResult?.issues.filter(issue => !issue.ignored) || []
  const ignoredIssues = currentResult?.issues.filter(issue => issue.ignored) || []

  const renderOverallScore = () => {
    if (!currentResult) return null

    const score = currentResult.overallScore

    return (
      <Card>
        <Row gutter={16}>
          <Col span={8}>
            <Statistic
              title="总体评分"
              value={score}
              suffix="/ 100"
              valueStyle={{ color: getScoreColor(score), fontSize: 48 }}
            />
            <Progress
              percent={score}
              strokeColor={getScoreColor(score)}
              showInfo={false}
              style={{ marginTop: 16 }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="问题总数"
              value={visibleIssues.length}
              suffix={`/ ${currentResult.issues.length}`}
              valueStyle={{ color: visibleIssues.length > 0 ? '#f5222d' : '#52c41a' }}
            />
            <div style={{ marginTop: 16 }}>
              <Space direction="vertical" style={{ width: '100%' }}>
                <div>
                  <Tag color="red">高: {groupedIssues.high?.length || 0}</Tag>
                  <Tag color="orange">中: {groupedIssues.medium?.length || 0}</Tag>
                  <Tag color="green">低: {groupedIssues.low?.length || 0}</Tag>
                </div>
              </Space>
            </div>
          </Col>
          <Col span={8}>
            <Space direction="vertical">
              <Button
                type="primary"
                icon={<ReloadOutlined />}
                onClick={handleExecuteReview}
                loading={loading}
              >
                重新审核
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => setBatchActionModalVisible(true)}
              >
                批量操作
              </Button>
              <Button.Group>
                <Button size="small" onClick={() => handleExportReport('json')}>JSON</Button>
                <Button size="small" onClick={() => handleExportReport('pdf')}>PDF</Button>
                <Button size="small" onClick={() => handleExportReport('markdown')}>MD</Button>
              </Button.Group>
            </Space>
          </Col>
        </Row>
      </Card>
    )
  }

  const renderDimensionScores = () => {
    if (!currentResult) return null

    const chartData = currentResult.dimensionScores.map(ds => ({
      dimension: ds.dimension,
      score: ds.score,
      weight: ds.weight,
      fullMark: 100
    }))

    return (
      <Card title="维度评分">
        <Row gutter={16}>
          <Col span={12}>
            <Title level={5}>柱状图</Title>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="dimension" angle={-45} textAnchor="end" height={100} />
                <YAxis />
                <RechartsTooltip />
                <Legend />
                <Bar dataKey="score" fill="#0ea5e9" name="分数" />
              </BarChart>
            </ResponsiveContainer>
          </Col>
          <Col span={12}>
            <Title level={5}>雷达图</Title>
            <ResponsiveContainer width="100%" height={300}>
              <RadarChart data={chartData}>
                <PolarGrid />
                <PolarAngleAxis dataKey="dimension" />
                <PolarRadiusAxis angle={30} domain={[0, 100]} />
                <Radar name="分数" dataKey="score" stroke="#0ea5e9" fill="#0ea5e9" fillOpacity={0.6} />
              </RadarChart>
            </ResponsiveContainer>
          </Col>
        </Row>
        <Divider />
        <List
          dataSource={currentResult.dimensionScores}
          renderItem={(ds) => (
            <List.Item>
              <List.Item.Meta
                title={
                  <Space>
                    {ds.dimension}
                    <Tag color="blue">权重: {(ds.weight * 100).toFixed(0)}%</Tag>
                  </Space>
                }
                description={
                  <Progress
                    percent={ds.score}
                    strokeColor={getScoreColor(ds.score)}
                    format={(percent) => `${percent}分`}
                  />
                }
              />
              <div style={{ width: 200 }}>
                <Statistic
                  value={ds.score}
                  suffix={`/ 100`}
                  valueStyle={{ color: getScoreColor(ds.score), fontSize: 20 }}
                />
              </div>
            </List.Item>
          )}
        />
      </Card>
    )
  }

  const renderIssueCard = (issue: Issue) => (
    <Card
      key={issue.id}
      size="small"
      style={{ marginBottom: 16 }}
      title={
        <Space>
          <Tag color={severityColors[issue.severity]}>{severityLabels[issue.severity]}</Tag>
          <span>{issue.type}</span>
          <Tag color="blue">{issue.dimension}</Tag>
        </Space>
      }
      extra={
        <Space>
          {issue.canAutoFix && (
            <Button
              size="small"
              type="primary"
              icon={<ToolOutlined />}
              onClick={() => handleAutoFix(issue.id)}
            >
              自动修复
            </Button>
          )}
          <Button
            size="small"
            icon={<EyeInvisibleOutlined />}
            onClick={() => handleIgnoreIssue(issue.id)}
          >
            忽略
          </Button>
        </Space>
      }
    >
      <Space direction="vertical" style={{ width: '100%' }}>
        <div>
          <strong>位置:</strong>{' '}
          {issue.location.section && `${issue.location.section} - `}
          {issue.location.episodeNumber && `第 ${issue.location.episodeNumber} 集`}
          {issue.location.lineNumber && `:${issue.location.lineNumber}行`}
        </div>
        <div>
          <strong>问题描述:</strong> {issue.description}
        </div>
        <div>
          <strong>原文:</strong>
          <Paragraph
            ellipsis={{ rows: 2, expandable: true, symbol: '展开' }}
            style={{
              background: '#f5f5f5',
              padding: '8px',
              borderRadius: '4px',
              marginTop: '8px'
            }}
          >
            {issue.originalText}
          </Paragraph>
        </div>
        {issue.suggestion && (
          <div>
            <strong>建议:</strong>
            <Paragraph
              ellipsis={{ rows: 2, expandable: true, symbol: '展开' }}
              style={{
                background: '#e6f7ff',
                padding: '8px',
                borderRadius: '4px',
                marginTop: '8px'
              }}
            >
              {issue.suggestion}
            </Paragraph>
          </div>
        )}
      </Space>
    </Card>
  )

  const renderIgnoredIssueCard = (issue: Issue) => (
    <Card
      key={issue.id}
      size="small"
      style={{ marginBottom: 16, opacity: 0.6 }}
      type="inner"
    >
      <Space direction="vertical" style={{ width: '100%' }}>
        <Space>
          <Tag color={severityColors[issue.severity]}>{severityLabels[issue.severity]}</Tag>
          <span>{issue.type}</span>
          <Tag>{issue.dimension}</Tag>
          <Tag color="default">已忽略</Tag>
          <Button
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleUnignoreIssue(issue.id)}
          >
            恢复
          </Button>
        </Space>
        <div>{issue.description}</div>
      </Space>
    </Card>
  )

  const renderIssues = () => {
    if (!currentResult) return null

    return (
      <Card title="问题列表">
        <Tabs defaultActiveKey="all">
          <TabPane tab={`全部 (${visibleIssues.length})`} key="all">
            {visibleIssues.length === 0 ? (
              <Empty description="暂无问题" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            ) : (
              visibleIssues.map(issue => renderIssueCard(issue))
            )}
          </TabPane>
          <TabPane
            tab={
              <span>
                <WarningOutlined style={{ color: '#f5222d' }} />
                高严重度 ({groupedIssues.high?.length || 0})
              </span>
            }
            key="high"
          >
            {groupedIssues.high?.length === 0 ? (
              <Empty description="暂无高严重度问题" />
            ) : (
              groupedIssues.high?.map(issue => renderIssueCard(issue))
            )}
          </TabPane>
          <TabPane
            tab={
              <span>
                <WarningOutlined style={{ color: '#faad14' }} />
                中严重度 ({groupedIssues.medium?.length || 0})
              </span>
            }
            key="medium"
          >
            {groupedIssues.medium?.length === 0 ? (
              <Empty description="暂无中严重度问题" />
            ) : (
              groupedIssues.medium?.map(issue => renderIssueCard(issue))
            )}
          </TabPane>
          <TabPane
            tab={
              <span>
                <WarningOutlined style={{ color: '#52c41a' }} />
                低严重度 ({groupedIssues.low?.length || 0})
              </span>
            }
            key="low"
          >
            {groupedIssues.low?.length === 0 ? (
              <Empty description="暂无低严重度问题" />
            ) : (
              groupedIssues.low?.map(issue => renderIssueCard(issue))
            )}
          </TabPane>
          <TabPane
            tab={
              <span>
                <EyeInvisibleOutlined />
                已忽略 ({ignoredIssues.length})
              </span>
            }
            key="ignored"
          >
            {ignoredIssues.length === 0 ? (
              <Empty description="暂无已忽略问题" />
            ) : (
              ignoredIssues.map(issue => renderIgnoredIssueCard(issue))
            )}
          </TabPane>
        </Tabs>
      </Card>
    )
  }

  const renderSummary = () => {
    if (!currentResult) return null

    return (
      <Card title="审核摘要">
        <Paragraph>{currentResult.summary}</Paragraph>
        {currentResult.configuration && (
          <div>
            <Divider />
            <Text type="secondary">
              审核配置: {currentResult.configuration.preset}
            </Text>
          </div>
        )}
      </Card>
    )
  }

  if (loading && !currentResult) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
      </div>
    )
  }

  if (error) {
    return <div style={{ padding: '24px', color: 'red' }}>Error: {error}</div>
  }

  if (!currentResult) {
    return (
      <div style={{ padding: 24 }}>
        <Card>
          <Empty description="暂无审核结果">
            <Button type="primary" onClick={handleExecuteReview} loading={loading}>
              开始审核
            </Button>
          </Empty>
        </Card>
      </div>
    )
  }

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: '#fff', padding: '16px', borderRadius: '8px', boxShadow: '0 1px 2px rgba(0,0,0,0.03)' }}>
        <Space size="middle">
          <Button
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate(`/projects/${projectId}`)}
            size="large"
          >
            返回项目详情
          </Button>
          <div>
            <Title level={4} style={{ margin: 0 }}>审核结果</Title>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              {selectedEpisode ? `EP${selectedEpisode} 质量分析报告` : '最新审核报告'}
            </Text>
          </div>
        </Space>
      </div>

      <Space direction="vertical" style={{ width: '100%' }} size="large">
        {renderOverallScore()}
        {renderDimensionScores()}
        {renderIssues()}
        {renderSummary()}
      </Space>

      {/* Batch Action Modal */}
      <Modal
        title="批量操作"
        open={batchActionModalVisible}
        onCancel={() => setBatchActionModalVisible(false)}
        footer={null}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Form.Item label="筛选严重度">
            <Select
              value={selectedSeverity}
              onChange={setSelectedSeverity}
              style={{ width: '100%' }}
            >
              <Select.Option value="all">全部</Select.Option>
              <Select.Option value="high">高</Select.Option>
              <Select.Option value="medium">中</Select.Option>
              <Select.Option value="low">低</Select.Option>
            </Select>
          </Form.Item>
          <Alert
            message={`将对 ${visibleIssues.filter(i => selectedSeverity === 'all' || i.severity === selectedSeverity).length} 个问题执行批量操作`}
            type="info"
          />
          <Space>
            <Button onClick={() => handleBatchAction('ignore')}>
              <EyeInvisibleOutlined /> 批量忽略
            </Button>
            <Button onClick={() => setBatchActionModalVisible(false)}>
              取消
            </Button>
          </Space>
        </Space>
      </Modal>
    </div>
  )
}

export default ReviewResults
