/**
 * 执行环境列表组件
 * 
 * 显示和管理工作流执行环境，包括健康检查和性能统计
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect, useCallback } from 'react';
import { 
  Server, 
  CheckCircle, 
  XCircle, 
  AlertTriangle,
  RefreshCw,
  Plus,
  Settings,
  Trash2,
  Activity,
  Clock,
  Zap,
  Globe,
  Monitor,
  Cloud,
  HardDrive
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';

// 环境类型枚举
type EnvironmentType = 'local_comfyui' | 'modal_cloud' | 'runpod_cloud' | 'custom';

// 健康状态枚举
type HealthStatus = 'healthy' | 'unhealthy' | 'unknown';

// 执行环境接口
interface WorkflowExecutionEnvironment {
  id: number;
  name: string;
  environment_type: EnvironmentType;
  description?: string;
  base_url: string;
  api_key?: string;
  connection_config_json?: any;
  supported_workflow_types: string[];
  max_concurrent_jobs: number;
  priority: number;
  is_active: boolean;
  is_available: boolean;
  last_health_check?: string;
  health_status: HealthStatus;
  average_response_time_ms?: number;
  success_rate: number;
  total_executions: number;
  failed_executions: number;
  max_memory_mb?: number;
  max_execution_time_seconds?: number;
  metadata_json?: any;
  tags?: string[];
  created_at: string;
  updated_at: string;
}

// 环境筛选器接口
interface EnvironmentFilter {
  environment_type?: EnvironmentType;
  is_active?: boolean;
  is_available?: boolean;
  health_status?: HealthStatus;
}

// 组件属性接口
interface EnvironmentListProps {
  /** 环境列表 */
  environments?: WorkflowExecutionEnvironment[];
  /** 添加环境回调 */
  onAdd: () => void;
  /** 编辑环境回调 */
  onEdit: (env: WorkflowExecutionEnvironment) => void;
  /** 删除环境回调 */
  onDelete: (envId: number) => void;
  /** 健康检查回调 */
  onHealthCheck: (envId: number) => void;
  /** 切换激活状态回调 */
  onToggleActive?: (envId: number, isActive: boolean) => void;
}

/**
 * 执行环境列表组件
 */
export const EnvironmentList: React.FC<EnvironmentListProps> = ({
  environments: propEnvironments,
  onAdd,
  onEdit,
  onDelete,
  onHealthCheck,
  onToggleActive
}) => {
  const [environments, setEnvironments] = useState<WorkflowExecutionEnvironment[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState<EnvironmentFilter>({});
  const [healthCheckingIds, setHealthCheckingIds] = useState<Set<number>>(new Set());

  // 加载环境列表
  const loadEnvironments = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const result = await invoke<WorkflowExecutionEnvironment[]>('get_execution_environments', {
        filter
      });

      setEnvironments(result);
    } catch (err) {
      console.error('加载执行环境失败:', err);
      setError('加载执行环境失败');
    } finally {
      setLoading(false);
    }
  }, [filter]);

  // 初始加载
  useEffect(() => {
    if (propEnvironments) {
      setEnvironments(propEnvironments);
      setLoading(false);
    } else {
      loadEnvironments();
    }
  }, [propEnvironments, loadEnvironments]);

  // 获取环境类型图标
  const getEnvironmentTypeIcon = (type: EnvironmentType) => {
    switch (type) {
      case 'local_comfyui':
        return <Monitor className="w-5 h-5 text-blue-500" />;
      case 'modal_cloud':
        return <Cloud className="w-5 h-5 text-purple-500" />;
      case 'runpod_cloud':
        return <Globe className="w-5 h-5 text-green-500" />;
      case 'custom':
        return <Server className="w-5 h-5 text-gray-500" />;
      default:
        return <Server className="w-5 h-5 text-gray-400" />;
    }
  };

  // 获取环境类型文本
  const getEnvironmentTypeText = (type: EnvironmentType) => {
    const typeMap = {
      local_comfyui: '本地ComfyUI',
      modal_cloud: 'Modal云端',
      runpod_cloud: 'RunPod云端',
      custom: '自定义'
    };
    return typeMap[type] || '未知';
  };

  // 获取健康状态图标
  const getHealthStatusIcon = (status: HealthStatus) => {
    switch (status) {
      case 'healthy':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'unhealthy':
        return <XCircle className="w-4 h-4 text-red-500" />;
      case 'unknown':
        return <AlertTriangle className="w-4 h-4 text-yellow-500" />;
      default:
        return <AlertTriangle className="w-4 h-4 text-gray-400" />;
    }
  };

  // 获取健康状态文本
  const getHealthStatusText = (status: HealthStatus) => {
    const statusMap = {
      healthy: '健康',
      unhealthy: '异常',
      unknown: '未知'
    };
    return statusMap[status] || '未知';
  };

  // 格式化响应时间
  const formatResponseTime = (ms?: number) => {
    if (!ms) return '-';
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(1)}s`;
  };

  // 格式化成功率
  const formatSuccessRate = (rate: number) => {
    return `${(rate * 100).toFixed(1)}%`;
  };

  // 处理健康检查
  const handleHealthCheck = async (envId: number) => {
    setHealthCheckingIds(prev => new Set(prev).add(envId));
    try {
      await onHealthCheck(envId);
      // 重新加载环境列表以获取最新状态
      if (!propEnvironments) {
        await loadEnvironments();
      }
    } finally {
      setHealthCheckingIds(prev => {
        const newSet = new Set(prev);
        newSet.delete(envId);
        return newSet;
      });
    }
  };

  // 处理激活状态切换
  const handleToggleActive = async (env: WorkflowExecutionEnvironment) => {
    if (onToggleActive) {
      await onToggleActive(env.id, !env.is_active);
      // 重新加载环境列表
      if (!propEnvironments) {
        await loadEnvironments();
      }
    }
  };

  // 筛选环境
  const filteredEnvironments = environments.filter(env => {
    if (filter.environment_type && env.environment_type !== filter.environment_type) return false;
    if (filter.is_active !== undefined && env.is_active !== filter.is_active) return false;
    if (filter.is_available !== undefined && env.is_available !== filter.is_available) return false;
    if (filter.health_status && env.health_status !== filter.health_status) return false;
    return true;
  });

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <RefreshCw className="w-8 h-8 text-blue-500 animate-spin" />
        <span className="ml-2 text-gray-600">加载执行环境...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex items-center">
          <XCircle className="w-5 h-5 text-red-500 mr-2" />
          <span className="text-red-700">{error}</span>
        </div>
        <button
          onClick={loadEnvironments}
          className="mt-2 px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 transition-colors"
        >
          重试
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 筛选和操作栏 */}
      <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
        <div className="flex flex-wrap gap-4">
          {/* 环境类型筛选 */}
          <select
            value={filter.environment_type || ''}
            onChange={(e) => setFilter(prev => ({ 
              ...prev, 
              environment_type: e.target.value as EnvironmentType || undefined 
            }))}
            className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">所有类型</option>
            <option value="local_comfyui">本地ComfyUI</option>
            <option value="modal_cloud">Modal云端</option>
            <option value="runpod_cloud">RunPod云端</option>
            <option value="custom">自定义</option>
          </select>

          {/* 状态筛选 */}
          <select
            value={filter.health_status || ''}
            onChange={(e) => setFilter(prev => ({ 
              ...prev, 
              health_status: e.target.value as HealthStatus || undefined 
            }))}
            className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">所有状态</option>
            <option value="healthy">健康</option>
            <option value="unhealthy">异常</option>
            <option value="unknown">未知</option>
          </select>

          {/* 激活状态筛选 */}
          <select
            value={filter.is_active !== undefined ? filter.is_active.toString() : ''}
            onChange={(e) => setFilter(prev => ({ 
              ...prev, 
              is_active: e.target.value ? e.target.value === 'true' : undefined 
            }))}
            className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">所有环境</option>
            <option value="true">已激活</option>
            <option value="false">已禁用</option>
          </select>
        </div>

        <div className="flex items-center space-x-2">
          <button
            onClick={loadEnvironments}
            className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center space-x-2"
          >
            <RefreshCw className="w-4 h-4" />
            <span>刷新</span>
          </button>

          <button
            onClick={onAdd}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
          >
            <Plus className="w-4 h-4" />
            <span>添加环境</span>
          </button>
        </div>
      </div>

      {/* 环境列表 */}
      {filteredEnvironments.length === 0 ? (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
          <Server className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            暂无执行环境
          </h3>
          <p className="text-gray-600 mb-4">
            {Object.keys(filter).length > 0 
              ? '没有找到匹配的执行环境' 
              : '还没有配置任何执行环境'}
          </p>
          <button
            onClick={onAdd}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2 mx-auto"
          >
            <Plus className="w-4 h-4" />
            <span>添加第一个环境</span>
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {filteredEnvironments.map((env) => (
            <div
              key={env.id}
              className={`bg-white rounded-lg shadow-sm border-2 transition-all ${
                env.is_active 
                  ? env.health_status === 'healthy' 
                    ? 'border-green-200 hover:border-green-300' 
                    : 'border-yellow-200 hover:border-yellow-300'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
            >
              {/* 环境头部 */}
              <div className="p-4 border-b border-gray-200">
                <div className="flex items-start justify-between">
                  <div className="flex items-start space-x-3">
                    {getEnvironmentTypeIcon(env.environment_type)}
                    <div className="flex-1">
                      <div className="flex items-center space-x-2">
                        <h3 className="text-lg font-medium text-gray-900">
                          {env.name}
                        </h3>
                        {!env.is_active && (
                          <span className="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full">
                            已禁用
                          </span>
                        )}
                      </div>
                      <p className="text-sm text-gray-500 mt-1">
                        {getEnvironmentTypeText(env.environment_type)}
                      </p>
                      {env.description && (
                        <p className="text-sm text-gray-600 mt-1">
                          {env.description}
                        </p>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center space-x-2">
                    {/* 健康状态 */}
                    <div className="flex items-center space-x-1">
                      {getHealthStatusIcon(env.health_status)}
                      <span className="text-sm text-gray-600">
                        {getHealthStatusText(env.health_status)}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* 环境详情 */}
              <div className="p-4 space-y-4">
                {/* 性能统计 */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="flex items-center space-x-2">
                    <Activity className="w-4 h-4 text-blue-500" />
                    <div>
                      <div className="text-sm text-gray-500">响应时间</div>
                      <div className="text-sm font-medium text-gray-900">
                        {formatResponseTime(env.average_response_time_ms)}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center space-x-2">
                    <Zap className="w-4 h-4 text-green-500" />
                    <div>
                      <div className="text-sm text-gray-500">成功率</div>
                      <div className="text-sm font-medium text-gray-900">
                        {formatSuccessRate(env.success_rate)}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center space-x-2">
                    <Clock className="w-4 h-4 text-purple-500" />
                    <div>
                      <div className="text-sm text-gray-500">总执行次数</div>
                      <div className="text-sm font-medium text-gray-900">
                        {env.total_executions}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center space-x-2">
                    <HardDrive className="w-4 h-4 text-orange-500" />
                    <div>
                      <div className="text-sm text-gray-500">并发数</div>
                      <div className="text-sm font-medium text-gray-900">
                        {env.max_concurrent_jobs}
                      </div>
                    </div>
                  </div>
                </div>

                {/* 支持的工作流类型 */}
                {env.supported_workflow_types.length > 0 && (
                  <div>
                    <div className="text-sm text-gray-500 mb-2">支持的工作流类型</div>
                    <div className="flex flex-wrap gap-1">
                      {env.supported_workflow_types.map((type, index) => (
                        <span
                          key={index}
                          className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full"
                        >
                          {type}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {/* 操作按钮 */}
                <div className="flex items-center justify-between pt-2 border-t border-gray-100">
                  <div className="flex items-center space-x-2">
                    <button
                      onClick={() => handleHealthCheck(env.id)}
                      disabled={healthCheckingIds.has(env.id)}
                      className="px-3 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors flex items-center space-x-1 disabled:opacity-50"
                    >
                      <RefreshCw className={`w-3 h-3 ${healthCheckingIds.has(env.id) ? 'animate-spin' : ''}`} />
                      <span>健康检查</span>
                    </button>

                    {onToggleActive && (
                      <button
                        onClick={() => handleToggleActive(env)}
                        className={`px-3 py-1 rounded transition-colors flex items-center space-x-1 ${
                          env.is_active
                            ? 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                            : 'bg-blue-100 text-blue-700 hover:bg-blue-200'
                        }`}
                      >
                        <span>{env.is_active ? '禁用' : '启用'}</span>
                      </button>
                    )}
                  </div>

                  <div className="flex items-center space-x-2">
                    <button
                      onClick={() => onEdit(env)}
                      className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                      title="编辑"
                    >
                      <Settings className="w-4 h-4" />
                    </button>

                    <button
                      onClick={() => onDelete(env.id)}
                      className="p-1 text-gray-400 hover:text-red-600 transition-colors"
                      title="删除"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
