import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import {
  Search,
  Plus,
  Edit,
  Eye,
  Trash2,
  Brain,
  Sparkles,
  Clock,
  Droplet,
  Play,
  CheckCircle,
  AlertCircle,
  Calendar,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

type ModelType = '经验灌溉模型' | 'AI决策模型';
type ModelStatus = '启用' | '停用';
type CropType = '番茄' | '黄瓜' | '西红柿' | '茄子' | '玉米' | '小麦' | '水稻' | '苹果' | '葡萄';
type AIModelType = '作物生长预测' | '病虫害识别' | '产量预估' | '土壤分析' | '灌溉优化' | '其他';

// 经验规则接口
interface ExperienceRule {
  id: string;
  plantDays: number; // 种植天数
  waterAmount: number; // 浇水量（L/m²）
  frequency: number; // 频率（次/天）
  duration: number; // 持续时间（分钟）
  notes?: string;
}

// AI模型（来自AI系统）
interface AIModel {
  id: string;
  name: string;
  version: string;
  type: AIModelType;
  format: string;
  description: string;
  status: string;
  accuracy?: number;
  endpoint: string;
}

// 灌溉模型接口
interface IrrigationModel {
  id: string;
  modelNo: string;
  modelName: string;
  modelType: ModelType;
  crop?: CropType;
  status: ModelStatus;
  // AI模型相关
  aiModelId?: string; // AI系统中的模型ID
  aiModelType?: AIModelType;
  aiModelVersion?: string;
  // 经验模型相关
  experienceRules?: ExperienceRule[];
  // 其他信息
  description?: string;
  creator?: string;
  createdAt: string;
  updatedAt?: string;
  lastUsedAt?: string;
}

export function IrrigationModelConfig() {
  // 从AI系统获取可用的灌溉优化模型（模拟数据）
  const availableAIModels: AIModel[] = [
    {
      id: 'ai-model-1',
      name: '番茄智能灌溉优化模型',
      version: 'v2.3.1',
      type: '灌溉优化',
      format: 'TensorFlow',
      description: '基于深度学习的番茄精准灌溉决策模型，综合考虑温湿度、光照、土壤水分等因素',
      status: '运行中',
      accuracy: 94.5,
      endpoint: 'https://api.farm-ai.com/v1/irrigation/tomato',
    },
    {
      id: 'ai-model-2',
      name: '黄瓜水肥一体化模型',
      version: 'v1.8.2',
      type: '灌溉优化',
      format: 'PyTorch',
      description: '黄瓜全生长周期水肥智能管理模型，自动优化灌溉和施肥策略',
      status: '运行中',
      accuracy: 96.2,
      endpoint: 'https://api.farm-ai.com/v1/irrigation/cucumber',
    },
    {
      id: 'ai-model-3',
      name: '小麦精准灌溉模型',
      version: 'v3.1.0',
      type: '灌溉优化',
      format: 'ONNX',
      description: '小麦关键生长期智能灌溉决策模型，提高水资源利用效率',
      status: '运行中',
      accuracy: 92.8,
      endpoint: 'https://api.farm-ai.com/v1/irrigation/wheat',
    },
    {
      id: 'ai-model-4',
      name: '玉米节水灌溉模型',
      version: 'v2.5.3',
      type: '灌溉优化',
      format: 'Scikit-learn',
      description: '玉米节水灌溉优化模型，在保证产量的前提下最小化用水量',
      status: '运行中',
      accuracy: 93.6,
      endpoint: 'https://api.farm-ai.com/v1/irrigation/corn',
    },
    {
      id: 'ai-model-5',
      name: '大棚蔬菜智能灌溉',
      version: 'v1.5.0',
      type: '灌溉优化',
      format: 'TensorFlow',
      description: '适用于大棚环境的多种蔬菜智能灌溉决策系统',
      status: '运行中',
      accuracy: 95.1,
      endpoint: 'https://api.farm-ai.com/v1/irrigation/greenhouse',
    },
  ];

  const [models, setModels] = useState<IrrigationModel[]>([
    {
      id: 'model-1',
      modelNo: 'MODEL-2024-001',
      modelName: '番茄AI智能灌溉模型',
      modelType: 'AI决策模型',
      crop: '番茄',
      status: '启用',
      aiModelId: 'ai-model-1',
      aiModelType: '灌溉优化',
      aiModelVersion: 'v2.3.1',
      description: '基于深度学习的番茄精准灌溉决策模型',
      creator: '张三',
      createdAt: '2024-03-15',
      lastUsedAt: '2024-10-24',
    },
    {
      id: 'model-2',
      modelNo: 'MODEL-2024-002',
      modelName: '黄瓜经验灌溉模型',
      modelType: '经验灌溉模型',
      crop: '黄瓜',
      status: '启用',
      experienceRules: [
        { id: 'rule-1', plantDays: 7, waterAmount: 15, frequency: 2, duration: 30, notes: '幼苗期' },
        { id: 'rule-2', plantDays: 30, waterAmount: 25, frequency: 3, duration: 45, notes: '生长期' },
        { id: 'rule-3', plantDays: 60, waterAmount: 30, frequency: 3, duration: 50, notes: '结果期' },
      ],
      description: '基于农业专家经验的黄瓜灌溉规则',
      creator: '李四',
      createdAt: '2024-05-20',
      lastUsedAt: '2024-10-23',
    },
    {
      id: 'model-3',
      modelNo: 'MODEL-2024-003',
      modelName: '小麦AI灌溉决策',
      modelType: 'AI决策模型',
      crop: '小麦',
      status: '停用',
      aiModelId: 'ai-model-3',
      aiModelType: '灌溉优化',
      aiModelVersion: 'v3.1.0',
      description: '小麦全生长周期智能灌溉模型',
      creator: '王五',
      createdAt: '2024-08-10',
    },
  ]);

  const [showDialog, setShowDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [editingModel, setEditingModel] = useState<IrrigationModel | null>(null);
  const [viewingModel, setViewingModel] = useState<IrrigationModel | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<IrrigationModel | null>(null);

  // 搜索和筛选状态
  const [searchText, setSearchText] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [filterCrop, setFilterCrop] = useState<string>('all');

  // 表单数据
  const [formData, setFormData] = useState<Partial<IrrigationModel>>({
    modelType: '经验灌溉模型',
    status: '测试中',
    experienceRules: [],
  });

  // 经验规则表单
  const [ruleFormData, setRuleFormData] = useState<Partial<ExperienceRule>>({});
  const [showRuleDialog, setShowRuleDialog] = useState(false);
  const [editingRuleIndex, setEditingRuleIndex] = useState<number | null>(null);

  // 过滤模型列表
  const filteredModels = models.filter(model => {
    const matchSearch = searchText === '' || 
      model.modelName.toLowerCase().includes(searchText.toLowerCase()) ||
      model.modelNo.toLowerCase().includes(searchText.toLowerCase());
    
    const matchType = filterType === 'all' || model.modelType === filterType;
    const matchStatus = filterStatus === 'all' || model.status === filterStatus;
    const matchCrop = filterCrop === 'all' || model.crop === filterCrop;
    
    return matchSearch && matchType && matchStatus && matchCrop;
  });

  // 统计数据
  const stats = {
    total: models.length,
    ai: models.filter(m => m.modelType === 'AI决策模型').length,
    experience: models.filter(m => m.modelType === '经验灌溉模型').length,
    active: models.filter(m => m.status === '启用').length,
  };

  const getStatusColor = (status: ModelStatus) => {
    switch (status) {
      case '启用': return 'bg-green-100 text-green-700 border-green-200';
      case '停用': return 'bg-gray-100 text-gray-700 border-gray-200';
      default: return 'bg-gray-100 text-gray-700 border-gray-200';
    }
  };

  const getTypeColor = (type: ModelType) => {
    return type === 'AI决策模型' 
      ? 'bg-purple-100 text-purple-700 border-purple-200'
      : 'bg-orange-100 text-orange-700 border-orange-200';
  };

  // 新增模型
  const handleAdd = () => {
    setEditingModel(null);
    setFormData({
      modelNo: `MODEL-${new Date().getFullYear()}-${String(models.length + 1).padStart(3, '0')}`,
      modelType: '经验灌溉模型',
      status: '启用',
      experienceRules: [],
    });
    setShowDialog(true);
  };

  // 编辑模型
  const handleEdit = (model: IrrigationModel) => {
    setEditingModel(model);
    setFormData(model);
    setShowDialog(true);
  };

  // 查看详情
  const handleView = (model: IrrigationModel) => {
    setViewingModel(model);
    setShowDetailDialog(true);
  };

  // 删除模型
  const handleDelete = (model: IrrigationModel) => {
    setDeleteTarget(model);
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (deleteTarget) {
      setModels(models.filter(m => m.id !== deleteTarget.id));
      toast.success(`模型 ${deleteTarget.modelName} 已删除`);
      setShowDeleteDialog(false);
      setDeleteTarget(null);
    }
  };

  // 保存模型
  const handleSave = () => {
    if (!formData.modelName || !formData.crop) {
      toast.error('请填写必填项');
      return;
    }

    if (formData.modelType === 'AI决策模型' && !formData.aiModelId) {
      toast.error('请选择AI模型');
      return;
    }

    if (formData.modelType === '经验灌溉模型' && (!formData.experienceRules || formData.experienceRules.length === 0)) {
      toast.error('请至少添加一条经验规则');
      return;
    }

    if (editingModel) {
      // 更新
      setModels(models.map(m => 
        m.id === editingModel.id ? { 
          ...m, 
          ...formData,
          updatedAt: new Date().toISOString().split('T')[0]
        } as IrrigationModel : m
      ));
      toast.success('模型配置已更新');
    } else {
      // 新增
      const newModel: IrrigationModel = {
        ...formData,
        id: `model-${Date.now()}`,
        creator: '当前用户',
        createdAt: new Date().toISOString().split('T')[0],
      } as IrrigationModel;
      setModels([...models, newModel]);
      toast.success('模型配置添加成功');
    }
    setShowDialog(false);
  };

  // 添加经验规则
  const handleAddRule = () => {
    setEditingRuleIndex(null);
    setRuleFormData({});
    setShowRuleDialog(true);
  };

  // 编辑经验规则
  const handleEditRule = (index: number) => {
    const rules = formData.experienceRules || [];
    setEditingRuleIndex(index);
    setRuleFormData(rules[index]);
    setShowRuleDialog(true);
  };

  // 删除经验规则
  const handleDeleteRule = (index: number) => {
    const rules = [...(formData.experienceRules || [])];
    rules.splice(index, 1);
    setFormData({ ...formData, experienceRules: rules });
    toast.success('规则已删除');
  };

  // 保存经验规则
  const handleSaveRule = () => {
    if (!ruleFormData.plantDays || !ruleFormData.waterAmount) {
      toast.error('请填写必填项');
      return;
    }

    const rules = [...(formData.experienceRules || [])];
    
    if (editingRuleIndex !== null) {
      // 更新规则
      rules[editingRuleIndex] = { ...rules[editingRuleIndex], ...ruleFormData } as ExperienceRule;
      toast.success('规则已更新');
    } else {
      // 新增规则
      const newRule: ExperienceRule = {
        ...ruleFormData,
        id: `rule-${Date.now()}`,
      } as ExperienceRule;
      rules.push(newRule);
      toast.success('规则已添加');
    }

    setFormData({ ...formData, experienceRules: rules });
    setShowRuleDialog(false);
  };

  return (
    <div className="space-y-6 px-6 pb-6">
      {/* 功能说明卡片 */}
      <Card className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 border-green-200">
        <div className="flex items-start gap-2">
          <Sparkles className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-green-900">
            <p className="mb-2">灌溉模型说明：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>AI决策模型</strong>：基于机器学习算法，自动分析环境数据进行智能决策</li>
              <li>• <strong>经验灌溉模型</strong>：基于农业专家经验，按照种植天数设置灌溉规则</li>
            </ul>
          </div>
        </div>
      </Card>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="flex items-center justify-between gap-4">
          <div className="flex gap-4 flex-1">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索模型名称、编号..."
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={filterType} onValueChange={setFilterType}>
              <SelectTrigger className="w-40">
                <SelectValue placeholder="模型类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类型</SelectItem>
                <SelectItem value="AI决策模型">AI决策模型</SelectItem>
                <SelectItem value="经验灌溉模型">经验灌溉模型</SelectItem>
              </SelectContent>
            </Select>
            <Select value={filterCrop} onValueChange={setFilterCrop}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="作物" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部作物</SelectItem>
                <SelectItem value="番茄">番茄</SelectItem>
                <SelectItem value="黄瓜">黄瓜</SelectItem>
                <SelectItem value="西红柿">西红柿</SelectItem>
                <SelectItem value="小麦">小麦</SelectItem>
                <SelectItem value="玉米">玉米</SelectItem>
              </SelectContent>
            </Select>
            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="启用">启用</SelectItem>
                <SelectItem value="停用">停用</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <Button className="bg-green-600 hover:bg-green-700" onClick={handleAdd}>
            <Plus className="w-4 h-4 mr-2" />
            新增模型
          </Button>
        </div>
      </Card>

      {/* 模型列表 - 卡片展示 */}
      <div>
        {filteredModels.length === 0 ? (
          <Card className="p-12">
            <div className="text-center text-muted-foreground">
              <Brain className="w-16 h-16 mx-auto mb-4 opacity-50" />
              <p>暂无模型数据</p>
              <p className="text-sm mt-1">点击右上角"新增模型"按钮创建第一个灌溉模型</p>
            </div>
          </Card>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {filteredModels.map((model) => (
              <Card key={model.id} className="p-5 hover:shadow-lg transition-shadow">
                <div className="space-y-4">
                  {/* 模型头部 */}
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        {model.modelType === 'AI决策模型' ? (
                          <Sparkles className="w-5 h-5 text-purple-600" />
                        ) : (
                          <Clock className="w-5 h-5 text-orange-600" />
                        )}
                        <h3 className="font-medium">{model.modelName}</h3>
                      </div>
                      <div className="text-xs text-muted-foreground">#{model.modelNo}</div>
                    </div>
                    <Badge className={getStatusColor(model.status)}>
                      {model.status}
                    </Badge>
                  </div>

                  {/* 模型信息 */}
                  <div className="space-y-2 text-sm">
                    <div className="flex items-center gap-2">
                      <Droplet className="w-4 h-4 text-blue-600" />
                      <span className="text-muted-foreground">作物:</span>
                      <span>{model.crop}</span>
                    </div>
                    
                    {model.modelType === 'AI决策模型' ? (
                      <>
                        <div className="flex items-center gap-2">
                          <Brain className="w-4 h-4 text-purple-600" />
                          <span className="text-muted-foreground">AI模型:</span>
                          <span className="text-xs">{model.aiModelType}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <Sparkles className="w-4 h-4 text-purple-600" />
                          <span className="text-muted-foreground">版本:</span>
                          <span className="text-xs">{model.aiModelVersion}</span>
                        </div>
                      </>
                    ) : (
                      <div className="flex items-center gap-2">
                        <Calendar className="w-4 h-4 text-orange-600" />
                        <span className="text-muted-foreground">规则数:</span>
                        <span>{model.experienceRules?.length || 0} 条</span>
                      </div>
                    )}
                  </div>

                  {/* 描述 */}
                  {model.description && (
                    <p className="text-xs text-muted-foreground line-clamp-2">
                      {model.description}
                    </p>
                  )}

                  {/* 时间信息 */}
                  <div className="text-xs text-muted-foreground space-y-1 pt-2 border-t">
                    <div>创建: {model.createdAt}</div>
                    {model.lastUsedAt && (
                      <div>最近使用: {model.lastUsedAt}</div>
                    )}
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex gap-2 pt-2">
                    <Button size="sm" variant="outline" className="flex-1" onClick={() => handleView(model)}>
                      <Eye className="w-3 h-3 mr-1" />
                      查看
                    </Button>
                    <Button size="sm" variant="outline" className="flex-1" onClick={() => handleEdit(model)}>
                      <Edit className="w-3 h-3 mr-1" />
                      编辑
                    </Button>
                    <Button 
                      size="sm" 
                      variant="outline" 
                      onClick={() => handleDelete(model)}
                      className="text-red-600 hover:text-red-700 hover:border-red-300"
                    >
                      <Trash2 className="w-3 h-3" />
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* 原来的表格版本保留但隐藏 */}
      <div className="hidden">
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>模型信息</TableHead>
                <TableHead>类型</TableHead>
                <TableHead>作物</TableHead>
                <TableHead>配置详情</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead className="text-right">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredModels.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                    <Brain className="w-12 h-12 mx-auto mb-2 opacity-50" />
                    <p>暂无模型数据</p>
                </TableCell>
              </TableRow>
            ) : (
              filteredModels.map((model) => (
                <TableRow key={model.id}>
                  <TableCell>
                    <div>
                      <div className="font-medium">{model.modelName}</div>
                      <div className="text-xs text-muted-foreground mt-1">#{model.modelNo}</div>
                      {model.description && (
                        <div className="text-xs text-muted-foreground mt-1">{model.description}</div>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge className={getTypeColor(model.modelType)}>
                      {model.modelType}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">{model.crop}</Badge>
                  </TableCell>
                  <TableCell>
                    {model.modelType === 'AI决策模型' ? (
                      <div className="text-xs">
                        <div>{model.aiModelType}</div>
                        <div className="text-muted-foreground mt-1">{model.aiModelVersion}</div>
                      </div>
                    ) : (
                      <div className="text-xs">
                        <div>{model.experienceRules?.length || 0} 条规则</div>
                        <div className="text-muted-foreground mt-1">经验规则配置</div>
                      </div>
                    )}
                  </TableCell>
                  <TableCell>
                    <Badge className={getStatusColor(model.status)}>
                      {model.status}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="text-xs">
                      <div>{model.createdAt}</div>
                      {model.lastUsedAt && (
                        <div className="text-muted-foreground mt-1">
                          最近使用: {model.lastUsedAt}
                        </div>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2 justify-end">
                      <Button size="sm" variant="outline" onClick={() => handleView(model)}>
                        <Eye className="w-3 h-3" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleEdit(model)}>
                        <Edit className="w-3 h-3" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline" 
                        onClick={() => handleDelete(model)}
                        className="text-red-600 hover:text-red-700 hover:border-red-300"
                      >
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>
      </div>

      {/* 新增/编辑模型对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingModel ? '编辑灌溉模型' : '新增灌溉模型'}
            </DialogTitle>
            <DialogDescription>
              配置灌溉模型的基本信息和参数
            </DialogDescription>
          </DialogHeader>

          <Tabs defaultValue={formData.modelType || '经验灌溉模型'} onValueChange={(value) => setFormData({ ...formData, modelType: value as ModelType })}>
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="经验灌溉模型">
                <Clock className="w-4 h-4 mr-2" />
                经验灌溉模型
              </TabsTrigger>
              <TabsTrigger value="AI决策模型">
                <Sparkles className="w-4 h-4 mr-2" />
                AI决策模型
              </TabsTrigger>
            </TabsList>

            {/* 经验灌溉模型配置 */}
            <TabsContent value="经验灌溉模型" className="space-y-4 mt-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>模型编号 *</Label>
                  <Input
                    value={formData.modelNo || ''}
                    onChange={(e) => setFormData({ ...formData, modelNo: e.target.value })}
                    placeholder="MODEL-2024-001"
                    disabled={!!editingModel}
                  />
                </div>
                <div>
                  <Label>模型名称 *</Label>
                  <Input
                    value={formData.modelName || ''}
                    onChange={(e) => setFormData({ ...formData, modelName: e.target.value })}
                    placeholder="番茄经验灌溉模型"
                  />
                </div>
                <div>
                  <Label>作物类型 *</Label>
                  <Select
                    value={formData.crop || ''}
                    onValueChange={(value: CropType) => setFormData({ ...formData, crop: value })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="请选择" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="番茄">番茄</SelectItem>
                      <SelectItem value="黄瓜">黄瓜</SelectItem>
                      <SelectItem value="西红柿">西红柿</SelectItem>
                      <SelectItem value="茄子">茄子</SelectItem>
                      <SelectItem value="小麦">小麦</SelectItem>
                      <SelectItem value="玉米">玉米</SelectItem>
                      <SelectItem value="水稻">水稻</SelectItem>
                      <SelectItem value="苹果">苹果</SelectItem>
                      <SelectItem value="葡萄">葡萄</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>状态</Label>
                  <Select
                    value={formData.status || '启用'}
                    onValueChange={(value: ModelStatus) => setFormData({ ...formData, status: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="启用">启用</SelectItem>
                      <SelectItem value="停用">停用</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="col-span-2">
                  <Label>模型描述</Label>
                  <Textarea
                    value={formData.description || ''}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    placeholder="描述模型的用途和特点"
                    rows={3}
                  />
                </div>
              </div>

              {/* 经验规则配置 */}
              <div className="mt-6">
                <div className="flex items-center justify-between mb-4">
                  <h4 className="text-green-700">经验规则配置</h4>
                  <Button size="sm" variant="outline" onClick={handleAddRule}>
                    <Plus className="w-4 h-4 mr-2" />
                    添加规则
                  </Button>
                </div>

                {formData.experienceRules && formData.experienceRules.length > 0 ? (
                  <div className="space-y-2">
                    {formData.experienceRules.map((rule, index) => (
                      <Card key={rule.id} className="p-4">
                        <div className="flex items-center justify-between">
                          <div className="flex-1 grid grid-cols-4 gap-4">
                            <div>
                              <div className="text-xs text-muted-foreground">种植天数</div>
                              <div className="mt-1">{rule.plantDays} 天后</div>
                            </div>
                            <div>
                              <div className="text-xs text-muted-foreground">浇水量</div>
                              <div className="mt-1">{rule.waterAmount} L/m²</div>
                            </div>
                            <div>
                              <div className="text-xs text-muted-foreground">频率</div>
                              <div className="mt-1">{rule.frequency} 次/天</div>
                            </div>
                            <div>
                              <div className="text-xs text-muted-foreground">持续时间</div>
                              <div className="mt-1">{rule.duration} 分钟</div>
                            </div>
                          </div>
                          <div className="flex gap-2 ml-4">
                            <Button size="sm" variant="outline" onClick={() => handleEditRule(index)}>
                              <Edit className="w-3 h-3" />
                            </Button>
                            <Button 
                              size="sm" 
                              variant="outline"
                              onClick={() => handleDeleteRule(index)}
                              className="text-red-600 hover:text-red-700"
                            >
                              <Trash2 className="w-3 h-3" />
                            </Button>
                          </div>
                        </div>
                        {rule.notes && (
                          <div className="mt-2 text-xs text-muted-foreground">
                            备注：{rule.notes}
                          </div>
                        )}
                      </Card>
                    ))}
                  </div>
                ) : (
                  <Card className="p-8">
                    <div className="text-center text-muted-foreground">
                      <Calendar className="w-12 h-12 mx-auto mb-2 opacity-50" />
                      <p>暂无规则，请添加经验规则</p>
                    </div>
                  </Card>
                )}
              </div>
            </TabsContent>

            {/* AI决策模型配置 */}
            <TabsContent value="AI决策模型" className="space-y-4 mt-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>模型编号 *</Label>
                  <Input
                    value={formData.modelNo || ''}
                    onChange={(e) => setFormData({ ...formData, modelNo: e.target.value })}
                    placeholder="MODEL-2024-001"
                    disabled={!!editingModel}
                  />
                </div>
                <div>
                  <Label>模型名称 *</Label>
                  <Input
                    value={formData.modelName || ''}
                    onChange={(e) => setFormData({ ...formData, modelName: e.target.value })}
                    placeholder="番茄AI智能灌溉模型"
                  />
                </div>
                <div>
                  <Label>作物类型 *</Label>
                  <Select
                    value={formData.crop || ''}
                    onValueChange={(value: CropType) => setFormData({ ...formData, crop: value })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="请选择" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="番茄">番茄</SelectItem>
                      <SelectItem value="黄瓜">黄瓜</SelectItem>
                      <SelectItem value="西红柿">西红柿</SelectItem>
                      <SelectItem value="茄子">茄子</SelectItem>
                      <SelectItem value="小麦">小麦</SelectItem>
                      <SelectItem value="玉米">玉米</SelectItem>
                      <SelectItem value="水稻">水稻</SelectItem>
                      <SelectItem value="苹果">苹果</SelectItem>
                      <SelectItem value="葡萄">葡萄</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>AI模型选择 *</Label>
                  <Select
                    value={formData.aiModelId || ''}
                    onValueChange={(value) => {
                      // 从AI系统模型列表中查找选中的模型
                      const selectedAIModel = availableAIModels.find(m => m.id === value);
                      setFormData({ 
                        ...formData, 
                        aiModelId: value,
                        aiModelType: selectedAIModel?.type,
                        aiModelVersion: selectedAIModel?.version,
                      });
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="请选择AI模型" />
                    </SelectTrigger>
                    <SelectContent>
                      {availableAIModels.map((model) => (
                        <SelectItem key={model.id} value={model.id}>
                          <div className="flex flex-col">
                            <span>{model.name}</span>
                            <span className="text-xs text-muted-foreground">
                              {model.type} • {model.version} • 准确率 {model.accuracy}%
                            </span>
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground mt-1">
                    从AI作物模型精准决策系统中选择已配置的模型
                  </p>
                </div>
                <div>
                  <Label>状态</Label>
                  <Select
                    value={formData.status || '启用'}
                    onValueChange={(value: ModelStatus) => setFormData({ ...formData, status: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="启用">启用</SelectItem>
                      <SelectItem value="停用">停用</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="col-span-2">
                  <Label>模型描述</Label>
                  <Textarea
                    value={formData.description || ''}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    placeholder="描述模型的用途和特点"
                    rows={3}
                  />
                </div>
              </div>

              {/* 显示选中的AI模型信息 */}
              {formData.aiModelId && (() => {
                const selectedModel = availableAIModels.find(m => m.id === formData.aiModelId);
                return selectedModel ? (
                  <Card className="p-4 bg-purple-50 border-purple-200">
                    <div className="flex items-start gap-3">
                      <Sparkles className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
                      <div className="flex-1">
                        <h4 className="text-purple-900 mb-2">选中的AI模型信息</h4>
                        <div className="grid grid-cols-2 gap-3 text-sm">
                          <div>
                            <span className="text-purple-700">模型类型：</span>
                            <span className="text-purple-900 ml-1">{selectedModel.type}</span>
                          </div>
                          <div>
                            <span className="text-purple-700">模型版本：</span>
                            <span className="text-purple-900 ml-1">{selectedModel.version}</span>
                          </div>
                          <div>
                            <span className="text-purple-700">准确率：</span>
                            <span className="text-purple-900 ml-1">{selectedModel.accuracy}%</span>
                          </div>
                          <div>
                            <span className="text-purple-700">运行状态：</span>
                            <span className="text-purple-900 ml-1">{selectedModel.status}</span>
                          </div>
                        </div>
                        {selectedModel.description && (
                          <p className="text-xs text-purple-800 mt-2">{selectedModel.description}</p>
                        )}
                      </div>
                    </div>
                  </Card>
                ) : null;
              })()}

              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="flex items-start gap-2">
                  <Sparkles className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                  <div className="text-sm text-blue-900">
                    <p className="mb-2">AI模型说明：</p>
                    <ul className="space-y-1 text-xs">
                      <li>• AI模型来自"AI作物模型与精准决策系统"中已部署的灌溉优化模型</li>
                      <li>• 模型将自动分析土壤湿度、气象数据、作物生长阶段等多维度信息</li>
                      <li>• 系统会根据模型输出自动调整灌溉策略</li>
                      <li>• 请确保选择的AI模型处于运行中状态</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </TabsContent>
          </Tabs>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 经验规则对话框 */}
      <Dialog open={showRuleDialog} onOpenChange={setShowRuleDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {editingRuleIndex !== null ? '编辑经验规则' : '新增经验规则'}
            </DialogTitle>
            <DialogDescription>
              配置基于种植天数的灌溉规则
            </DialogDescription>
          </DialogHeader>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>种植天数 *</Label>
              <Input
                type="number"
                value={ruleFormData.plantDays || ''}
                onChange={(e) => setRuleFormData({ ...ruleFormData, plantDays: parseInt(e.target.value) || 0 })}
                placeholder="7"
              />
              <p className="text-xs text-muted-foreground mt-1">种植多少天后开始执行</p>
            </div>
            <div>
              <Label>浇水量 (L/m²) *</Label>
              <Input
                type="number"
                value={ruleFormData.waterAmount || ''}
                onChange={(e) => setRuleFormData({ ...ruleFormData, waterAmount: parseFloat(e.target.value) || 0 })}
                placeholder="15"
              />
            </div>
            <div>
              <Label>频率 (次/天)</Label>
              <Input
                type="number"
                value={ruleFormData.frequency || ''}
                onChange={(e) => setRuleFormData({ ...ruleFormData, frequency: parseInt(e.target.value) || 1 })}
                placeholder="2"
              />
            </div>
            <div>
              <Label>持续时间 (分钟)</Label>
              <Input
                type="number"
                value={ruleFormData.duration || ''}
                onChange={(e) => setRuleFormData({ ...ruleFormData, duration: parseInt(e.target.value) || 30 })}
                placeholder="30"
              />
            </div>
            <div className="col-span-2">
              <Label>备注</Label>
              <Textarea
                value={ruleFormData.notes || ''}
                onChange={(e) => setRuleFormData({ ...ruleFormData, notes: e.target.value })}
                placeholder="如：幼苗期、生长期、结果期等"
                rows={2}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowRuleDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveRule}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 查看详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>模型详情</DialogTitle>
            <DialogDescription>查看灌溉模型的详细信息</DialogDescription>
          </DialogHeader>

          {viewingModel && (
            <div className="space-y-6">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>模型编号</Label>
                  <div className="field-value">{viewingModel.modelNo}</div>
                </div>
                <div>
                  <Label>模型名称</Label>
                  <div className="field-value">{viewingModel.modelName}</div>
                </div>
                <div>
                  <Label>模型类型</Label>
                  <div className="field-value">
                    <Badge className={getTypeColor(viewingModel.modelType)}>
                      {viewingModel.modelType}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label>作物类型</Label>
                  <div className="field-value">
                    <Badge variant="outline">{viewingModel.crop}</Badge>
                  </div>
                </div>
                <div>
                  <Label>状态</Label>
                  <div className="field-value">
                    <Badge className={getStatusColor(viewingModel.status)}>
                      {viewingModel.status}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label>创建时间</Label>
                  <div className="field-value">{viewingModel.createdAt}</div>
                </div>
              </div>

              {viewingModel.description && (
                <div>
                  <Label>模型描述</Label>
                  <div className="field-value">{viewingModel.description}</div>
                </div>
              )}

              {viewingModel.modelType === 'AI决策模型' && viewingModel.aiModelId && (() => {
                const aiModel = availableAIModels.find(m => m.id === viewingModel.aiModelId);
                return aiModel ? (
                  <Card className="p-4 bg-purple-50 border-purple-200">
                    <div className="flex items-start gap-3">
                      <Sparkles className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
                      <div className="flex-1">
                        <h4 className="text-purple-900 mb-3">AI模型信息</h4>
                        <div className="grid grid-cols-2 gap-3">
                          <div>
                            <div className="text-xs text-purple-700">模型名称</div>
                            <div className="mt-1 text-sm text-purple-900">{aiModel.name}</div>
                          </div>
                          <div>
                            <div className="text-xs text-purple-700">模型类型</div>
                            <div className="mt-1 text-sm text-purple-900">{aiModel.type}</div>
                          </div>
                          <div>
                            <div className="text-xs text-purple-700">模型版本</div>
                            <div className="mt-1 text-sm text-purple-900">{aiModel.version}</div>
                          </div>
                          <div>
                            <div className="text-xs text-purple-700">模型格式</div>
                            <div className="mt-1 text-sm text-purple-900">{aiModel.format}</div>
                          </div>
                          <div>
                            <div className="text-xs text-purple-700">准确率</div>
                            <div className="mt-1 text-sm text-purple-900">{aiModel.accuracy}%</div>
                          </div>
                          <div>
                            <div className="text-xs text-purple-700">运行状态</div>
                            <div className="mt-1 text-sm text-purple-900">{aiModel.status}</div>
                          </div>
                        </div>
                        {aiModel.description && (
                          <div className="mt-3">
                            <div className="text-xs text-purple-700">模型描述</div>
                            <div className="mt-1 text-sm text-purple-900">{aiModel.description}</div>
                          </div>
                        )}
                      </div>
                    </div>
                  </Card>
                ) : (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>AI模型类型</Label>
                      <div className="field-value">{viewingModel.aiModelType}</div>
                    </div>
                    <div>
                      <Label>模型版本</Label>
                      <div className="field-value">{viewingModel.aiModelVersion || '-'}</div>
                    </div>
                  </div>
                );
              })()}

              {viewingModel.modelType === '经验灌溉模型' && viewingModel.experienceRules && (
                <div>
                  <Label>经验规则</Label>
                  <div className="mt-2 space-y-2">
                    {viewingModel.experienceRules.map((rule, index) => (
                      <Card key={rule.id} className="p-4">
                        <div className="grid grid-cols-4 gap-4">
                          <div>
                            <div className="text-xs text-muted-foreground">种植天数</div>
                            <div className="mt-1">{rule.plantDays} 天后</div>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground">浇水量</div>
                            <div className="mt-1">{rule.waterAmount} L/m²</div>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground">频率</div>
                            <div className="mt-1">{rule.frequency} 次/天</div>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground">持续时间</div>
                            <div className="mt-1">{rule.duration} 分钟</div>
                          </div>
                        </div>
                        {rule.notes && (
                          <div className="mt-2 text-xs text-muted-foreground">
                            备注：{rule.notes}
                          </div>
                        )}
                      </Card>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除模型 <strong>{deleteTarget?.modelName}</strong> 吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
