/**
 * filekorolheader: 模型配置对话框组件 - 模型编辑与查看界面
 * 功能：模型信息编辑、参数配置、查看模式、保存处理
 * 路径：/ai-crop-model/model-integration/management
 * 规范：遵循crop-x/docs/开发项目规范.md，支持编辑/查看双模式，shadcn语义化样式
 */

'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import { ModelService, ModelType, ModelStatus } from '../types';
import { Edit, Eye, Save, Copy, ExternalLink } from 'lucide-react';
import { toast } from 'sonner';

interface ModelConfigDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  model: ModelService | null;
  viewMode?: boolean;
  dispatch: React.Dispatch<any>;
}

const MODEL_TYPES: { value: ModelType; label: string; description: string }[] = [
  {
    value: 'pest_identification',
    label: '病虫害识别',
    description: '识别农作物病虫害'
  },
  {
    value: 'growth_status',
    label: '生长状态',
    description: '分析作物生长阶段'
  },
  {
    value: 'yield_prediction',
    label: '产量预测',
    description: '预测农作物产量'
  }
];

const STATUS_OPTIONS: { value: ModelStatus; label: string; color: string }[] = [
  { value: 'active', label: '运行中', color: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' },
  { value: 'inactive', label: '已停止', color: 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200' },
  { value: 'testing', label: '测试中', color: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200' },
  { value: 'error', label: '错误', color: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200' }
];

export function ModelConfigDialog({ open, onOpenChange, model, viewMode = false, dispatch }: ModelConfigDialogProps) {
  const [formData, setFormData] = useState<Partial<ModelService>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (open && model) {
      setFormData(model);
    }
  }, [open, model]);

  const handleInputChange = (field: keyof ModelService, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    toast.success('已复制到剪贴板');
  };

  const validateForm = (): boolean => {
    if (!formData.name?.trim()) {
      toast.error('请输入模型名称');
      return false;
    }

    if (!formData.description?.trim()) {
      toast.error('请输入模型描述');
      return false;
    }

    if (!formData.apiEndpoint?.trim()) {
      toast.error('请输入API端点地址');
      return false;
    }

    return true;
  };

  const handleSubmit = async () => {
    if (viewMode) return;

    if (!validateForm()) return;
    if (!model) return;

    setIsSubmitting(true);

    try {
      // 更新模型对象
      const updatedModel: ModelService = {
        ...model,
        ...formData,
        updatedAt: new Date().toISOString()
      } as ModelService;

      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000));

      // 更新模型
      dispatch({ type: 'UPDATE_MODEL', payload: updatedModel });
      dispatch({ type: 'SET_CONFIG_DIALOG', payload: false });

      toast.success('模型更新成功！');
    } catch (error) {
      toast.error('更新模型失败，请重试');
      console.error('Update model error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!model) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-center space-x-2">
            {viewMode ? (
              <Eye className="h-5 w-5 text-blue-500" />
            ) : (
              <Edit className="h-5 w-5 text-orange-500" />
            )}
            <DialogTitle>
              {viewMode ? '查看模型详情' : '编辑模型配置'}
            </DialogTitle>
          </div>
          <DialogDescription>
            {viewMode
              ? '查看模型的详细信息和配置参数'
              : '修改模型的基本信息和参数配置'
            }
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* 模型基本信息 */}
          <Card className="p-4 bg-muted/30">
            <h4 className="font-medium text-foreground mb-4">基本信息</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="name">模型名称</Label>
                <Input
                  id="name"
                  value={formData.name || ''}
                  onChange={(e) => !viewMode && handleInputChange('name', e.target.value)}
                  disabled={viewMode}
                  placeholder="模型名称"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="type">模型类型</Label>
                <Select
                  value={formData.type}
                  onValueChange={(value: ModelType) => !viewMode && handleInputChange('type', value)}
                  disabled={viewMode}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {MODEL_TYPES.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        <div className="flex flex-col items-start">
                          <span>{type.label}</span>
                          <span className="text-xs text-muted-foreground">
                            {type.description}
                          </span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="version">版本号</Label>
                <Input
                  id="version"
                  value={formData.version || ''}
                  onChange={(e) => !viewMode && handleInputChange('version', e.target.value)}
                  disabled={viewMode}
                  placeholder="例如：1.0.0"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="status">状态</Label>
                <div className="flex items-center space-x-2">
                  <Select
                    value={formData.status}
                    onValueChange={(value: ModelStatus) => !viewMode && handleInputChange('status', value)}
                    disabled={viewMode}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {STATUS_OPTIONS.map((status) => (
                        <SelectItem key={status.value} value={status.value}>
                          <Badge className={status.color}>
                            {status.label}
                          </Badge>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-2 col-span-2">
                <Label htmlFor="apiEndpoint">API端点地址</Label>
                <div className="flex space-x-2">
                  <Input
                    id="apiEndpoint"
                    value={formData.apiEndpoint || ''}
                    onChange={(e) => !viewMode && handleInputChange('apiEndpoint', e.target.value)}
                    disabled={viewMode}
                    placeholder="https://api.example.com/v1/models/..."
                    className="flex-1"
                  />
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={() => copyToClipboard(formData.apiEndpoint || '')}
                    title="复制API地址"
                  >
                    <Copy className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={() => window.open(formData.apiEndpoint, '_blank')}
                    title="访问API"
                  >
                    <ExternalLink className="h-4 w-4" />
                  </Button>
                </div>
              </div>

              <div className="space-y-2 col-span-2">
                <Label htmlFor="description">模型描述</Label>
                <Textarea
                  id="description"
                  value={formData.description || ''}
                  onChange={(e) => !viewMode && handleInputChange('description', e.target.value)}
                  disabled={viewMode}
                  placeholder="描述模型的功能、应用场景、技术特点等..."
                  rows={3}
                />
              </div>
            </div>
          </Card>

          {/* 服务配置 */}
          <Card className="p-4 bg-muted/30">
            <h4 className="font-medium text-foreground mb-4">服务配置</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="concurrency">并发数</Label>
                <Input
                  id="concurrency"
                  type="number"
                  value={formData.concurrency || ''}
                  onChange={(e) => !viewMode && handleInputChange('concurrency', e.target.value)}
                  disabled={viewMode}
                  placeholder="100"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="timeout">超时时间(ms)</Label>
                <Input
                  id="timeout"
                  type="number"
                  value={formData.timeout || ''}
                  onChange={(e) => !viewMode && handleInputChange('timeout', e.target.value)}
                  disabled={viewMode}
                  placeholder="30000"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="retryCount">重试次数</Label>
                <Input
                  id="retryCount"
                  type="number"
                  value={formData.retryCount || ''}
                  onChange={(e) => !viewMode && handleInputChange('retryCount', e.target.value)}
                  disabled={viewMode}
                  placeholder="3"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="team">所属团队</Label>
                <Input
                  id="team"
                  value={formData.team || ''}
                  onChange={(e) => !viewMode && handleInputChange('team', e.target.value)}
                  disabled={viewMode}
                  placeholder="AI算法团队"
                />
              </div>
            </div>
          </Card>

          {/* 查询参数 */}
          <Card className="p-4 bg-muted/30">
            <h4 className="font-medium text-foreground mb-4">查询参数</h4>
            <div className="space-y-3">
              {Object.entries(model.parameters).map(([key, value]) => (
                <div key={key} className="flex items-center justify-between p-3 border rounded-lg">
                  <div>
                    <div className="font-medium text-foreground">{key}</div>
                    <div className="text-sm text-muted-foreground">
                      {typeof value === 'object' ? JSON.stringify(value) : value.toString()}
                    </div>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => copyToClipboard(
                      typeof value === 'object' ? JSON.stringify(value) : value.toString()
                    )}
                  >
                    <Copy className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          </Card>

          {/* 操作日志 */}
          <Card className="p-4 bg-muted/30">
            <h4 className="font-medium text-foreground mb-4">操作</h4>
            <div className="space-y-3">
              <div className="flex items-center justify-between p-3 border rounded-lg">
                <div>
                  <div className="font-medium text-foreground">模型部署</div>
                  <div className="text-sm text-muted-foreground">2024-03-20 14:30:00 by admin</div>
                </div>
                <Badge className="bg-green-100 text-green-800">成功</Badge>
              </div>
              <div className="flex items-center justify-between p-3 border rounded-lg">
                <div>
                  <div className="font-medium text-foreground">参数更新</div>
                  <div className="text-sm text-muted-foreground">2024-03-19 10:15:00 by admin</div>
                </div>
                <Badge className="bg-blue-100 text-blue-800">配置</Badge>
              </div>
              <div className="flex items-center justify-between p-3 border rounded-lg">
                <div>
                  <div className="font-medium text-foreground">版本升级</div>
                  <div className="text-sm text-muted-foreground">2024-03-18 16:45:00 by admin</div>
                </div>
                <Badge className="bg-purple-100 text-purple-800">更新</Badge>
              </div>
              <div className="flex items-center justify-between p-3 border rounded-lg">
                <div>
                  <div className="font-medium text-foreground">模型训练</div>
                  <div className="text-sm text-muted-foreground">2024-03-15 08:00:00 by admin</div>
                </div>
                <Badge className="bg-orange-100 text-orange-800">训练</Badge>
              </div>
            </div>
          </Card>

          {/* 运行统计信息 */}
          <Card className="p-4 bg-muted/30">
            <h4 className="font-medium text-foreground mb-4">运行统计</h4>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                  {model.metrics.total_calls.toLocaleString()}
                </div>
                <div className="text-sm text-muted-foreground">总调用次数</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600 dark:text-green-400">
                  {model.metrics.accuracy.toFixed(1)}%
                </div>
                <div className="text-sm text-muted-foreground">准确率</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-orange-600 dark:text-orange-400">
                  {model.metrics.qps.toFixed(1)}
                </div>
                <div className="text-sm text-muted-foreground">QPS</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-purple-600 dark:text-purple-400">
                  {model.metrics.success_rate}%
                </div>
                <div className="text-sm text-muted-foreground">成功率</div>
              </div>
            </div>
          </Card>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            {viewMode ? '关闭' : '取消'}
          </Button>
          {!viewMode && (
            <Button onClick={handleSubmit} disabled={isSubmitting}>
              {isSubmitting ? '保存中...' : (
                <>
                  <Save className="h-4 w-4 mr-2" />
                  保存更改
                </>
              )}
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}