/**
 * filekorolheader: 模型接入页面 - AI模型统一接入管理平台
 * 功能：模型服务注册、接入步骤说明、格式支持展示、快速接入示例、模型管理
 * 路径：/ai-crop-model/model-integration/access
 * 规范：遵循crop-x/docs/开发项目规范.md，使用useReducer状态管理，shadcn语义化样式，支持暗色主题
 */

'use client';

import { useState, useReducer } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Progress } from '@/components/ui/progress';
import { Switch } from '@/components/ui/switch';
import { copyToClipboard } from '@/lib/clipboard';
import {
  Brain,
  Plus,
  Search,
  Download,
  Upload,
  RefreshCw,
  CheckCircle,
  XCircle,
  AlertCircle,
  PlayCircle,
  PauseCircle,
  Settings,
  Eye,
  Edit,
  Trash2,
  Link,
  Cpu,
  Zap,
  Shield,
  BarChart3,
  Activity,
  Clock,
  Package,
  Server,
  Gauge,
  TrendingUp,
  Users,
  Lock,
  Unlock,
  Copy,
  GitBranch,
  Code,
  Terminal,
  RotateCw,
} from 'lucide-react';
import { toast } from 'sonner';

// 导入弹窗组件
import { ServiceConfigDialog } from './components/ServiceConfigDialog';
import { ModelDetailDialog } from './components/ModelDetailDialog';
import { VersionManageDialog } from './components/VersionManageDialog';
import { DeployConfigDialog } from './components/DeployConfigDialog';
import { ModelEditDialog } from './components/ModelEditDialog';
import { PermissionManageDialog } from './components/PermissionManageDialog';
import { DependencyManageDialog } from './components/DependencyManageDialog';
import { PerformanceTuneDialog } from './components/PerformanceTuneDialog';

// 类型定义
type ModelType = '作物生长预测' | '病虫害识别' | '产量预估' | '土壤分析' | '灌溉优化' | '其他';
type ModelFormat = 'ONNX' | 'TensorFlow' | 'PyTorch' | 'Scikit-learn' | 'H5' | 'SavedModel';
type ModelStatus = '运行中' | '已停止' | '部署中' | '故障' | '维护中';
type AccessLevel = '公开' | '私有' | '团队共享';

interface ModelService {
  id: string;
  name: string;
  version: string;
  type: ModelType;
  format: ModelFormat;
  description: string;
  author: string;
  createTime: string;
  lastUpdateTime: string;
  status: ModelStatus;
  endpoint: string;
  accessLevel: AccessLevel;
  tags: string[];
  accuracy?: number;
  inferenceTime?: number;
  requestCount: number;
  successRate: number;
  dependencies: string[];
}

interface PerformanceMetrics {
  avgResponseTime: number;
  p95ResponseTime: number;
  p99ResponseTime: number;
  qps: number;
  errorRate: number;
  cpuUsage: number;
  memoryUsage: number;
}

interface ModelState {
  modelServices: ModelService[];
  selectedModel: ModelService | null;
  showModelDialog: boolean;
  showConfigDialog: boolean;
  showDetailDialog: boolean;
  showVersionDialog: boolean;
  showDeployDialog: boolean;
  showEditDialog: boolean;
  showPermissionDialog: boolean;
  showDependencyDialog: boolean;
  showPerformanceDialog: boolean;
  performanceMetrics: PerformanceMetrics;
}

type ModelAction =
  | { type: 'SET_MODEL_SERVICES'; payload: ModelService[] }
  | { type: 'SET_SELECTED_MODEL'; payload: ModelService | null }
  | { type: 'TOGGLE_DIALOG'; payload: keyof Pick<ModelState, 'showModelDialog' | 'showConfigDialog' | 'showDetailDialog' | 'showVersionDialog' | 'showDeployDialog' | 'showEditDialog' | 'showPermissionDialog' | 'showDependencyDialog' | 'showPerformanceDialog'> }
  | { type: 'UPDATE_MODEL_STATUS'; payload: { id: string; status: ModelStatus } };

// 初始状态
const initialState: ModelState = {
  modelServices: [
    {
      id: 'model-1',
      name: '番茄生长预测模型',
      version: 'v2.3.1',
      type: '作物生长预测',
      format: 'TensorFlow',
      description: '基于深度学习的番茄生长周期预测模型，综合温湿度、光照等因素',
      author: '农业AI研究院',
      createTime: '2024-03-15',
      lastUpdateTime: '2024-10-10',
      status: '运行中',
      endpoint: 'https://api.farm-ai.com/v1/tomato-growth',
      accessLevel: '团队共享',
      tags: ['作物生长', '番茄', '深度学习'],
      accuracy: 94.5,
      inferenceTime: 120,
      requestCount: 15680,
      successRate: 99.2,
      dependencies: ['tensorflow==2.13.0', 'numpy==1.24.0', 'pandas==2.0.0'],
    },
    {
      id: 'model-2',
      name: '病虫害智能识别',
      version: 'v1.8.0',
      type: '病虫害识别',
      format: 'PyTorch',
      description: '基于卷积神经网络的作物病虫害图像识别模型，支持20+种常见病虫害',
      author: '植保技术团队',
      createTime: '2024-05-20',
      lastUpdateTime: '2024-10-12',
      status: '运行中',
      endpoint: 'https://api.farm-ai.com/v1/pest-detection',
      accessLevel: '公开',
      tags: ['病虫害', '图像识别', 'CNN'],
      accuracy: 96.8,
      inferenceTime: 85,
      requestCount: 28950,
      successRate: 98.7,
      dependencies: ['torch==2.0.1', 'torchvision==0.15.0', 'opencv-python==4.8.0'],
    },
    {
      id: 'model-3',
      name: '产量预估分析',
      version: 'v3.1.2',
      type: '产量预估',
      format: 'ONNX',
      description: '综合历史数据和实时监测的作物产量预估模型',
      author: '数据分析中心',
      createTime: '2024-01-10',
      lastUpdateTime: '2024-09-28',
      status: '运行中',
      endpoint: 'https://api.farm-ai.com/v1/yield-prediction',
      accessLevel: '私有',
      tags: ['产量预估', 'LSTM', '时间序列'],
      accuracy: 92.3,
      inferenceTime: 150,
      requestCount: 8520,
      successRate: 99.5,
      dependencies: ['onnxruntime==1.15.0', 'scikit-learn==1.3.0'],
    },
    {
      id: 'model-4',
      name: '土壤养分分析',
      version: 'v2.0.0',
      type: '土壤分析',
      format: 'Scikit-learn',
      description: '基于机器学习的土壤养分含量预测与分析模型',
      author: '土壤实验室',
      createTime: '2024-06-01',
      lastUpdateTime: '2024-10-05',
      status: '已停止',
      endpoint: 'https://api.farm-ai.com/v1/soil-analysis',
      accessLevel: '团队共享',
      tags: ['土壤分析', '机器学习'],
      accuracy: 89.7,
      inferenceTime: 95,
      requestCount: 4250,
      successRate: 97.8,
      dependencies: ['scikit-learn==1.3.0', 'xgboost==2.0.0'],
    },
  ],
  selectedModel: null,
  showModelDialog: false,
  showConfigDialog: false,
  showDetailDialog: false,
  showVersionDialog: false,
  showDeployDialog: false,
  showEditDialog: false,
  showPermissionDialog: false,
  showDependencyDialog: false,
  showPerformanceDialog: false,
  performanceMetrics: {
    avgResponseTime: 115,
    p95ResponseTime: 280,
    p99ResponseTime: 450,
    qps: 45.6,
    errorRate: 0.8,
    cpuUsage: 42.5,
    memoryUsage: 68.3,
  },
};

// Reducer
function modelReducer(state: ModelState, action: ModelAction): ModelState {
  switch (action.type) {
    case 'SET_MODEL_SERVICES':
      return { ...state, modelServices: action.payload };
    case 'SET_SELECTED_MODEL':
      return { ...state, selectedModel: action.payload };
    case 'TOGGLE_DIALOG':
      return { ...state, [action.payload]: !state[action.payload] };
    case 'UPDATE_MODEL_STATUS':
      return {
        ...state,
        modelServices: state.modelServices.map(model =>
          model.id === action.payload.id
            ? { ...model, status: action.payload.status }
            : model
        ),
      };
    default:
      return state;
  }
}

export default function ModelAccessPage() {
  const [state, dispatch] = useReducer(modelReducer, initialState);

  // 计算统计数据
  const totalModels = state.modelServices.length;
  const runningModels = state.modelServices.filter(m => m.status === '运行中').length;
  const stoppedModels = state.modelServices.filter(m => m.status === '已停止').length;
  const avgAccuracy = state.modelServices.reduce((sum, m) => sum + (m.accuracy || 0), 0) / totalModels;

  // 模型类型分布数据
  const modelTypeDistribution = [
    { name: '作物生长预测', value: 3, color: '#10b981' },
    { name: '病虫害识别', value: 2, color: '#3b82f6' },
    { name: '产量预估', value: 2, color: '#f59e0b' },
    { name: '土壤分析', value: 1, color: '#8b5cf6' },
    { name: '灌溉优化', value: 1, color: '#ec4899' },
  ];

  // 模型调用趋势数据
  const modelCallTrend = [
    { time: '10:00', 调用次数: 120, 成功率: 98.5 },
    { time: '11:00', 调用次数: 156, 成功率: 99.1 },
    { time: '12:00', 调用次数: 142, 成功率: 98.8 },
    { time: '13:00', 调用次数: 178, 成功率: 99.3 },
    { time: '14:00', 调用次数: 195, 成功率: 99.0 },
  ];

  // 工具函数
  const getStatusColor = (status: ModelStatus) => {
    switch (status) {
      case '运行中': return 'bg-success-muted text-success-muted-foreground';
      case '已停止': return 'bg-muted text-muted-foreground';
      case '部署中': return 'bg-info-muted text-info-muted-foreground';
      case '故障': return 'bg-error-muted text-error-muted-foreground';
      case '维护中': return 'bg-warning-muted text-warning-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getStatusIcon = (status: ModelStatus) => {
    switch (status) {
      case '运行中': return <PlayCircle className="w-4 h-4 text-success" />;
      case '已停止': return <PauseCircle className="w-4 h-4 text-muted-foreground" />;
      case '部署中': return <RefreshCw className="w-4 h-4 text-info animate-spin" />;
      case '故障': return <XCircle className="w-4 h-4 text-error" />;
      case '维护中': return <AlertCircle className="w-4 h-4 text-warning" />;
      default: return <AlertCircle className="w-4 h-4 text-muted-foreground" />;
    }
  };

  const getAccessLevelIcon = (level: AccessLevel) => {
    switch (level) {
      case '公开': return <Unlock className="w-4 h-4 text-green-600" />;
      case '私有': return <Lock className="w-4 h-4 text-red-600" />;
      case '团队共享': return <Users className="w-4 h-4 text-blue-600" />;
      default: return <Lock className="w-4 h-4 text-gray-600" />;
    }
  };

  // 事件处理函数
  const handleToggleDialog = (dialog: keyof Pick<ModelState, 'showModelDialog' | 'showConfigDialog' | 'showDetailDialog' | 'showVersionDialog' | 'showDeployDialog' | 'showEditDialog' | 'showPermissionDialog' | 'showDependencyDialog' | 'showPerformanceDialog'>) => {
    dispatch({ type: 'TOGGLE_DIALOG', payload: dialog });
  };

  const handleSelectModel = (model: ModelService) => {
    dispatch({ type: 'SET_SELECTED_MODEL', payload: model });
  };

  const handleStartModel = (modelName: string) => {
    toast.success(`模型"${modelName}"已启动`);
  };

  const handleStopModel = (modelName: string) => {
    toast.success(`模型"${modelName}"已停止`);
  };

  const handleTestModel = () => {
    toast.success('模型测试成功，推理正常');
  };

  const handleSaveModel = () => {
    toast.success('模型服务注册成功');
    handleToggleDialog('showModelDialog');
  };

  const handleCopyEndpoint = async (endpoint: string) => {
    const success = await copyToClipboard(endpoint);
    if (success) {
      toast.success('端点已复制到剪贴板');
    } else {
      toast.error('复制失败，请重试');
    }
  };

  const handleEditModel = (model: ModelService) => {
    handleSelectModel(model);
    handleToggleDialog('showEditDialog');
  };

  const handleViewDetail = (model: ModelService) => {
    handleSelectModel(model);
    handleToggleDialog('showDetailDialog');
  };

  const handleViewVersions = (model: ModelService) => {
    handleSelectModel(model);
    handleToggleDialog('showVersionDialog');
  };

  const handlePermissionManage = (model: ModelService) => {
    handleSelectModel(model);
    handleToggleDialog('showPermissionDialog');
  };

  const handleDependencyManage = (model: ModelService) => {
    handleSelectModel(model);
    handleToggleDialog('showDependencyDialog');
  };

  const handlePerformanceTune = (model: ModelService) => {
    handleSelectModel(model);
    handleToggleDialog('showPerformanceDialog');
  };

  const handleRedeploy = (model: ModelService) => {
    toast.success(`模型"${model.name}"重新部署已启动，预计3-5分钟完成`);
  };

  const handleConfigModel = (model: ModelService) => {
    handleSelectModel(model);
    handleToggleDialog('showConfigDialog');
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h2 className="text-3xl font-bold tracking-tight">模型接入</h2>
        <p className="text-muted-foreground mt-1">
          AI模型统一接入、管理与服务化部署平台
        </p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">模型总数</p>
              <p className="mt-2 text-3xl text-blue-600 dark:text-blue-400">{totalModels}</p>
              <p className="text-xs text-blue-600 dark:text-blue-400 mt-1">已注册模型</p>
            </div>
            <Brain className="w-12 h-12 text-blue-600 dark:text-blue-400 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">运行中</p>
              <p className="mt-2 text-3xl text-green-600 dark:text-green-400">{runningModels}</p>
              <p className="text-xs text-green-600 dark:text-green-400 mt-1">服务正常</p>
            </div>
            <PlayCircle className="w-12 h-12 text-green-600 dark:text-green-400 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">平均准确率</p>
              <p className="mt-2 text-3xl text-purple-600 dark:text-purple-400">{avgAccuracy.toFixed(1)}%</p>
              <p className="text-xs text-purple-600 dark:text-purple-400 mt-1">模型性能</p>
            </div>
            <BarChart3 className="w-12 h-12 text-purple-600 dark:text-purple-400 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">QPS</p>
              <p className="mt-2 text-3xl text-orange-600 dark:text-orange-400">{state.performanceMetrics.qps}</p>
              <p className="text-xs text-orange-600 dark:text-orange-400 mt-1">每秒请求</p>
            </div>
            <Zap className="w-12 h-12 text-orange-600 dark:text-orange-400 opacity-50" />
          </div>
        </Card>
      </div>

      {/* 功能说明卡片 */}
      <Card className="p-4 bg-gradient-to-r from-blue-50 to-purple-50 border-blue-200 dark:from-blue-950 dark:to-purple-950 dark:border-blue-800">
        <div className="flex items-start gap-2">
          <Brain className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-blue-900 dark:text-blue-100">
            <p className="mb-2">模型服务接入功能：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>标准化框架</strong>: 提供统一的模型接入标准，支持配置化注册</li>
              <li>• <strong>多种模型</strong>: 支持作物生长预测、病虫害识别、产量预估等AI模型</li>
              <li>• <strong>格式兼容</strong>: 支持ONNX、TensorFlow、PyTorch等主流框架</li>
              <li>• <strong>版本管理</strong>: 完善的模型版本控制与回滚机制</li>
              <li>• <strong>快速部署</strong>: 一键封装、部署，降低集成复杂度</li>
            </ul>
          </div>
        </div>
      </Card>

      {/* 操作按钮 */}
      <div className="flex gap-4">
        <Button
          className="bg-blue-600 hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-600"
          onClick={() => {
            dispatch({ type: 'SET_SELECTED_MODEL', payload: null });
            handleToggleDialog('showModelDialog');
          }}
        >
          <Plus className="w-4 h-4 mr-2" />
          注册新模型
        </Button>
      </div>

      {/* 接入步骤说明 */}
      <Card className="p-6">
        <h4 className="mb-4 flex items-center gap-2">
          <Code className="w-5 h-5 text-blue-600 dark:text-blue-400" />
          模型接入步骤
        </h4>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
            <div className="w-12 h-12 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center mx-auto mb-3">
              <Upload className="w-6 h-6 text-blue-600 dark:text-blue-400" />
            </div>
            <h5 className="mb-2">1. 上传模型</h5>
            <p className="text-xs text-muted-foreground">
              上传模型文件或提供模型仓库地址
            </p>
          </div>
          <div className="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
            <div className="w-12 h-12 bg-purple-100 dark:bg-purple-900 rounded-full flex items-center justify-center mx-auto mb-3">
              <Settings className="w-6 h-6 text-purple-600 dark:text-purple-400" />
            </div>
            <h5 className="mb-2">2. 配置参数</h5>
            <p className="text-xs text-muted-foreground">
              填写模型元信息、输入输出格式等
            </p>
          </div>
          <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
            <div className="w-12 h-12 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center mx-auto mb-3">
              <CheckCircle className="w-6 h-6 text-green-600 dark:text-green-400" />
            </div>
            <h5 className="mb-2">3. 验证测试</h5>
            <p className="text-xs text-muted-foreground">
              测试模型推理功能，验证输出结果
            </p>
          </div>
          <div className="text-center p-4 bg-orange-50 dark:bg-orange-950 rounded-lg">
            <div className="w-12 h-12 bg-orange-100 dark:bg-orange-900 rounded-full flex items-center justify-center mx-auto mb-3">
              <Server className="w-6 h-6 text-orange-600 dark:text-orange-400" />
            </div>
            <h5 className="mb-2">4. 服务部署</h5>
            <p className="text-xs text-muted-foreground">
              一键部署，生成API服务接口
            </p>
          </div>
        </div>
      </Card>

      {/* 模型格式支持 */}
      <Card className="p-6">
        <h4 className="mb-4 flex items-center gap-2">
          <Package className="w-5 h-5 text-purple-600 dark:text-purple-400" />
          支持的模型格式
        </h4>
        <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
          {['ONNX', 'TensorFlow', 'PyTorch', 'Scikit-learn', 'H5', 'SavedModel'].map((format) => (
            <div key={format} className="flex items-center gap-3 p-3 bg-muted dark:bg-muted rounded-lg">
              <CheckCircle className="w-5 h-5 text-green-600 dark:text-green-400" />
              <div>
                <div className="font-medium">{format}</div>
                <div className="text-xs text-muted-foreground">完全支持</div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* 快速接入示例 */}
      <Card className="p-6">
        <h4 className="mb-4 flex items-center gap-2">
          <Terminal className="w-5 h-5 text-green-600 dark:text-green-400" />
          快速接入示例
        </h4>
        <div className="bg-foreground text-green-400 p-4 rounded-lg font-mono text-sm overflow-x-auto">
          <pre>{`# 使用Python SDK快速注册模型
from farm_ai_sdk import ModelRegistry

# 1. 初始化注册器
registry = ModelRegistry(api_key="your_api_key")

# 2. 注册模型
model = registry.register(
    name="番茄生长预测模型",
    model_path="./tomato_growth_v2.onnx",
    model_type="作物生长预测",
    version="v2.3.1",
    metadata={
        "input_shape": "(batch, 10, 8)",
        "output_shape": "(batch, 1)",
        "framework": "ONNX",
    }
)

# 3. 部署模型
deployment = registry.deploy(
    model_id=model.id,
    replicas=3,
    enable_autoscaling=True
)

print(f"模型已部署: {deployment.endpoint}")`}</pre>
        </div>
      </Card>

      {/* 模型注册对话框 */}
      <Dialog open={state.showModelDialog} onOpenChange={() => handleToggleDialog('showModelDialog')}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>注册AI模型</DialogTitle>
            <DialogDescription>
              填写模型基本信息和配置参数
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>模型名称</Label>
                <Input placeholder="输入模型名称" />
              </div>
              <div>
                <Label>模型版本</Label>
                <Input placeholder="v1.0.0" />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>模型类型</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择模型类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="作物生长预测">作物生长预测</SelectItem>
                    <SelectItem value="病虫害识别">病虫害识别</SelectItem>
                    <SelectItem value="产量预估">产量预估</SelectItem>
                    <SelectItem value="土壤分析">土壤分析</SelectItem>
                    <SelectItem value="灌溉优化">灌溉优化</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>模型格式</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择模型格式" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ONNX">ONNX</SelectItem>
                    <SelectItem value="TensorFlow">TensorFlow</SelectItem>
                    <SelectItem value="PyTorch">PyTorch</SelectItem>
                    <SelectItem value="Scikit-learn">Scikit-learn</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label>模型描述</Label>
              <Textarea placeholder="描述模型的功能、适用场景等..." rows={3} />
            </div>

            <div>
              <Label>模型文件</Label>
              <div className="border-2 border-dashed rounded-lg p-6 text-center">
                <Upload className="w-8 h-8 mx-auto text-muted-foreground mb-2" />
                <p className="text-sm text-muted-foreground mb-1">
                  点击上传或拖拽模型文件到此区域
                </p>
                <p className="text-xs text-muted-foreground">
                  支持 .onnx, .h5, .pb, .pt 等格式
                </p>
              </div>
            </div>

            <div>
              <Label>依赖包</Label>
              <Textarea placeholder="每行一个依赖，如：tensorflow==2.13.0" rows={3} />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>访问权限</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择访问权限" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="公开">公开</SelectItem>
                    <SelectItem value="私有">私有</SelectItem>
                    <SelectItem value="团队共享">团队共享</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>标签</Label>
                <Input placeholder="用逗号分隔，如：深度学习,CNN" />
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => handleToggleDialog('showModelDialog')}>
              取消
            </Button>
            <Button variant="outline" onClick={handleTestModel}>
              <CheckCircle className="w-4 h-4 mr-2" />
              测试模型
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-600" onClick={handleSaveModel}>
              <Server className="w-4 h-4 mr-2" />
              注册并部署
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 所有弹窗组件 */}
      <ServiceConfigDialog
        open={state.showConfigDialog}
        onOpenChange={(open) => {
          if (!open) handleToggleDialog('showConfigDialog');
        }}
      />

      <ModelDetailDialog
        open={state.showDetailDialog}
        onOpenChange={(open) => {
          if (!open) handleToggleDialog('showDetailDialog');
        }}
        model={state.selectedModel}
      />

      <VersionManageDialog
        open={state.showVersionDialog}
        onOpenChange={(open) => {
          if (!open) handleToggleDialog('showVersionDialog');
        }}
        model={state.selectedModel}
      />

      <DeployConfigDialog
        open={state.showDeployDialog}
        onOpenChange={(open) => {
          if (!open) handleToggleDialog('showDeployDialog');
        }}
      />

      <ModelEditDialog
        open={state.showEditDialog}
        onOpenChange={(open) => {
          if (!open) handleToggleDialog('showEditDialog');
        }}
        model={state.selectedModel}
      />

      <PermissionManageDialog
        open={state.showPermissionDialog}
        onOpenChange={(open) => {
          if (!open) handleToggleDialog('showPermissionDialog');
        }}
        model={state.selectedModel}
      />

      <DependencyManageDialog
        open={state.showDependencyDialog}
        onOpenChange={(open) => {
          if (!open) handleToggleDialog('showDependencyDialog');
        }}
        model={state.selectedModel}
      />

      <PerformanceTuneDialog
        open={state.showPerformanceDialog}
        onOpenChange={(open) => {
          if (!open) handleToggleDialog('showPerformanceDialog');
        }}
        model={state.selectedModel}
        performanceMetrics={state.performanceMetrics}
      />
    </div>
  );
}