import React, { useState, useEffect } from 'react';
import { Activity, Database, Clock, TrendingUp, RefreshCw, Trash2 } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { DeleteConfirmDialog } from '../DeleteConfirmDialog';

interface PerformanceStats {
  template_import?: {
    avg_duration_ms: number;
    p95_duration_ms: number;
    total_imports: number;
  };
  file_upload?: {
    avg_duration_ms: number;
    p95_duration_ms: number;
    total_uploads: number;
  };
  database?: {
    avg_query_ms: number;
    p95_query_ms: number;
    total_queries: number;
  };
  memory?: {
    avg_usage_mb: number;
    max_usage_mb: number;
    current_usage_mb: number;
  };
}

interface CacheStats {
  total_items: number;
  hit_count: number;
  miss_count: number;
  hit_rate: number;
  eviction_count: number;
  memory_usage_bytes: number;
}

interface PerformanceMonitorProps {
  onClose: () => void;
}

export const PerformanceMonitor: React.FC<PerformanceMonitorProps> = ({ onClose }) => {
  const [performanceStats, setPerformanceStats] = useState<PerformanceStats>({});
  const [cacheStats, setCacheStats] = useState<CacheStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  // 加载性能数据
  const loadPerformanceData = async () => {
    try {
      setRefreshing(true);
      
      // 获取性能报告
      const perfReport = await invoke<PerformanceStats>('get_template_performance_report');
      setPerformanceStats(perfReport);
      
      // 获取缓存统计
      const cacheReport = await invoke<CacheStats>('get_cache_stats');
      setCacheStats(cacheReport);
      
    } catch (error) {
      console.error('加载性能数据失败:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // 清理性能数据
  const handleCleanupData = () => {
    setShowDeleteConfirm(true);
  };

  // 确认清理性能数据
  const confirmCleanupData = async () => {
    try {
      setDeleting(true);
      await invoke('cleanup_template_performance_data', { olderThanHours: 24 * 7 });
      await loadPerformanceData();
      setShowDeleteConfirm(false);
    } catch (error) {
      console.error('清理性能数据失败:', error);
    } finally {
      setDeleting(false);
    }
  };

  // 取消清理
  const cancelCleanupData = () => {
    setShowDeleteConfirm(false);
  };

  // 预热缓存
  const handleWarmCache = async () => {
    try {
      // 这里可以传入需要预热的模板ID列表
      await invoke('warm_template_cache', { templateIds: [] });
      await loadPerformanceData();
    } catch (error) {
      console.error('预热缓存失败:', error);
    }
  };

  useEffect(() => {
    loadPerformanceData();
    
    // 定期刷新数据
    const interval = setInterval(loadPerformanceData, 30000); // 30秒刷新一次
    
    return () => clearInterval(interval);
  }, []);

  const formatDuration = (ms: number) => {
    if (ms < 1000) {
      return `${Math.round(ms)}ms`;
    } else {
      return `${(ms / 1000).toFixed(1)}s`;
    }
  };

  const formatBytes = (bytes: number) => {
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
  };

  const formatPercentage = (value: number) => {
    return `${(value * 100).toFixed(1)}%`;
  };

  if (loading) {
    return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div className="bg-white rounded-lg shadow-xl w-full max-w-4xl mx-4 p-6">
          <div className="flex items-center justify-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <span className="ml-3 text-gray-600">加载性能数据...</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-6xl mx-4 max-h-[90vh] overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center">
            <Activity className="w-6 h-6 text-blue-600 mr-3" />
            <h2 className="text-xl font-semibold text-gray-900">性能监控</h2>
          </div>
          
          <div className="flex items-center space-x-3">
            <button
              onClick={loadPerformanceData}
              disabled={refreshing}
              className="flex items-center px-3 py-2 text-sm font-medium text-gray-600 bg-gray-50 border border-gray-200 rounded-lg hover:bg-gray-100 disabled:opacity-50 transition-colors"
            >
              <RefreshCw className={`w-4 h-4 mr-1 ${refreshing ? 'animate-spin' : ''}`} />
              刷新
            </button>
            
            <button
              onClick={handleCleanupData}
              className="flex items-center px-3 py-2 text-sm font-medium text-red-600 bg-red-50 border border-red-200 rounded-lg hover:bg-red-100 transition-colors"
            >
              <Trash2 className="w-4 h-4 mr-1" />
              清理数据
            </button>
            
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
            >
              关闭
            </button>
          </div>
        </div>

        {/* 内容 */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 模板导入性能 */}
            {performanceStats.template_import && (
              <div className="bg-gray-50 p-4 rounded-lg">
                <div className="flex items-center mb-3">
                  <Clock className="w-5 h-5 text-blue-600 mr-2" />
                  <h3 className="text-lg font-medium text-gray-900">模板导入性能</h3>
                </div>
                
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">平均耗时:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {formatDuration(performanceStats.template_import.avg_duration_ms)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">95%耗时:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {formatDuration(performanceStats.template_import.p95_duration_ms)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">总导入数:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {performanceStats.template_import.total_imports}
                    </span>
                  </div>
                </div>
              </div>
            )}

            {/* 文件上传性能 */}
            {performanceStats.file_upload && (
              <div className="bg-gray-50 p-4 rounded-lg">
                <div className="flex items-center mb-3">
                  <TrendingUp className="w-5 h-5 text-green-600 mr-2" />
                  <h3 className="text-lg font-medium text-gray-900">文件上传性能</h3>
                </div>
                
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">平均耗时:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {formatDuration(performanceStats.file_upload.avg_duration_ms)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">95%耗时:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {formatDuration(performanceStats.file_upload.p95_duration_ms)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">总上传数:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {performanceStats.file_upload.total_uploads}
                    </span>
                  </div>
                </div>
              </div>
            )}

            {/* 数据库性能 */}
            {performanceStats.database && (
              <div className="bg-gray-50 p-4 rounded-lg">
                <div className="flex items-center mb-3">
                  <Database className="w-5 h-5 text-purple-600 mr-2" />
                  <h3 className="text-lg font-medium text-gray-900">数据库性能</h3>
                </div>
                
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">平均查询:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {formatDuration(performanceStats.database.avg_query_ms)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">95%查询:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {formatDuration(performanceStats.database.p95_query_ms)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">总查询数:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {performanceStats.database.total_queries}
                    </span>
                  </div>
                </div>
              </div>
            )}

            {/* 内存使用 */}
            {performanceStats.memory && (
              <div className="bg-gray-50 p-4 rounded-lg">
                <div className="flex items-center mb-3">
                  <Activity className="w-5 h-5 text-orange-600 mr-2" />
                  <h3 className="text-lg font-medium text-gray-900">内存使用</h3>
                </div>
                
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">当前使用:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {performanceStats.memory.current_usage_mb.toFixed(1)} MB
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">平均使用:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {performanceStats.memory.avg_usage_mb.toFixed(1)} MB
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">峰值使用:</span>
                    <span className="text-sm font-medium text-gray-900">
                      {performanceStats.memory.max_usage_mb.toFixed(1)} MB
                    </span>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* 缓存统计 */}
          {cacheStats && (
            <div className="mt-6">
              <div className="bg-blue-50 p-4 rounded-lg">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center">
                    <Database className="w-5 h-5 text-blue-600 mr-2" />
                    <h3 className="text-lg font-medium text-gray-900">缓存统计</h3>
                  </div>
                  
                  <button
                    onClick={handleWarmCache}
                    className="px-3 py-1 text-xs font-medium text-blue-600 bg-blue-100 rounded-md hover:bg-blue-200 transition-colors"
                  >
                    预热缓存
                  </button>
                </div>
                
                <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                  <div className="text-center">
                    <div className="text-2xl font-bold text-blue-600">{cacheStats.total_items}</div>
                    <div className="text-xs text-gray-600">缓存项数</div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-green-600">
                      {formatPercentage(cacheStats.hit_rate)}
                    </div>
                    <div className="text-xs text-gray-600">命中率</div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-orange-600">
                      {formatBytes(cacheStats.memory_usage_bytes)}
                    </div>
                    <div className="text-xs text-gray-600">内存占用</div>
                  </div>
                  <div className="text-center">
                    <div className="text-lg font-semibold text-gray-700">{cacheStats.hit_count}</div>
                    <div className="text-xs text-gray-600">命中次数</div>
                  </div>
                  <div className="text-center">
                    <div className="text-lg font-semibold text-gray-700">{cacheStats.miss_count}</div>
                    <div className="text-xs text-gray-600">未命中次数</div>
                  </div>
                  <div className="text-center">
                    <div className="text-lg font-semibold text-gray-700">{cacheStats.eviction_count}</div>
                    <div className="text-xs text-gray-600">淘汰次数</div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      <DeleteConfirmDialog
        isOpen={showDeleteConfirm}
        title="清理性能数据"
        message="确定要清理7天前的性能数据吗？此操作不可撤销。"
        deleting={deleting}
        onConfirm={confirmCleanupData}
        onCancel={cancelCleanupData}
      />
    </div>
  );
};
