/**
 * Phase 2: 文献选择器（用于逐篇精读模式）
 */

import { useState } from 'react'
import { Document } from '../../types/index'
import './DocumentSelector.css'

interface DocumentSelectorProps {
  documents: Document[]
  maxSelection: number
  onConfirm: (selected: Document[]) => void
  onCancel: () => void
}

export function DocumentSelector({
  documents,
  maxSelection,
  onConfirm,
  onCancel,
}: DocumentSelectorProps) {
  const [selected, setSelected] = useState<Set<string>>(new Set())

  const toggleSelect = (docId: string) => {
    setSelected(prev => {
      const newSet = new Set(prev)
      if (newSet.has(docId)) {
        newSet.delete(docId)
      } else {
        if (newSet.size < maxSelection) {
          newSet.add(docId)
        }
      }
      return newSet
    })
  }

  const selectedDocs = documents.filter(doc => selected.has(doc.id))
  const totalTokens = selectedDocs.reduce((sum, doc) => sum + (doc.tokensCount || 0), 0)

  const handleConfirm = () => {
    if (selectedDocs.length > 0) {
      onConfirm(selectedDocs)
    }
  }

  return (
    <div className="doc-selector-overlay" onClick={onCancel}>
      <div className="doc-selector-modal" onClick={(e) => e.stopPropagation()}>
        <div className="doc-selector-header">
          <h2 className="doc-selector-title">
            📄 选择要精读的文献（最多{maxSelection}篇）
          </h2>
          <button className="doc-selector-close" onClick={onCancel}>
            ×
          </button>
        </div>

        {/* 文献列表 */}
        <div className="doc-selector-list">
          {documents.map(doc => {
            const isSelected = selected.has(doc.id)
            const isDisabled = !isSelected && selected.size >= maxSelection
            
            return (
              <div
                key={doc.id}
                className={`doc-selector-item ${isSelected ? 'selected' : ''} ${
                  isDisabled ? 'disabled' : ''
                }`}
                onClick={() => !isDisabled && toggleSelect(doc.id)}
              >
                <input
                  type="checkbox"
                  checked={isSelected}
                  readOnly
                  className="doc-checkbox"
                />
                <div className="doc-info">
                  <div className="doc-filename">{doc.filename}</div>
                  <div className="doc-meta">
                    {((doc.fileSizeBytes || 0) / 1024).toFixed(1)} KB •{' '}
                    {doc.tokensCount ? `${Math.round(doc.tokensCount / 1000)}K tokens` : '未知大小'}
                  </div>
                </div>
              </div>
            )
          })}
        </div>

        {/* 底部统计 */}
        <div className="doc-selector-footer">
          <div className="doc-selector-stats">
            <div className="stat-item">
              <span className="stat-label">已选文献：</span>
              <span className="stat-value">
                {selected.size} / {maxSelection} 篇
              </span>
            </div>
            <div className="stat-item">
              <span className="stat-label">Token总计：</span>
              <span className="stat-value">{totalTokens.toLocaleString()}</span>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="doc-selector-actions">
            <button className="btn-cancel" onClick={onCancel}>
              取消
            </button>
            <button
              className={`btn-confirm ${selected.size === 0 ? 'disabled' : ''}`}
              onClick={handleConfirm}
              disabled={selected.size === 0}
            >
              确认选择
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}






