/**
 * Phase 3: 批处理模式 - 主组件
 */

import { useEffect, useState } from 'react';
import { Button, message as antdMessage } from 'antd';
import { RocketOutlined } from '@ant-design/icons';
import { TaskDefinition } from './TaskDefinition';
import { DocumentSelection } from './DocumentSelection';
import { BatchProgress } from './BatchProgress';
import { BatchResults } from './BatchResults';
import { useBatchTask } from '../../hooks/useBatchTask';
import { documentApi, type Document } from '../../api/knowledgeBaseApi';
import './BatchMode.css';

interface BatchModeProps {
  kbId: string;
  modelType: string;
}

export function BatchMode({ kbId, modelType }: BatchModeProps) {
  const [documents, setDocuments] = useState<Document[]>([]);

  const {
    state,
    loadTemplates,
    selectTemplate,
    setCustomPrompt,
    setSelectedDocuments,
    executeBatch,
    retryFailed,
    reset,
  } = useBatchTask();

  // 加载模板和文档列表
  useEffect(() => {
    loadTemplates();
    loadDocuments();
  }, [kbId]);

  // 加载知识库文档列表
  const loadDocuments = async () => {
    try {
      const docs = await documentApi.getList(kbId);
      setDocuments(docs);
    } catch (error: any) {
      antdMessage.error(`加载文献列表失败: ${error.message}`);
    }
  };

  // 开始批处理
  const handleStartBatch = async () => {
    if (state.selectedDocuments.length < 3) {
      antdMessage.warning('请至少选择3篇文献');
      return;
    }

    if (state.selectedDocuments.length > 50) {
      antdMessage.warning('最多只能选择50篇文献');
      return;
    }

    await executeBatch({
      kbId,
      modelType,
      taskName: state.selectedTemplate 
        ? `${state.selectedTemplate.name}_${new Date().toLocaleString('zh-CN')}`
        : `自定义任务_${new Date().toLocaleString('zh-CN')}`,
    });
  };

  return (
    <div className="batch-mode">
      {/* 步骤1：任务定义 */}
      <div className="batch-section">
        <div className="section-header">
          <span className="section-number">1</span>
          <span className="section-title">定义任务</span>
        </div>
        <TaskDefinition
          templates={state.templates}
          selectedTemplate={state.selectedTemplate}
          customPrompt={state.customPrompt}
          onSelectTemplate={selectTemplate}
          onCustomPromptChange={setCustomPrompt}
        />
      </div>

      {/* 步骤2：选择文献 */}
      <div className="batch-section">
        <div className="section-header">
          <span className="section-number">2</span>
          <span className="section-title">选择文献</span>
        </div>
        <DocumentSelection
          documents={documents}
          selectedIds={state.selectedDocuments}
          onSelectionChange={setSelectedDocuments}
        />
      </div>

      {/* 步骤3：开始按钮 */}
      {state.step === 'define' && (
        <div className="batch-section">
          <Button
            type="primary"
            size="large"
            icon={<RocketOutlined />}
            onClick={handleStartBatch}
            disabled={state.selectedDocuments.length < 3 || state.selectedDocuments.length > 50}
            loading={state.isExecuting}
            block
            style={{ height: '56px', fontSize: '18px' }}
          >
            🚀 开始批处理 ({state.selectedDocuments.length} 篇文献)
          </Button>
        </div>
      )}

      {/* 步骤3：执行进度 */}
      {state.step === 'executing' && state.currentTask && (
        <div className="batch-section">
          <div className="section-header">
            <span className="section-number">3</span>
            <span className="section-title">执行中...</span>
          </div>
          <BatchProgress task={state.currentTask} />
        </div>
      )}

      {/* 步骤4：结果展示 */}
      {state.step === 'results' && state.currentTask && (
        <div className="batch-section">
          <div className="section-header">
            <span className="section-number">4</span>
            <span className="section-title">结果展示</span>
          </div>
          <BatchResults
            task={state.currentTask}
            results={state.taskResults}
            template={state.selectedTemplate}
            onRetryFailed={retryFailed}
            onReset={reset}
          />
        </div>
      )}
    </div>
  );
}

