import React from 'react';
import { Table, Tag, Button, Popconfirm, Space, Typography, Progress, Tooltip } from 'antd';
import { 
  FileTextOutlined, 
  DeleteOutlined, 
  ReloadOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import type { Document } from '../../api/knowledgeBaseApi';
import type { ColumnsType } from 'antd/es/table';

const { Text } = Typography;

interface DocumentListProps {
  documents: Document[];
  loading: boolean;
  onDelete: (doc: Document) => void;
  onReprocess: (doc: Document) => void;
}

const DocumentList: React.FC<DocumentListProps> = ({
  documents,
  loading,
  onDelete,
  onReprocess,
}) => {
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const getStatusTag = (status: Document['status']) => {
    const statusConfig = {
      uploading: { 
        color: 'blue', 
        icon: <LoadingOutlined />, 
        text: '上传中' 
      },
      parsing: { 
        color: 'processing', 
        icon: <ClockCircleOutlined />, 
        text: '解析中' 
      },
      indexing: { 
        color: 'processing', 
        icon: <ClockCircleOutlined />, 
        text: '索引中' 
      },
      completed: { 
        color: 'success', 
        icon: <CheckCircleOutlined />, 
        text: '已就绪' 
      },
      error: { 
        color: 'error', 
        icon: <CloseCircleOutlined />, 
        text: '失败' 
      },
    };

    const config = statusConfig[status] || statusConfig.uploading;

    return (
      <Tag icon={config.icon} color={config.color}>
        {config.text}
      </Tag>
    );
  };

  const columns: ColumnsType<Document> = [
    {
      title: '文件名',
      dataIndex: 'filename',
      key: 'filename',
      ellipsis: true,
      render: (filename: string) => (
        <Space>
          <FileTextOutlined style={{ color: '#1890ff' }} />
          <Text ellipsis>{filename}</Text>
        </Space>
      ),
    },
    {
      title: '文件大小',
      dataIndex: 'fileSizeBytes',
      key: 'fileSizeBytes',
      width: 120,
      render: (size: number) => formatFileSize(size),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: Document['status'], record: Document) => {
        if (status === 'error' && record.errorMessage) {
          return (
            <Tooltip title={record.errorMessage}>
              {getStatusTag(status)}
            </Tooltip>
          );
        }
        return getStatusTag(status);
      },
    },
    {
      title: '进度',
      dataIndex: 'progress',
      key: 'progress',
      width: 150,
      render: (progress: number, record: Document) => {
        if (record.status === 'completed') {
          return (
            <Space size={4}>
              <Text type="secondary" style={{ fontSize: 12 }}>
                {record.segmentsCount || 0} 段
              </Text>
              <Text type="secondary" style={{ fontSize: 12 }}>|</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>
                {record.tokensCount || 0} tokens
              </Text>
            </Space>
          );
        }
        
        if (record.status === 'error') {
          return <Text type="danger">处理失败</Text>;
        }
        
        return (
          <Progress 
            percent={progress} 
            size="small" 
            status={progress === 100 ? 'success' : 'active'}
          />
        );
      },
    },
    {
      title: '上传时间',
      dataIndex: 'uploadedAt',
      key: 'uploadedAt',
      width: 180,
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: Document) => (
        <Space size="small">
          {record.status === 'error' && (
            <Tooltip title="重新处理">
              <Button
                type="text"
                size="small"
                icon={<ReloadOutlined />}
                onClick={() => onReprocess(record)}
              >
                重试
              </Button>
            </Tooltip>
          )}
          <Popconfirm
            title="确认删除？"
            description={`删除文档 "${record.filename}"？`}
            onConfirm={() => onDelete(record)}
            okText="确认"
            cancelText="取消"
            okButtonProps={{ danger: true }}
          >
            <Button
              type="text"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Table
      columns={columns}
      dataSource={documents}
      rowKey="id"
      loading={loading}
      pagination={{
        pageSize: 10,
        showSizeChanger: true,
        showTotal: (total) => `共 ${total} 个文档`,
      }}
      locale={{
        emptyText: '暂无文档，请上传文件',
      }}
    />
  );
};

export default DocumentList;


