/**
 * filekorolheader: 模型注册对话框组件 - 新增AI模型注册
 * 功能：模型基本信息填写、文件上传、权限配置、依赖管理
 * 路径：/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 { 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 { Upload, Save } from 'lucide-react';
import { toast } from 'sonner';

interface AddModelDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  dispatch: React.Dispatch<any>;
}

export function AddModelDialog({ open, onOpenChange, dispatch }: AddModelDialogProps) {
  const [formData, setFormData] = useState({
    name: '',
    version: '',
    type: '',
    format: '',
    description: '',
    access: '',
    tags: '',
    dependencies: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

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

  const handleSubmit = async () => {
    // 验证必填项
    if (!formData.name.trim()) {
      toast.error('请输入模型名称');
      return;
    }
    if (!formData.version.trim()) {
      toast.error('请输入模型版本');
      return;
    }
    if (!formData.type) {
      toast.error('请选择模型类型');
      return;
    }
    if (!formData.format) {
      toast.error('请选择模型格式');
      return;
    }

    setIsSubmitting(true);

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

      // 创建新模型对象
      const newModel = {
        id: Date.now().toString(),
        name: formData.name,
        type: formData.type,
        version: formData.version,
        status: 'active',
        description: formData.description,
        apiEndpoint: `https://api.smart-crop.com/v2/models/${formData.name.toLowerCase().replace(/\s+/g, '-')}`,
        parameters: {
          confidence_threshold: 0.85,
          max_detections: 10
        },
        metrics: {
          total_calls: 0,
          avg_response_time: 200,
          success_rate: 100,
          accuracy: 95.0,
          last_called: new Date().toISOString(),
          qps: 0
        },
        tags: formData.tags ? formData.tags.split(',').map(tag => tag.trim()) : [],
        visibility: formData.access === '公开' ? 'public' : formData.access === '团队共享' ? 'team' : 'private',
        team: 'AI算法团队',
        concurrency: 100,
        timeout: 30000,
        retryCount: 3,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };

      // 添加模型
      dispatch({ type: 'ADD_MODEL', payload: newModel });
      dispatch({ type: 'SET_ADD_MODEL_DIALOG', payload: false });

      // 重置表单
      setFormData({
        name: '',
        version: '',
        type: '',
        format: '',
        description: '',
        access: '',
        tags: '',
        dependencies: ''
      });

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <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="输入模型名称"
                value={formData.name}
                onChange={(e) => handleInputChange('name', e.target.value)}
              />
            </div>
            <div>
              <Label>模型版本</Label>
              <Input
                placeholder="v1.0.0"
                value={formData.version}
                onChange={(e) => handleInputChange('version', e.target.value)}
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>模型类型</Label>
              <Select value={formData.type} onValueChange={(value) => handleInputChange('type', value)}>
                <SelectTrigger>
                  <SelectValue placeholder="选择模型类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="pest_identification">病虫害识别</SelectItem>
                  <SelectItem value="growth_status">生长状态</SelectItem>
                  <SelectItem value="yield_prediction">产量预估</SelectItem>
                  <SelectItem value="soil_analysis">土壤分析</SelectItem>
                  <SelectItem value="irrigation_optimization">灌溉优化</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>模型格式</Label>
              <Select value={formData.format} onValueChange={(value) => handleInputChange('format', value)}>
                <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}
              value={formData.description}
              onChange={(e) => handleInputChange('description', e.target.value)}
            />
          </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}
              value={formData.dependencies}
              onChange={(e) => handleInputChange('dependencies', e.target.value)}
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>访问权限</Label>
              <Select value={formData.access} onValueChange={(value) => handleInputChange('access', value)}>
                <SelectTrigger>
                  <SelectValue placeholder="选择访问权限" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="公开">公开</SelectItem>
                  <SelectItem value="私有">私有</SelectItem>
                  <SelectItem value="团队共享">团队共享</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>标签</Label>
              <Input
                placeholder="用逗号分隔，如：深度学习,CNN"
                value={formData.tags}
                onChange={(e) => handleInputChange('tags', e.target.value)}
              />
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSubmit} disabled={isSubmitting}>
            {isSubmitting ? '注册中...' : (
              <>
                <Save className="h-4 w-4 mr-2" />
                注册模型
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}