import React, { useState } from 'react';
import { Upload, message, Progress, Card } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { useKnowledgeBaseStore } from '../../stores/useKnowledgeBaseStore';

const { Dragger } = Upload;

interface DocumentUploadProps {
  kbId: string;
  onUploadSuccess: () => void;
  disabled?: boolean;
  maxDocuments?: number;
  currentDocumentCount?: number;
}

const DocumentUpload: React.FC<DocumentUploadProps> = ({
  kbId,
  onUploadSuccess,
  disabled = false,
  maxDocuments = 50,
  currentDocumentCount = 0,
}) => {
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);

  const allowedTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'text/plain',
    'text/markdown',
  ];

  const allowedExtensions = ['.pdf', '.doc', '.docx', '.txt', '.md'];

  const isAtLimit = currentDocumentCount >= maxDocuments;

  const beforeUpload = (file: File) => {
    // 检查文档数量限制
    if (isAtLimit) {
      message.error(`已达到文档数量上限（${maxDocuments}个）`);
      return Upload.LIST_IGNORE;
    }

    // 检查文件类型
    if (!allowedTypes.includes(file.type) && !allowedExtensions.some(ext => file.name.endsWith(ext))) {
      message.error(`不支持的文件类型。支持：PDF、DOC、DOCX、TXT、MD`);
      return Upload.LIST_IGNORE;
    }

    // 检查文件大小 (10MB)
    const maxSize = 10 * 1024 * 1024;
    if (file.size > maxSize) {
      message.error('文件大小不能超过 10MB');
      return Upload.LIST_IGNORE;
    }

    // 不返回任何值，让 customRequest 处理上传
  };

  const customRequest: UploadProps['customRequest'] = async (options) => {
    const { file, onSuccess, onError } = options;
    
    try {
      setUploading(true);
      setUploadProgress(0);

      // 使用 knowledgeBaseStore 的 uploadDocument 方法
      await useKnowledgeBaseStore.getState().uploadDocument(
        kbId, 
        file as File, 
        (progress) => {
          setUploadProgress(progress);
        }
      );

      message.success(`${(file as File).name} 上传成功`);
      
      if (onSuccess) {
        onSuccess('ok');
      }

      // 通知父组件刷新文档列表
      onUploadSuccess();
    } catch (error: any) {
      console.error('Upload error:', error);
      message.error(error.message || '上传失败');
      
      if (onError) {
        onError(error);
      }
    } finally {
      setUploading(false);
      setUploadProgress(0);
    }
  };

  return (
    <Card>
      <Dragger
        name="file"
        multiple={false}
        beforeUpload={beforeUpload}
        customRequest={customRequest}
        disabled={disabled || isAtLimit || uploading}
        showUploadList={false}
        style={{ marginBottom: uploading ? 16 : 0 }}
      >
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">
          {isAtLimit ? `已达到文档数量上限（${maxDocuments}个）` : '点击或拖拽文件到此区域上传'}
        </p>
        <p className="ant-upload-hint">
          支持格式：PDF、DOC、DOCX、TXT、MD | 单个文件最大10MB
        </p>
        <p className="ant-upload-hint" style={{ marginTop: 8, fontSize: 13, color: '#8c8c8c' }}>
          当前已上传: {currentDocumentCount}/{maxDocuments} 个文档
        </p>
      </Dragger>

      {uploading && (
        <div style={{ marginTop: 16 }}>
          <Progress 
            percent={uploadProgress} 
            status={uploadProgress === 100 ? 'success' : 'active'}
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
          />
          <p style={{ marginTop: 8, textAlign: 'center', color: '#595959', fontSize: 13 }}>
            {uploadProgress < 100 ? '正在上传...' : '上传完成，正在处理...'}
          </p>
        </div>
      )}
    </Card>
  );
};

export default DocumentUpload;

