/**
 * filekorolheader: 性能调优对话框组件 - 模型性能参数优化
 * 功能：当前性能指标、负载均衡策略、缓存优化配置
 * 路径：/ai-crop-model/model-integration/management
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式
 */

'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  Zap,
  Activity,
  Server,
  Database,
  Gauge,
  TrendingUp,
  Settings
} from 'lucide-react';
import { toast } from 'sonner';

interface PerformanceDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  model: any;
}

export function PerformanceDialog({ open, onOpenChange, model }: PerformanceDialogProps) {
  const [performanceSettings, setPerformanceSettings] = useState({
    // 基础性能配置
    concurrency: model?.concurrency || 100,
    timeout: model?.timeout || 30000,
    retryCount: model?.retryCount || 3,

    // 负载均衡策略
    loadBalancing: {
      strategy: 'round_robin',
      healthCheck: true,
      healthCheckInterval: 30,
      failoverEnabled: true,
      maxFailures: 3
    },

    // 缓存配置
    caching: {
      enabled: true,
      ttl: 300,
      maxSize: 1000,
      strategy: 'lru'
    },

    // 资源限制
    resources: {
      maxMemory: '2GB',
      maxCpu: '50%',
      maxGpu: '1'
    }
  });

  const handleBasicSettingChange = (field: string, value: any) => {
    setPerformanceSettings(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleLoadBalancingChange = (field: string, value: any) => {
    setPerformanceSettings(prev => ({
      ...prev,
      loadBalancing: {
        ...prev.loadBalancing,
        [field]: value
      }
    }));
  };

  const handleCachingChange = (field: string, value: any) => {
    setPerformanceSettings(prev => ({
      ...prev,
      caching: {
        ...prev.caching,
        [field]: value
      }
    }));
  };

  const handleResourcesChange = (field: string, value: any) => {
    setPerformanceSettings(prev => ({
      ...prev,
      resources: {
        ...prev.resources,
        [field]: value
      }
    }));
  };

  const savePerformanceSettings = () => {
    toast.success('性能配置已保存');
    onOpenChange(false);
  };

  // 模拟当前性能指标
  const currentMetrics = {
    cpuUsage: 65,
    memoryUsage: 78,
    gpuUsage: 45,
    avgResponseTime: model?.metrics?.avg_response_time || 245,
    qps: model?.metrics?.qps || 12.5,
    cacheHitRate: 82,
    errorRate: 1.5
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>性能调优</DialogTitle>
          <DialogDescription>
            优化模型 <strong>{model?.name}</strong> 的性能参数和资源配置
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* 当前性能指标 */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Gauge className="w-5 h-5 text-blue-600" />
              <Label className="text-base font-medium">当前性能指标</Label>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <Card className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <Activity className="w-4 h-4 text-blue-600" />
                  <span className="text-sm font-medium">CPU使用率</span>
                </div>
                <div className="text-2xl font-bold">{currentMetrics.cpuUsage}%</div>
                <Progress value={currentMetrics.cpuUsage} className="mt-2" />
              </Card>

              <Card className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <Database className="w-4 h-4 text-green-600" />
                  <span className="text-sm font-medium">内存使用率</span>
                </div>
                <div className="text-2xl font-bold">{currentMetrics.memoryUsage}%</div>
                <Progress value={currentMetrics.memoryUsage} className="mt-2" />
              </Card>

              <Card className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <Zap className="w-4 h-4 text-purple-600" />
                  <span className="text-sm font-medium">响应时间</span>
                </div>
                <div className="text-2xl font-bold">{currentMetrics.avgResponseTime}ms</div>
                <Badge
                  className={
                    currentMetrics.avgResponseTime < 200
                      ? 'bg-green-100 text-green-800'
                      : currentMetrics.avgResponseTime < 500
                      ? 'bg-yellow-100 text-yellow-800'
                      : 'bg-red-100 text-red-800'
                  }
                >
                  {currentMetrics.avgResponseTime < 200 ? '优秀' : currentMetrics.avgResponseTime < 500 ? '良好' : '需优化'}
                </Badge>
              </Card>

              <Card className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <TrendingUp className="w-4 h-4 text-orange-600" />
                  <span className="text-sm font-medium">QPS</span>
                </div>
                <div className="text-2xl font-bold">{currentMetrics.qps}</div>
                <Badge className="bg-blue-100 text-blue-800">
                  当前
                </Badge>
              </Card>
            </div>
          </div>

          {/* 基础性能配置 */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Settings className="w-5 h-5 text-green-600" />
              <Label className="text-base font-medium">基础性能配置</Label>
            </div>
            <div className="grid grid-cols-3 gap-4 p-4 border rounded-lg">
              <div className="space-y-2">
                <Label>并发数</Label>
                <Input
                  type="number"
                  value={performanceSettings.concurrency}
                  onChange={(e) => handleBasicSettingChange('concurrency', parseInt(e.target.value) || 0)}
                />
              </div>
              <div className="space-y-2">
                <Label>超时时间 (ms)</Label>
                <Input
                  type="number"
                  value={performanceSettings.timeout}
                  onChange={(e) => handleBasicSettingChange('timeout', parseInt(e.target.value) || 0)}
                />
              </div>
              <div className="space-y-2">
                <Label>重试次数</Label>
                <Input
                  type="number"
                  value={performanceSettings.retryCount}
                  onChange={(e) => handleBasicSettingChange('retryCount', parseInt(e.target.value) || 0)}
                />
              </div>
            </div>
          </div>

          {/* 负载均衡策略 */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Server className="w-5 h-5 text-orange-600" />
              <Label className="text-base font-medium">负载均衡策略</Label>
            </div>
            <Card className="p-4">
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>负载均衡算法</Label>
                    <Select
                      value={performanceSettings.loadBalancing.strategy}
                      onValueChange={(value) => handleLoadBalancingChange('strategy', value)}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="round_robin">轮询 (Round Robin)</SelectItem>
                        <SelectItem value="least_connections">最少连接 (Least Connections)</SelectItem>
                        <SelectItem value="weighted_round_robin">加权轮询 (Weighted Round Robin)</SelectItem>
                        <SelectItem value="random">随机 (Random)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label>健康检查间隔 (秒)</Label>
                    <Input
                      type="number"
                      value={performanceSettings.loadBalancing.healthCheckInterval}
                      onChange={(e) => handleLoadBalancingChange('healthCheckInterval', parseInt(e.target.value) || 0)}
                      disabled={!performanceSettings.loadBalancing.healthCheck}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="flex items-center justify-between p-3 border rounded-lg">
                    <div>
                      <div className="font-medium">启用健康检查</div>
                      <div className="text-sm text-muted-foreground">
                        定期检查服务健康状态
                      </div>
                    </div>
                    <Switch
                      checked={performanceSettings.loadBalancing.healthCheck}
                      onCheckedChange={(checked) => handleLoadBalancingChange('healthCheck', checked)}
                    />
                  </div>

                  <div className="flex items-center justify-between p-3 border rounded-lg">
                    <div>
                      <div className="font-medium">启用故障转移</div>
                      <div className="text-sm text-muted-foreground">
                        服务失败时自动切换
                      </div>
                    </div>
                    <Switch
                      checked={performanceSettings.loadBalancing.failoverEnabled}
                      onCheckedChange={(checked) => handleLoadBalancingChange('failoverEnabled', checked)}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label>最大失败次数</Label>
                  <Input
                    type="number"
                    value={performanceSettings.loadBalancing.maxFailures}
                    onChange={(e) => handleLoadBalancingChange('maxFailures', parseInt(e.target.value) || 0)}
                    disabled={!performanceSettings.loadBalancing.failoverEnabled}
                  />
                </div>
              </div>
            </Card>
          </div>

          {/* 缓存优化 */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Database className="w-5 h-5 text-purple-600" />
              <Label className="text-base font-medium">缓存优化</Label>
            </div>
            <Card className="p-4">
              <div className="space-y-4">
                <div className="flex items-center justify-between p-3 border rounded-lg">
                  <div>
                    <div className="font-medium">启用缓存</div>
                    <div className="text-sm text-muted-foreground">
                      缓存频繁请求的结果以提高响应速度
                    </div>
                  </div>
                  <Switch
                    checked={performanceSettings.caching.enabled}
                    onCheckedChange={(checked) => handleCachingChange('enabled', checked)}
                  />
                </div>

                {performanceSettings.caching.enabled && (
                  <div className="grid grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <Label>缓存时间 (秒)</Label>
                      <Input
                        type="number"
                        value={performanceSettings.caching.ttl}
                        onChange={(e) => handleCachingChange('ttl', parseInt(e.target.value) || 0)}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>最大缓存条目</Label>
                      <Input
                        type="number"
                        value={performanceSettings.caching.maxSize}
                        onChange={(e) => handleCachingChange('maxSize', parseInt(e.target.value) || 0)}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>缓存策略</Label>
                      <Select
                        value={performanceSettings.caching.strategy}
                        onValueChange={(value) => handleCachingChange('strategy', value)}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="lru">最近最少使用 (LRU)</SelectItem>
                          <SelectItem value="lfu">最少使用频率 (LFU)</SelectItem>
                          <SelectItem value="fifo">先进先出 (FIFO)</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                )}

                <div className="grid grid-cols-3 gap-4">
                  <Card className="p-3">
                    <div className="text-sm text-muted-foreground">当前缓存命中率</div>
                    <div className="text-lg font-bold text-green-600">{currentMetrics.cacheHitRate}%</div>
                  </Card>
                  <Card className="p-3">
                    <div className="text-sm text-muted-foreground">当前错误率</div>
                    <div className="text-lg font-bold text-red-600">{currentMetrics.errorRate}%</div>
                  </Card>
                  <Card className="p-3">
                    <div className="text-sm text-muted-foreground">GPU使用率</div>
                    <div className="text-lg font-bold text-purple-600">{currentMetrics.gpuUsage}%</div>
                  </Card>
                </div>
              </div>
            </Card>
          </div>

          {/* 资源限制 */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Activity className="w-5 h-5 text-red-600" />
              <Label className="text-base font-medium">资源限制</Label>
            </div>
            <div className="grid grid-cols-3 gap-4 p-4 border rounded-lg">
              <div className="space-y-2">
                <Label>最大内存</Label>
                <Select
                  value={performanceSettings.resources.maxMemory}
                  onValueChange={(value) => handleResourcesChange('maxMemory', value)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="1GB">1GB</SelectItem>
                    <SelectItem value="2GB">2GB</SelectItem>
                    <SelectItem value="4GB">4GB</SelectItem>
                    <SelectItem value="8GB">8GB</SelectItem>
                    <SelectItem value="16GB">16GB</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>最大CPU</Label>
                <Select
                  value={performanceSettings.resources.maxCpu}
                  onValueChange={(value) => handleResourcesChange('maxCpu', value)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="25%">25%</SelectItem>
                    <SelectItem value="50%">50%</SelectItem>
                    <SelectItem value="75%">75%</SelectItem>
                    <SelectItem value="100%">100%</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>最大GPU</Label>
                <Select
                  value={performanceSettings.resources.maxGpu}
                  onValueChange={(value) => handleResourcesChange('maxGpu', value)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="0">不使用</SelectItem>
                    <SelectItem value="1">1个</SelectItem>
                    <SelectItem value="2">2个</SelectItem>
                    <SelectItem value="4">4个</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={savePerformanceSettings}>
            保存配置
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}