/**
 * 文献详情与复核 Drawer（统一组件）
 * 
 * 布局：
 * - 左侧（70%）：文献信息 + 双模型详细对比
 * - 右侧（30%）：人工复核区域（固定，一眼可见）
 */

import { useState } from 'react';
import { 
  Drawer, 
  Row, 
  Col, 
  Descriptions, 
  Card,
  Tag, 
  Typography, 
  Alert,
  Radio,
  Input,
  Button,
  Space,
  Divider,
} from 'antd';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import JudgmentBadge from './JudgmentBadge';
import ConclusionTag from './ConclusionTag';
import type { ScreeningResult } from '../types';

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

interface DetailReviewDrawerProps {
  visible: boolean;
  result: ScreeningResult | null;
  onClose: () => void;
  onSubmitReview: (resultId: string, decision: 'include' | 'exclude', note?: string) => void;
  isReviewing?: boolean;
}

const DetailReviewDrawer: React.FC<DetailReviewDrawerProps> = ({
  visible,
  result,
  onClose,
  onSubmitReview,
  isReviewing = false,
}) => {
  const [decision, setDecision] = useState<'include' | 'exclude' | null>(null);
  const [note, setNote] = useState('');

  if (!result) return null;

  const hasConflict = result.conflictStatus === 'conflict';
  const alreadyReviewed = !!result.finalDecision;

  const handleSubmit = () => {
    if (!decision) return;
    onSubmitReview(result.id, decision, note);
    // 清空表单
    setDecision(null);
    setNote('');
  };

  const handleClose = () => {
    setDecision(null);
    setNote('');
    onClose();
  };

  return (
    <Drawer
      title="文献详情与复核"
      width={1000}
      open={visible}
      onClose={handleClose}
      destroyOnClose
    >
      <Row gutter={24}>
        {/* 左侧：详情区域 (70%) */}
        <Col span={17}>
          {/* 文献基本信息 */}
          <Card size="small" className="mb-4">
            <Title level={5}>文献信息</Title>
            <Descriptions bordered size="small" column={2}>
              <Descriptions.Item label="标题" span={2}>
                <Text strong>{result.literature.title}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="作者">
                {result.literature.authors || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="期刊">
                {result.literature.journal || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="年份">
                {result.literature.publicationYear || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="PMID">
                {result.literature.pmid || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="摘要" span={2}>
                <Paragraph 
                  ellipsis={{ rows: 3, expandable: true, symbol: '展开' }}
                  className="mb-0"
                >
                  {result.literature.abstract}
                </Paragraph>
              </Descriptions.Item>
            </Descriptions>
          </Card>

          {/* AI判断对比 */}
          <Title level={5}>AI判断对比</Title>
          
          {/* DeepSeek */}
          <Card 
            size="small" 
            className="mb-3"
            style={{ borderLeft: '3px solid #1890ff' }}
          >
            <div className="flex items-center justify-between mb-3">
              <Space>
                <Tag color="blue">DeepSeek-V3</Tag>
                <ConclusionTag conclusion={result.dsConclusion} />
              </Space>
              {result.dsConfidence !== null && (
                <Text type="secondary">
                  置信度: {(result.dsConfidence * 100).toFixed(0)}%
                </Text>
              )}
            </div>

            <Descriptions bordered size="small" column={2}>
              <Descriptions.Item label="P-人群">
                <JudgmentBadge judgment={result.dsPJudgment} showIcon={false} />
              </Descriptions.Item>
              <Descriptions.Item label="证据">
                <Text className="text-xs">{result.dsPEvidence || '-'}</Text>
              </Descriptions.Item>

              <Descriptions.Item label="I-干预">
                <JudgmentBadge judgment={result.dsIJudgment} showIcon={false} />
              </Descriptions.Item>
              <Descriptions.Item label="证据">
                <Text className="text-xs">{result.dsIEvidence || '-'}</Text>
              </Descriptions.Item>

              <Descriptions.Item label="C-对照">
                <JudgmentBadge judgment={result.dsCJudgment} showIcon={false} />
              </Descriptions.Item>
              <Descriptions.Item label="证据">
                <Text className="text-xs">{result.dsCEvidence || '-'}</Text>
              </Descriptions.Item>

              <Descriptions.Item label="S-研究设计">
                <JudgmentBadge judgment={result.dsSJudgment} showIcon={false} />
              </Descriptions.Item>
              <Descriptions.Item label="证据">
                <Text className="text-xs">{result.dsSEvidence || '-'}</Text>
              </Descriptions.Item>
            </Descriptions>

            {result.dsReason && (
              <div className="mt-3 p-2 bg-blue-50 rounded">
                <Text strong className="text-sm">判断理由:</Text>
                <Paragraph className="mt-1 mb-0 text-sm whitespace-pre-wrap">
                  {result.dsReason}
                </Paragraph>
              </div>
            )}
          </Card>

          {/* Qwen */}
          <Card 
            size="small"
            style={{ borderLeft: '3px solid #722ed1' }}
          >
            <div className="flex items-center justify-between mb-3">
              <Space>
                <Tag color="purple">Qwen-Max</Tag>
                <ConclusionTag conclusion={result.qwenConclusion} />
              </Space>
              {result.qwenConfidence !== null && (
                <Text type="secondary">
                  置信度: {(result.qwenConfidence * 100).toFixed(0)}%
                </Text>
              )}
            </div>

            <Descriptions bordered size="small" column={2}>
              <Descriptions.Item label="P-人群">
                <JudgmentBadge judgment={result.qwenPJudgment} showIcon={false} />
              </Descriptions.Item>
              <Descriptions.Item label="证据">
                <Text className="text-xs">{result.qwenPEvidence || '-'}</Text>
              </Descriptions.Item>

              <Descriptions.Item label="I-干预">
                <JudgmentBadge judgment={result.qwenIJudgment} showIcon={false} />
              </Descriptions.Item>
              <Descriptions.Item label="证据">
                <Text className="text-xs">{result.qwenIEvidence || '-'}</Text>
              </Descriptions.Item>

              <Descriptions.Item label="C-对照">
                <JudgmentBadge judgment={result.qwenCJudgment} showIcon={false} />
              </Descriptions.Item>
              <Descriptions.Item label="证据">
                <Text className="text-xs">{result.qwenCEvidence || '-'}</Text>
              </Descriptions.Item>

              <Descriptions.Item label="S-研究设计">
                <JudgmentBadge judgment={result.qwenSJudgment} showIcon={false} />
              </Descriptions.Item>
              <Descriptions.Item label="证据">
                <Text className="text-xs">{result.qwenSEvidence || '-'}</Text>
              </Descriptions.Item>
            </Descriptions>

            {result.qwenReason && (
              <div className="mt-3 p-2 bg-purple-50 rounded">
                <Text strong className="text-sm">判断理由:</Text>
                <Paragraph className="mt-1 mb-0 text-sm whitespace-pre-wrap">
                  {result.qwenReason}
                </Paragraph>
              </div>
            )}
          </Card>
        </Col>

        {/* 右侧：人工复核区域 (30%) */}
        <Col span={7}>
          <div 
            className="sticky top-0"
            style={{ 
              border: '1px solid #d9d9d9', 
              borderRadius: '4px',
              padding: '16px',
              backgroundColor: '#fafafa',
            }}
          >
            <Title level={5} className="mt-0">
              👉 人工复核
            </Title>

            {/* 冲突提示 */}
            {hasConflict && (
              <Alert
                message="检测到冲突"
                description="两个模型的结论不一致，建议仔细查看详情后做出决策。"
                type="warning"
                icon={<WarningOutlined />}
                showIcon
                className="mb-4"
              />
            )}

            {/* 已复核提示 */}
            {alreadyReviewed && (
              <Alert
                message="已复核"
                description={
                  <div>
                    <div>决策: <ConclusionTag conclusion={result.finalDecision} /></div>
                    {result.exclusionReason && (
                      <div className="mt-2">备注: {result.exclusionReason}</div>
                    )}
                    <div className="mt-2 text-xs text-gray-500">
                      {result.finalDecisionBy} · {result.finalDecisionAt}
                    </div>
                  </div>
                }
                type="success"
                showIcon
                className="mb-4"
              />
            )}

            <Divider className="my-4" />

            {/* 决策选择 */}
            <div className="mb-4">
              <Text strong>您的决策：</Text>
              <Radio.Group
                value={decision}
                onChange={(e) => setDecision(e.target.value)}
                className="mt-2 w-full"
              >
                <Space direction="vertical" className="w-full">
                  <Radio value="include" className="w-full">
                    <CheckCircleOutlined className="text-green-600 mr-1" />
                    纳入
                  </Radio>
                  <Radio value="exclude" className="w-full">
                    <CloseCircleOutlined className="text-gray-600 mr-1" />
                    排除
                  </Radio>
                </Space>
              </Radio.Group>
            </div>

            {/* 备注 */}
            <div className="mb-4">
              <Text strong>备注（可选）：</Text>
              <TextArea
                rows={4}
                placeholder="请输入复核备注，例如排除原因、特殊说明等..."
                value={note}
                onChange={(e) => setNote(e.target.value)}
                className="mt-2"
              />
            </div>

            {/* 操作按钮 */}
            <Space direction="vertical" className="w-full">
              <Button
                type="primary"
                block
                size="large"
                disabled={!decision}
                loading={isReviewing}
                onClick={handleSubmit}
              >
                提交复核
              </Button>
              <Button
                block
                onClick={handleClose}
              >
                关闭
              </Button>
            </Space>

            {/* AI对比摘要 */}
            <Divider className="my-4" />
            <Card size="small" className="bg-white">
              <Text strong className="text-xs">AI判断摘要：</Text>
              <div className="mt-2 text-xs">
                <div className="flex justify-between mb-1">
                  <span>DeepSeek:</span>
                  <ConclusionTag 
                    conclusion={result.dsConclusion} 
                    size="small" 
                  />
                </div>
                <div className="flex justify-between">
                  <span>Qwen:</span>
                  <ConclusionTag 
                    conclusion={result.qwenConclusion} 
                    size="small" 
                  />
                </div>
              </div>
            </Card>
          </div>
        </Col>
      </Row>
    </Drawer>
  );
};

export default DetailReviewDrawer;



