/**
 * 标题摘要初筛 - 设置与启动页面
 * 
 * 功能：
 * 1. Excel文献导入（上传 + 解析 + 去重）
 * 2. Excel模板下载
 * 3. PICOS标准配置
 * 4. 纳入/排除标准配置
 * 5. 筛选风格选择
 * 6. 启动AI筛选
 */

import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  Form,
  Input,
  Button,
  Upload,
  Radio,
  Space,
  Tooltip,
  message,
  Alert,
  Divider,
  Row,
  Col,
  Table,
  Statistic,
  Tag,
} from 'antd';
import type { UploadFile } from 'antd';
import {
  InboxOutlined,
  QuestionCircleOutlined,
  DownloadOutlined,
  PlayCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { 
  downloadExcelTemplate, 
  processExcelFile, 
  LiteratureData, 
  ParseStatistics 
} from '../utils/excelUtils';
import { aslApi } from '../api';

const { TextArea } = Input;
const { Dragger } = Upload;

const TitleScreeningSettings = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  
  // Excel上传相关状态
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [literatures, setLiteratures] = useState<LiteratureData[]>([]);
  const [parseStats, setParseStats] = useState<ParseStatistics | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [canStart, setCanStart] = useState(false);
  
  // 提交相关状态
  const [isSubmitting, setIsSubmitting] = useState(false);

  /**
   * 下载Excel模板
   */
  const handleDownloadTemplate = () => {
    try {
      downloadExcelTemplate();
      message.success('Excel模板下载成功');
    } catch (error) {
      message.error('模板下载失败');
    }
  };

  /**
   * 处理Excel文件上传
   */
  const handleFileUpload = async (file: File): Promise<boolean> => {
    try {
      setIsUploading(true);
      message.loading({ content: '正在解析Excel文件...', key: 'parsing' });
      
      // 解析Excel文件
      const { valid, statistics } = await processExcelFile(file);
      
      setLiteratures(valid);
      setParseStats(statistics);
      setFileList([{
        uid: String(Date.now()),
        name: file.name,
        status: 'done',
        originFileObj: file as any,
      }]);
      
      // 简化启动条件判断：只要有有效文献就可以启动（表单验证在提交时进行）
      setCanStart(valid.length > 0);
      
      message.success({
        content: `Excel解析成功！共 ${statistics.total} 条，有效 ${statistics.afterDedup} 条`,
        key: 'parsing',
        duration: 3,
      });
      
      // 如果有错误，显示警告
      if (statistics.invalid > 0) {
        message.warning(`有 ${statistics.invalid} 条数据验证失败，已自动过滤`, 3);
      }
      if (statistics.duplicates > 0) {
        message.info(`检测到 ${statistics.duplicates} 条重复数据，已自动去重`, 3);
      }
      
      return false; // 阻止自动上传
    } catch (error) {
      message.error({
        content: `文件解析失败: ${(error as Error).message}`,
        key: 'parsing',
      });
      return false;
    } finally {
      setIsUploading(false);
    }
  };

  /**
   * 移除上传的文件
   */
  const handleFileRemove = () => {
    setFileList([]);
    setLiteratures([]);
    setParseStats(null);
    setCanStart(false);
  };

  /**
   * 提交表单并启动筛选
   */
  const handleSubmit = async () => {
    try {
      setIsSubmitting(true);
      
      // 1. 验证表单
      const values = await form.validateFields();
      
      // 2. 检查是否已导入文献
      if (literatures.length === 0) {
        message.warning('请先导入文献');
        return;
      }
      
      message.loading({ content: '正在创建项目...', key: 'submit' });
      
      // 3. 创建项目
      const createProjectResponse = await aslApi.createProject({
        projectName: `标题摘要初筛 - ${new Date().toLocaleDateString()}`,
        picoCriteria: values.picoCriteria,
        inclusionCriteria: values.inclusionCriteria,
        exclusionCriteria: values.exclusionCriteria,
        screeningConfig: {
          style: values.screeningConfig.style,
          models: ['DeepSeek-V3', 'Qwen-Max'], // 默认双模型
        },
      });
      
      if (!createProjectResponse.success || !createProjectResponse.data) {
        const errorMsg = (createProjectResponse as any).error || '项目创建失败';
        throw new Error(errorMsg);
      }
      
      const projectId = createProjectResponse.data.id;
      
      message.loading({ content: '正在导入文献...', key: 'submit' });
      
      // 4. 导入文献
      const importResponse = await aslApi.importLiteratures({
        projectId,
        literatures: literatures.map(lit => ({
          title: lit.title,
          abstract: lit.abstract,
          publicationYear: lit.year,
          journal: lit.journal,
          authors: lit.authors,
          pmid: lit.pmid,
          doi: lit.doi,
          // 注意：后端目前只支持上述字段，key和language暂存在前端或future扩展
        })),
      });
      
      if (!importResponse.success) {
        throw new Error('文献导入失败');
      }
      
      // 5. TODO: 启动筛选任务（Week 2 Day 3-4实现）
      // await aslApi.startScreening(projectId);
      
      message.success({
        content: '项目创建成功！正在跳转到审核工作台...',
        key: 'submit',
        duration: 2,
      });
      
      // 6. 跳转到审核工作台
      setTimeout(() => {
        navigate('/literature/screening/title/workbench', {
          state: { projectId },
        });
      }, 1000);
      
    } catch (error) {
      message.error({
        content: `操作失败: ${(error as Error).message}`,
        key: 'submit',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  /**
   * 文献预览表格列定义
   * 优先级：title和abstract最宽，authors最窄
   */
  const literatureColumns = [
    {
      title: '#',
      dataIndex: 'tempId',
      key: 'index',
      width: 50,
      align: 'center' as const,
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '文献ID',
      dataIndex: 'key',
      key: 'key',
      width: 80,
      ellipsis: { showTitle: false },
      render: (text: string) => {
        const value = text || '-';
        return (
          <Tooltip title={value}>
            <span>{value}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 400,  // 增加宽度，重要信息
      ellipsis: { showTitle: false },
      render: (text: string) => (
        <Tooltip title={text} placement="topLeft">
          <span>{text}</span>
        </Tooltip>
      ),
    },
    {
      title: '年份',
      dataIndex: 'year',
      key: 'year',
      width: 60,
      align: 'center' as const,
      render: (year: number) => year || '-',
    },
    {
      title: '期刊',
      dataIndex: 'journal',
      key: 'journal',
      width: 140,  // 缩短
      ellipsis: { showTitle: false },
      render: (text: string) => {
        const value = text || '-';
        return (
          <Tooltip title={value}>
            <span>{value}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '作者',
      dataIndex: 'authors',
      key: 'authors',
      width: 120,  // 大幅缩短，最不重要的列
      ellipsis: { showTitle: false },
      render: (text: string) => {
        const value = text || '-';
        return (
          <Tooltip title={value} placement="topLeft">
            <span>{value}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '语言',
      dataIndex: 'language',
      key: 'language',
      width: 70,  // 缩短
      align: 'center' as const,
      ellipsis: { showTitle: false },
      render: (text: string) => {
        const value = text || '-';
        return (
          <Tooltip title={value}>
            <span>{value}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '摘要',
      dataIndex: 'abstract',
      key: 'abstract',
      width: 450,  // 增加宽度，重要信息
      ellipsis: { showTitle: false },
      render: (text: string) => (
        <Tooltip title={text} placement="topLeft">
          <span>{text}</span>
        </Tooltip>
      ),
    },
  ];

  return (
    <div className="p-6 max-w-7xl mx-auto">
      {/* 页面标题 */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold mb-2">标题摘要初筛 - 设置与启动</h1>
        <p className="text-gray-500">
          配置筛选标准并导入文献，然后启动AI智能初筛流程
        </p>
      </div>

      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{
          picoCriteria: {
            P: '',
            I: '',
            C: '',
            O: '',
            S: '',
          },
          inclusionCriteria: '',
          exclusionCriteria: '',
          screeningConfig: {
            style: 'standard',
          },
        }}
      >
        {/* 步骤1: 配置筛选标准 */}
        <Card title="步骤1: 配置筛选标准" className="mb-6">
          <Alert
            message="PICOS标准"
            description="系统评价研究问题的标准化框架，请详细填写每个维度"
            type="info"
            showIcon
            className="mb-4"
          />

          <Row gutter={16}>
            {/* 左侧：P + I */}
            <Col span={12}>
              <Form.Item
                label={
                  <span className="text-base font-semibold">
                    P - 人群 (Population)
                    <Tooltip title="研究对象的特征，如年龄、性别、疾病类型等">
                      <QuestionCircleOutlined className="ml-2 text-gray-400" />
                    </Tooltip>
                  </span>
                }
                name={['picoCriteria', 'P']}
                rules={[{ required: true, message: '请输入人群标准' }]}
              >
                <TextArea
                  rows={10}
                  placeholder="例如：&#10;Patients with non-cardioembolic ischemic stroke (NCIS) 非心源性缺血性卒中、亚洲人群&#10;亚组人群：&#10;1. NIHSS评分亚组卒中人群（mild/moderate stroke）&#10;..."
                  className="font-mono text-sm"
                />
              </Form.Item>

              <Form.Item
                label={
                  <span className="text-base font-semibold">
                    I - 干预 (Intervention)
                    <Tooltip title="研究的干预措施或暴露因素">
                      <QuestionCircleOutlined className="ml-2 text-gray-400" />
                    </Tooltip>
                  </span>
                }
                name={['picoCriteria', 'I']}
                rules={[{ required: true, message: '请输入干预措施' }]}
              >
                <TextArea
                  rows={5}
                  placeholder="例如：抗血小板治疗药物（阿司匹林，氯吡格雷等）、抗凝药物（华法林等）、溶栓药物（阿替普酶等）"
                  className="font-mono text-sm"
                />
              </Form.Item>
            </Col>

            {/* 右侧：C + O + S */}
            <Col span={12}>
              <Form.Item
                label={
                  <span className="text-base font-semibold">
                    C - 对照 (Comparison)
                    <Tooltip title="对照组的干预措施">
                      <QuestionCircleOutlined className="ml-2 text-gray-400" />
                    </Tooltip>
                  </span>
                }
                name={['picoCriteria', 'C']}
                rules={[{ required: true, message: '请输入对照措施' }]}
              >
                <TextArea
                  rows={5}
                  placeholder="例如：安慰剂、常规治疗、其他药物对照等"
                  className="font-mono text-sm"
                />
              </Form.Item>

              <Form.Item
                label={
                  <span className="text-base font-semibold">
                    O - 结局 (Outcome)
                    <Tooltip title="研究的主要结局指标（可选）">
                      <QuestionCircleOutlined className="ml-2 text-gray-400" />
                    </Tooltip>
                  </span>
                }
                name={['picoCriteria', 'O']}
              >
                <TextArea
                  rows={5}
                  placeholder="例如：卒中进展、卒中复发、死亡、NIHSS评分变化、疗效、安全性等"
                  className="font-mono text-sm"
                />
              </Form.Item>

              <Form.Item
                label={
                  <span className="text-base font-semibold">
                    S - 研究设计 (Study Design)
                    <Tooltip title="纳入的研究类型">
                      <QuestionCircleOutlined className="ml-2 text-gray-400" />
                    </Tooltip>
                  </span>
                }
                name={['picoCriteria', 'S']}
                rules={[{ required: true, message: '请输入研究设计' }]}
              >
                <Input
                  placeholder="例如：系统评价（SR）、随机对照试验（RCT）、真实世界研究（RWE）、观察性研究（OBS）"
                  className="font-mono text-sm"
                />
              </Form.Item>
            </Col>
          </Row>

          <Divider />

          {/* 纳入标准 & 排除标准 */}
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={
                  <span className="text-base font-semibold">
                    纳入标准
                    <Tooltip title="文献必须满足的条件才能被纳入">
                      <QuestionCircleOutlined className="ml-2 text-gray-400" />
                    </Tooltip>
                  </span>
                }
                name="inclusionCriteria"
                rules={[{ required: true, message: '请输入纳入标准' }]}
              >
                <TextArea
                  rows={10}
                  placeholder="详细的纳入标准，例如：&#10;1. 非心源性缺血性卒中、亚洲患者&#10;2. 包含二级预防相关研究&#10;3. 涉及抗血小板或抗凝药物&#10;..."
                  className="font-mono text-sm"
                />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label={
                  <span className="text-base font-semibold">
                    排除标准
                    <Tooltip title="满足这些条件的文献将被排除">
                      <QuestionCircleOutlined className="ml-2 text-gray-400" />
                    </Tooltip>
                  </span>
                }
                name="exclusionCriteria"
                rules={[{ required: true, message: '请输入排除标准' }]}
              >
                <TextArea
                  rows={10}
                  placeholder="详细的排除标准，例如：&#10;1. 心源性卒中患者、非亚洲人群&#10;2. 急性期治疗研究（无二级预防关键词）&#10;3. 病例报告、会议摘要&#10;..."
                  className="font-mono text-sm"
                />
              </Form.Item>
            </Col>
          </Row>

          <Divider />

          {/* 筛选风格 */}
          <Form.Item
            label={
              <span className="text-base font-semibold">
                筛选风格
                <Tooltip title="选择AI筛选的严格程度">
                  <QuestionCircleOutlined className="ml-2 text-gray-400" />
                </Tooltip>
              </span>
            }
            name={['screeningConfig', 'style']}
          >
            <Radio.Group>
              <Radio.Button value="lenient">
                <Space>
                  🔓 宽松模式
                  <Tooltip title="初筛推荐，宁可多纳入不错过">
                    <QuestionCircleOutlined />
                  </Tooltip>
                </Space>
              </Radio.Button>
              <Radio.Button value="standard">
                ⚖️ 标准模式（推荐）
              </Radio.Button>
              <Radio.Button value="strict">
                <Space>
                  🔒 严格模式
                  <Tooltip title="精筛推荐，保证质量">
                    <QuestionCircleOutlined />
                  </Tooltip>
                </Space>
              </Radio.Button>
            </Radio.Group>
          </Form.Item>
        </Card>

        {/* 步骤2: 导入文献 */}
        <Card title="步骤2: 导入文献" className="mb-6">
          <Alert
            message="支持Excel格式"
            description="请上传包含文献标题和摘要的Excel文件。Title和Abstract为必填字段，其他字段可选。系统会自动根据DOI和Title去重。"
            type="info"
            showIcon
            className="mb-4"
          />

          <div className="flex items-start justify-between space-x-4 mb-6">
            <div className="flex-1">
              <Dragger
                name="file"
                multiple={false}
                accept=".xlsx,.xls"
                fileList={fileList}
                beforeUpload={handleFileUpload as any}
                onRemove={handleFileRemove}
                disabled={isUploading}
              >
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">点击或拖拽Excel文件到此区域</p>
                <p className="ant-upload-hint">
                  支持 .xlsx 和 .xls 格式，单文件上传
                </p>
              </Dragger>
            </div>

            <Button
              icon={<DownloadOutlined />}
              size="large"
              onClick={handleDownloadTemplate}
              className="flex-shrink-0"
            >
              下载Excel模板
            </Button>
          </div>

          {/* 解析统计信息 */}
          {parseStats && (
            <div className="bg-gray-50 p-4 rounded-lg mb-4">
              <Row gutter={16}>
                <Col span={6}>
                  <Statistic
                    title="总数"
                    value={parseStats.total}
                    suffix="篇"
                    prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="有效"
                    value={parseStats.afterDedup}
                    suffix="篇"
                    valueStyle={{ color: '#3f8600' }}
                    prefix={<CheckCircleOutlined />}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="重复"
                    value={parseStats.duplicates}
                    suffix="篇"
                    valueStyle={{ color: '#faad14' }}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="无效"
                    value={parseStats.invalid}
                    suffix="篇"
                    valueStyle={{ color: '#cf1322' }}
                    prefix={parseStats.invalid > 0 ? <ExclamationCircleOutlined /> : undefined}
                  />
                </Col>
              </Row>

              {parseStats.invalid > 0 && parseStats.errors.length > 0 && (
                <Alert
                  message="部分数据验证失败"
                  description={
                    <div className="text-xs">
                      {parseStats.errors.map((err, idx) => (
                        <div key={idx}>• {err}</div>
                      ))}
                      {parseStats.errors.length >= 5 && (
                        <div className="mt-1 text-gray-400">...以及更多错误</div>
                      )}
                    </div>
                  }
                  type="warning"
                  showIcon
                  className="mt-4"
                />
              )}
            </div>
          )}

          {/* 文献预览表格 */}
          {literatures.length > 0 && (
            <div className="mt-4">
              <div className="flex items-center justify-between mb-3">
                <h4 className="text-base font-semibold">
                  文献预览 
                  <Tag color="blue" className="ml-2">共 {literatures.length} 篇</Tag>
                </h4>
              </div>
              <Table
                columns={literatureColumns}
                dataSource={literatures}
                rowKey="tempId"
                pagination={{
                  pageSize: 50,
                  showSizeChanger: false,
                  showTotal: (total) => `共 ${total} 篇文献`,
                }}
                size="small"
                scroll={{ x: 1370 }}
                bordered
              />
            </div>
          )}
        </Card>

        {/* 步骤3: 启动AI初筛 */}
        <Card title="步骤3: 启动AI初筛">
          <Button
            type="primary"
            size="large"
            icon={<PlayCircleOutlined />}
            htmlType="submit"
            disabled={!canStart}
            loading={isSubmitting}
            className="w-full"
          >
            {isSubmitting ? '正在创建项目并导入文献...' : '开始AI标题摘要初筛'}
          </Button>
          
          {!canStart && literatures.length === 0 && (
            <Alert
              message="请先完成以上步骤"
              description="填写PICOS标准、纳入/排除标准，并导入文献后，即可开始筛选"
              type="warning"
              showIcon
              className="mt-4"
            />
          )}
        </Card>
      </Form>
    </div>
  );
};

export default TitleScreeningSettings;
