import React, { useEffect, useState } from 'react';
import { Drawer, List, Tag, Typography, Spin, Space, Pagination } from 'antd';
import { SyncOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import * as jenkinsService from '../service';
import type { JenkinsSyncHistoryDTO } from '../types';

const { Text } = Typography;

interface SyncStatusDrawerProps {
  visible: boolean;
  onClose: () => void;
}

const PAGE_SIZE = 5;

const SyncStatusDrawer: React.FC<SyncStatusDrawerProps> = ({ visible, onClose }) => {
  const [syncHistories, setSyncHistories] = useState<JenkinsSyncHistoryDTO[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);

  const fetchSyncHistories = async () => {
    try {
      const response = await jenkinsService.getSyncHistories();
      setSyncHistories(response || []);
    } catch (error) {
      console.error('获取同步历史失败:', error);
    }
  };

  useEffect(() => {
    if (visible) {
      setLoading(true);
      fetchSyncHistories().finally(() => setLoading(false));
      
      const timer = setInterval(fetchSyncHistories, 5000);
      return () => clearInterval(timer);
    }
  }, [visible]);

  const renderSyncType = (type: string) => {
    const typeMap: Record<string, string> = {
      ALL: '全量同步',
      VIEW: '视图同步',
      JOB: '作业同步',
      BUILD: '构建同步'
    };
    
    const colorMap: Record<string, string> = {
      ALL: 'blue',
      VIEW: 'green',
      JOB: 'orange',
      BUILD: 'purple'
    };
    
    return <Tag color={colorMap[type] || 'default'}>{typeMap[type] || type}</Tag>;
  };

  const renderStatus = (status: string) => {
    switch (status) {
      case 'SUCCESS':
        return <Tag icon={<CheckCircleOutlined />} color="success">成功</Tag>;
      case 'FAILED':
        return <Tag icon={<CloseCircleOutlined />} color="error">失败</Tag>;
      case 'RUNNING':
        return <Tag icon={<SyncOutlined spin />} color="processing">同步中</Tag>;
      default:
        return <Tag>未知状态</Tag>;
    }
  };

  const getCurrentPageData = () => {
    const startIndex = (currentPage - 1) * PAGE_SIZE;
    return syncHistories.slice(startIndex, startIndex + PAGE_SIZE);
  };

  return (
    <Drawer
      title="历史同步记录"
      placement="right"
      onClose={onClose}
      open={visible}
      width={600}
    >
      <Spin spinning={loading}>
        {syncHistories.length === 0 ? (
          <Text>暂无同步记录</Text>
        ) : (
          <>
            <List
              dataSource={getCurrentPageData()}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    title={
                      <Space>
                        {item.jenkinsName}
                        {renderStatus(item.status)}
                      </Space>
                    }
                    description={
                      <>
                        <div>同步类型: {renderSyncType(item.syncType)}</div>
                        <div>开始时间: {dayjs(item.startTime).format('YYYY-MM-DD HH:mm:ss')}</div>
                        {item.endTime && (
                          <div>结束时间: {dayjs(item.endTime).format('YYYY-MM-DD HH:mm:ss')}</div>
                        )}
                        {item.errorMessage && (
                          <div style={{ color: '#ff4d4f' }}>错误信息: {item.errorMessage}</div>
                        )}
                      </>
                    }
                  />
                </List.Item>
              )}
            />
            <div style={{ 
              marginTop: 16,
              padding: '10px 0',
              borderTop: '1px solid #f0f0f0',
              textAlign: 'right'
            }}>
              <Pagination
                current={currentPage}
                total={syncHistories.length}
                pageSize={PAGE_SIZE}
                onChange={setCurrentPage}
                size="small"
                showSizeChanger={false}
                showTotal={(total) => `共 ${total} 条`}
              />
            </div>
          </>
        )}
      </Spin>
    </Drawer>
  );
};

export default SyncStatusDrawer; 