/**
 * Phase 3: 批处理模式 - 文献选择组件
 */

import { useState, useMemo } from 'react';
import { Checkbox, Input, Button, Space } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import './DocumentSelection.css';

interface Document {
  id: string;
  filename: string;
  tokensCount?: number;
}

interface DocumentSelectionProps {
  documents: Document[];
  selectedIds: string[];
  onSelectionChange: (selectedIds: string[]) => void;
}

export function DocumentSelection({
  documents = [], // 默认空数组
  selectedIds = [], // 默认空数组
  onSelectionChange,
}: DocumentSelectionProps) {
  const [searchText, setSearchText] = useState('');

  // 过滤文档
  const filteredDocuments = useMemo(() => {
    if (!searchText.trim()) return documents;
    
    const search = searchText.toLowerCase();
    return documents.filter(doc => 
      doc.filename.toLowerCase().includes(search)
    );
  }, [documents, searchText]);

  // 全选/清空/反选
  const handleSelectAll = () => {
    onSelectionChange(filteredDocuments.map(doc => doc.id));
  };

  const handleClearAll = () => {
    onSelectionChange([]);
  };

  const handleInvert = () => {
    const allIds = new Set(documents.map(doc => doc.id));
    const selectedSet = new Set(selectedIds);
    const inverted = Array.from(allIds).filter(id => !selectedSet.has(id));
    onSelectionChange(inverted);
  };

  // 切换单个文档
  const handleToggleDocument = (docId: string) => {
    if (selectedIds.includes(docId)) {
      onSelectionChange(selectedIds.filter(id => id !== docId));
    } else {
      onSelectionChange([...selectedIds, docId]);
    }
  };

  // 格式化Token数
  const formatTokens = (tokens?: number) => {
    if (!tokens) return '';
    if (tokens > 1000) {
      return `${Math.round(tokens / 1000)}K`;
    }
    return tokens.toString();
  };

  return (
    <div className="document-selection">
      <div className="task-section-title">第2步：选择文献</div>

      {/* 统计信息 */}
      <div className="selection-summary">
        <span className="summary-text">
          已选择：<strong>{selectedIds.length}</strong> / 50 篇
        </span>
        {selectedIds.length < 3 && (
          <span className="summary-warning">（至少需要3篇）</span>
        )}
        {selectedIds.length > 50 && (
          <span className="summary-error">（最多50篇）</span>
        )}
      </div>

      {/* 操作按钮 */}
      <div className="selection-actions">
        <Space size="small">
          <Button size="small" onClick={handleSelectAll}>
            全选
          </Button>
          <Button size="small" onClick={handleClearAll}>
            清空
          </Button>
          <Button size="small" onClick={handleInvert}>
            反选
          </Button>
        </Space>
      </div>

      {/* 搜索框 */}
      <div className="selection-search">
        <Input
          placeholder="搜索文献名称..."
          prefix={<SearchOutlined />}
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          allowClear
        />
      </div>

      {/* 文档列表 */}
      <div className="document-list">
        {filteredDocuments.length === 0 ? (
          <div className="empty-list">
            {searchText ? '没有匹配的文献' : '知识库中没有文献'}
          </div>
        ) : (
          filteredDocuments.map(doc => (
            <div
              key={doc.id}
              className={`document-item ${selectedIds.includes(doc.id) ? 'selected' : ''}`}
              onClick={() => handleToggleDocument(doc.id)}
            >
              <Checkbox
                checked={selectedIds.includes(doc.id)}
                onChange={() => handleToggleDocument(doc.id)}
                onClick={(e) => e.stopPropagation()}
              />
              <div className="document-info">
                <div className="document-name">{doc.filename}</div>
                {doc.tokensCount && (
                  <div className="document-tokens">
                    {formatTokens(doc.tokensCount)} tokens
                  </div>
                )}
              </div>
            </div>
          ))
        )}
      </div>

      {/* 提示信息 */}
      {selectedIds.length > 0 && (
        <div className="selection-hint">
          💡 已选择 {selectedIds.length} 篇文献，预计处理时间约 {Math.round(selectedIds.length * 20 / 60)} 分钟
        </div>
      )}
    </div>
  );
}

