/**
 * 审核工作台页面
 * 
 * 功能：
 * 1. 显示任务进度（轮询）
 * 2. 双行表格展示筛选结果（DeepSeek + Qwen）
 * 3. 冲突高亮显示
 * 4. 人工复核功能
 */

import { useState } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import {
  Card,
  Table,
  Tag,
  Button,
  Tabs,
  Progress,
  Row,
  Col,
  Tooltip,
  Empty,
  Spin,
} from 'antd';
import {
  ReloadOutlined,
  EditOutlined,
  WarningOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

import { useScreeningTask } from '../hooks/useScreeningTask';
import { useScreeningResults } from '../hooks/useScreeningResults';
import { transformToDoubleRows } from '../utils/tableTransform';
import JudgmentBadge from '../components/JudgmentBadge';
import ConclusionTag from '../components/ConclusionTag';
import DetailReviewDrawer from '../components/DetailReviewDrawer';
import type { DoubleRowData, ScreeningResult } from '../types';

const ScreeningWorkbench = () => {
  // 从路由state或URL参数获取projectId
  const location = useLocation();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const projectId = 
    (location.state as { projectId?: string })?.projectId || 
    searchParams.get('projectId') || 
    '';

  // 状态管理
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20); // 20条文献，40行数据
  const [filter, setFilter] = useState<'all' | 'conflict' | 'included' | 'excluded' | 'reviewed'>('all');
  const [selectedResult, setSelectedResult] = useState<ScreeningResult | null>(null);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]); // 展开的行

  // 使用Hooks
  const {
    task,
    progress,
    isRunning,
    isCompleted,
    isFailed,
    isLoading: taskLoading,
    refetch: refetchTask,
  } = useScreeningTask({
    projectId: projectId || '',
    enabled: !!projectId,
  });

  const {
    results,
    total,
    isLoading: resultsLoading,
    refetch: refetchResults,
    review,
    isReviewing,
  } = useScreeningResults({
    projectId: projectId || '',
    page: currentPage,
    pageSize,
    filter,
    enabled: !!projectId && isCompleted, // 只有任务完成后才查询结果
  });

  // 转换为双行表格数据
  const tableData = transformToDoubleRows(results);

  // 如果没有projectId，显示错误
  if (!projectId) {
    return (
      <div className="flex items-center justify-center h-full">
        <Empty
          description="未找到项目ID，请从设置页面启动筛选"
        />
      </div>
    );
  }

  // 处理提交复核
  const handleSubmitReview = (resultId: string, decision: 'include' | 'exclude', note?: string) => {
    review({ resultId, decision, note });
    setDrawerVisible(false);
    setSelectedResult(null);
  };

  // 处理行展开/收起
  const toggleRowExpanded = (recordKey: React.Key) => {
    setExpandedRowKeys((prevKeys) => {
      if (prevKeys.includes(recordKey)) {
        // 如果已展开，则收起
        return prevKeys.filter((key) => key !== recordKey);
      } else {
        // 如果未展开，则展开
        return [...prevKeys, recordKey];
      }
    });
  };

  // 双行表格列定义
  const columns: ColumnsType<DoubleRowData> = [
    {
      title: '#',
      dataIndex: 'literatureIndex',
      key: 'index',
      width: 60,
      align: 'center',
      onCell: (record) => ({
        rowSpan: record.isFirstRow ? 2 : 0,
      }),
      render: (value) => value,
    },
    {
      title: '文献标题',
      dataIndex: 'literatureTitle',
      key: 'title',
      width: 280,
      ellipsis: { showTitle: false },
      onCell: (record) => ({
        rowSpan: record.isFirstRow ? 2 : 0,
      }),
      render: (text: string, record) => {
        if (!record.isFirstRow) return null;
        
        const isExpanded = expandedRowKeys.includes(record.key);
        
        return (
          <Tooltip 
            title={
              <div>
                <div>{text}</div>
                <div className="text-xs text-gray-300 mt-1">
                  💡 点击标题查看AI判断证据
                </div>
              </div>
            } 
            placement="topLeft"
          >
            <div 
              className="flex items-start cursor-pointer hover:text-blue-600 transition-colors"
              onClick={() => toggleRowExpanded(record.key)}
            >
              {record.hasConflict && (
                <WarningOutlined className="text-red-500 mr-1 flex-shrink-0 mt-0.5" />
              )}
              <span className="text-sm">
                {isExpanded ? '📖 ' : '📕 '}
                {text}
              </span>
            </div>
          </Tooltip>
        );
      },
    },
    {
      title: '结论',
      dataIndex: 'conclusion',
      key: 'conclusion',
      width: 90,
      align: 'center',
      render: (value, record) => (
        <div>
          <ConclusionTag conclusion={value} />
          {record.confidence !== null && (
            <div className="text-xs text-gray-500 mt-1">
              {(record.confidence * 100).toFixed(0)}%
            </div>
          )}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 80,
      align: 'center',
      onCell: (record) => ({
        rowSpan: record.isFirstRow ? 2 : 0,
      }),
      render: (_, record) => {
        if (!record.isFirstRow) return null;
        
        const hasConflict = record.hasConflict;
        
        return (
          <Button
            size="small"
            type={hasConflict ? 'primary' : 'default'}
            icon={<EditOutlined />}
            onClick={() => {
              setSelectedResult(record.originalResult);
              setDrawerVisible(true);
            }}
          >
            复核
          </Button>
        );
      },
    },
    {
      title: '模型',
      dataIndex: 'modelName',
      key: 'model',
      width: 60,
      align: 'center',
      render: (text: string) => {
        const shortName = text === 'DeepSeek-V3' ? 'DS' : 'Qw';
        const color = text === 'DeepSeek-V3' ? 'blue' : 'purple';
        return (
          <Tooltip title={text}>
            <Tag color={color} className="cursor-help">{shortName}</Tag>
          </Tooltip>
        );
      },
    },
    {
      title: 'P',
      dataIndex: 'P',
      key: 'P',
      width: 60,
      align: 'center',
      render: (value) => <JudgmentBadge judgment={value} showIcon={false} />,
    },
    {
      title: 'I',
      dataIndex: 'I',
      key: 'I',
      width: 60,
      align: 'center',
      render: (value) => <JudgmentBadge judgment={value} showIcon={false} />,
    },
    {
      title: 'C',
      dataIndex: 'C',
      key: 'C',
      width: 60,
      align: 'center',
      render: (value) => <JudgmentBadge judgment={value} showIcon={false} />,
    },
    {
      title: 'S',
      dataIndex: 'S',
      key: 'S',
      width: 60,
      align: 'center',
      render: (value) => <JudgmentBadge judgment={value} showIcon={false} />,
    },
  ];

  // 设置行样式（冲突行高亮）
  const rowClassName = (record: DoubleRowData) => {
    if (record.hasConflict) {
      return 'bg-red-50';
    }
    return '';
  };

  // 展开行渲染：显示双模型的 PICOS 证据详情
  const expandedRowRender = (record: DoubleRowData) => {
    if (!record.isFirstRow || !record.originalResult) return null;
    
    const result = record.originalResult;
    
    return (
      <div className="p-4 bg-gray-50">
        <Row gutter={24}>
          {/* DeepSeek 证据 */}
          <Col span={12}>
            <Card 
              size="small" 
              title={
                <div className="flex items-center justify-between">
                  <span>
                    <Tag color="blue">DeepSeek-V3</Tag>
                    <ConclusionTag conclusion={result.dsConclusion} />
                  </span>
                  {result.dsConfidence !== null && (
                    <span className="text-xs text-gray-500">
                      置信度: {(result.dsConfidence * 100).toFixed(0)}%
                    </span>
                  )}
                </div>
              }
              className="h-full"
            >
              <div className="space-y-3">
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-semibold text-gray-600">P - 人群</span>
                    <JudgmentBadge judgment={result.dsPJudgment} showIcon={false} />
                  </div>
                  <p className="text-xs text-gray-700 bg-white p-2 rounded border">
                    {result.dsPEvidence || '未提供证据'}
                  </p>
                </div>
                
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-semibold text-gray-600">I - 干预</span>
                    <JudgmentBadge judgment={result.dsIJudgment} showIcon={false} />
                  </div>
                  <p className="text-xs text-gray-700 bg-white p-2 rounded border">
                    {result.dsIEvidence || '未提供证据'}
                  </p>
                </div>
                
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-semibold text-gray-600">C - 对照</span>
                    <JudgmentBadge judgment={result.dsCJudgment} showIcon={false} />
                  </div>
                  <p className="text-xs text-gray-700 bg-white p-2 rounded border">
                    {result.dsCEvidence || '未提供证据'}
                  </p>
                </div>
                
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-semibold text-gray-600">S - 研究设计</span>
                    <JudgmentBadge judgment={result.dsSJudgment} showIcon={false} />
                  </div>
                  <p className="text-xs text-gray-700 bg-white p-2 rounded border">
                    {result.dsSEvidence || '未提供证据'}
                  </p>
                </div>

                {result.dsReason && (
                  <div className="mt-3 pt-3 border-t">
                    <p className="text-xs font-semibold text-gray-600 mb-1">判断理由：</p>
                    <p className="text-xs text-gray-700 bg-blue-50 p-2 rounded">
                      {result.dsReason}
                    </p>
                  </div>
                )}
              </div>
            </Card>
          </Col>

          {/* Qwen 证据 */}
          <Col span={12}>
            <Card 
              size="small" 
              title={
                <div className="flex items-center justify-between">
                  <span>
                    <Tag color="purple">Qwen-Max</Tag>
                    <ConclusionTag conclusion={result.qwenConclusion} />
                  </span>
                  {result.qwenConfidence !== null && (
                    <span className="text-xs text-gray-500">
                      置信度: {(result.qwenConfidence * 100).toFixed(0)}%
                    </span>
                  )}
                </div>
              }
              className="h-full"
            >
              <div className="space-y-3">
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-semibold text-gray-600">P - 人群</span>
                    <JudgmentBadge judgment={result.qwenPJudgment} showIcon={false} />
                  </div>
                  <p className="text-xs text-gray-700 bg-white p-2 rounded border">
                    {result.qwenPEvidence || '未提供证据'}
                  </p>
                </div>
                
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-semibold text-gray-600">I - 干预</span>
                    <JudgmentBadge judgment={result.qwenIJudgment} showIcon={false} />
                  </div>
                  <p className="text-xs text-gray-700 bg-white p-2 rounded border">
                    {result.qwenIEvidence || '未提供证据'}
                  </p>
                </div>
                
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-semibold text-gray-600">C - 对照</span>
                    <JudgmentBadge judgment={result.qwenCJudgment} showIcon={false} />
                  </div>
                  <p className="text-xs text-gray-700 bg-white p-2 rounded border">
                    {result.qwenCEvidence || '未提供证据'}
                  </p>
                </div>
                
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-semibold text-gray-600">S - 研究设计</span>
                    <JudgmentBadge judgment={result.qwenSJudgment} showIcon={false} />
                  </div>
                  <p className="text-xs text-gray-700 bg-white p-2 rounded border">
                    {result.qwenSEvidence || '未提供证据'}
                  </p>
                </div>

                {result.qwenReason && (
                  <div className="mt-3 pt-3 border-t">
                    <p className="text-xs font-semibold text-gray-600 mb-1">判断理由：</p>
                    <p className="text-xs text-gray-700 bg-purple-50 p-2 rounded">
                      {result.qwenReason}
                    </p>
                  </div>
                )}
              </div>
            </Card>
          </Col>
        </Row>
      </div>
    );
  };

  return (
    <div className="p-6 max-w-[1800px] mx-auto">
      {/* 页面标题 */}
      <div className="mb-6 flex justify-between items-start">
        <div>
          <h2 className="text-2xl font-bold">审核工作台</h2>
          <p className="text-gray-500 mt-1">双模型筛选结果对比与人工复核</p>
        </div>
        {isCompleted && projectId && (
          <Button
            type="primary"
            icon={<BarChartOutlined />}
            onClick={() => navigate(`/literature/screening/title/results?projectId=${projectId}`)}
          >
            查看结果统计
          </Button>
        )}
      </div>

      {/* 任务进度卡片 */}
      <Card className="mb-6" loading={taskLoading}>
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <div className="mb-2">
              <span className="font-semibold mr-2">筛选进度:</span>
              {isRunning && <Tag color="processing">进行中</Tag>}
              {isCompleted && <Tag color="success">已完成</Tag>}
              {isFailed && <Tag color="error">失败</Tag>}
            </div>
            <Progress
              percent={progress}
              status={isFailed ? 'exception' : isCompleted ? 'success' : 'active'}
              strokeColor={{ '0%': '#108ee9', '100%': '#87d068' }}
            />
            {task && (
              <>
                <div className="text-sm text-gray-500 mt-2">
                  已处理: {task.processedItems} / {task.totalItems} 篇 · 
                  成功: {task.successItems} · 
                  冲突: {task.conflictItems} · 
                  失败: {task.failedItems}
                </div>
                <div className="text-xs text-gray-400 mt-1">
                  <Tag color="blue" className="text-xs">DeepSeek-V3</Tag> 
                  已处理 {task.processedItems} 篇 · 
                  <Tag color="purple" className="text-xs">Qwen-Max</Tag> 
                  已处理 {task.processedItems} 篇
                </div>
              </>
            )}
          </Col>
          <Col>
            <Button
              icon={<ReloadOutlined />}
              onClick={() => {
                refetchTask();
                refetchResults();
              }}
            >
              刷新
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 筛选Tab */}
      <Card className="mb-6">
        <Tabs 
          activeKey={filter} 
          onChange={(key) => {
            setFilter(key as any);
            setCurrentPage(1);
          }}
          items={[
            {
              key: 'all',
              label: '全部',
            },
            {
              key: 'conflict',
              label: (
                <span>
                  <WarningOutlined className="mr-1" />
                  待复核（有冲突）
                </span>
              ),
            },
            {
              key: 'included',
              label: '已纳入',
            },
            {
              key: 'excluded',
              label: '已排除',
            },
            {
              key: 'reviewed',
              label: '已复核',
            },
          ]}
        />
      </Card>

      {/* 双行表格 */}
      <Card>
        {isRunning ? (
          <div className="text-center py-12">
            <Spin size="large" />
            <div className="mt-4 text-gray-500">
              筛选任务进行中，请稍候...
            </div>
          </div>
        ) : (
          <Table<DoubleRowData>
            columns={columns}
            dataSource={tableData}
            rowKey="key"
            rowClassName={rowClassName}
            loading={resultsLoading}
            pagination={{
              current: currentPage,
              pageSize: pageSize * 2, // 每篇文献2行
              total: total * 2,
              showSizeChanger: false,
              showTotal: (total) => `共 ${Math.floor(total / 2)} 篇文献`,
              onChange: (page) => setCurrentPage(page),
            }}
            expandable={{
              expandedRowRender,
              expandedRowKeys,
              onExpandedRowsChange: (keys) => setExpandedRowKeys([...keys]),
              rowExpandable: (record) => record.isFirstRow, // 只有第一行可以展开
              expandRowByClick: false, // 不支持点击行展开，只能点击展开图标或标题
            }}
            bordered
            size="middle"
            scroll={{ x: 850 }}
          />
        )}
      </Card>

      {/* 详情与复核 Drawer */}
      <DetailReviewDrawer
        visible={drawerVisible}
        result={selectedResult}
        onClose={() => {
          setDrawerVisible(false);
          setSelectedResult(null);
        }}
        onSubmitReview={handleSubmitReview}
        isReviewing={isReviewing}
      />
    </div>
  );
};

export default ScreeningWorkbench;
