import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Switch } from '../ui/switch';
import { Progress } from '../ui/progress';
import {
  Wand2,
  Plus,
  Search,
  Droplets,
  Bug,
  Sprout,
  TrendingUp,
  Thermometer,
  Brain,
  Settings,
  Eye,
  Edit,
  Trash2,
  Play,
  CheckCircle,
  AlertCircle,
  Zap,
  Code,
  FileCode,
  Database,
  Bell,
  Calendar,
  Clock,
  Filter,
  Copy,
  Download,
  Upload,
  Link,
  Layers,
  GitBranch,
  Activity,
  BarChart3,
  Server,
  Cpu,
  Package,
  Workflow,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface AIApplicationGenerationProps {
  activePath?: string;
}

// 应用模板类型
type TemplateType = 'irrigation' | 'pest' | 'fertilizer' | 'yield' | 'growth' | 'weather' | 'custom';

// 应用模板定义
interface ApplicationTemplate {
  id: TemplateType;
  name: string;
  icon: any;
  description: string;
  category: string;
  features: string[];
  defaultInputs: InputField[];
  defaultOutputs: OutputField[];
  sampleTriggers: string[];
  complexity: 'simple' | 'medium' | 'complex';
  estimatedTime: string;
}

// 输入字段
interface InputField {
  id: string;
  name: string;
  type: 'number' | 'text' | 'date' | 'boolean' | 'select' | 'sensor';
  source: 'manual' | 'sensor' | 'database' | 'api';
  required: boolean;
  defaultValue?: any;
  unit?: string;
  range?: { min: number; max: number };
  options?: string[];
}

// 输出字段
interface OutputField {
  id: string;
  name: string;
  type: 'number' | 'text' | 'boolean' | 'json' | 'alert';
  format: string;
  destination: 'display' | 'database' | 'notification' | 'api';
  condition?: string;
}

// 触发条件
interface TriggerCondition {
  id: string;
  type: 'time' | 'event' | 'threshold' | 'manual';
  config: any;
  enabled: boolean;
}

// 业务逻辑节点
interface LogicNode {
  id: string;
  type: 'input' | 'process' | 'decision' | 'output';
  label: string;
  config: any;
  position: { x: number; y: number };
}

// 生成的应用
interface GeneratedApplication {
  id: string;
  name: string;
  template: TemplateType;
  modelId: string;
  modelName: string;
  inputs: InputField[];
  outputs: OutputField[];
  triggers: TriggerCondition[];
  logicNodes: LogicNode[];
  status: 'draft' | 'testing' | 'published';
  createTime: string;
  updateTime: string;
}

const applicationTemplates: ApplicationTemplate[] = [
  {
    id: 'irrigation',
    name: '智能灌溉策略',
    icon: Droplets,
    description: '基于土壤湿度、天气预报和作物需水规律，自动生成精准灌溉计划',
    category: '水肥管理',
    features: ['实时土壤监测', '天气预报集成', '作物需水模型', '灌溉计划优化'],
    defaultInputs: [
      { id: 'soil_moisture', name: '土壤湿度', type: 'number', source: 'sensor', required: true, unit: '%', range: { min: 0, max: 100 } },
      { id: 'temperature', name: '环境温度', type: 'number', source: 'sensor', required: true, unit: '°C', range: { min: -10, max: 50 } },
      { id: 'crop_stage', name: '作物生长阶段', type: 'select', source: 'manual', required: true, options: ['苗期', '生长期', '开花期', '结果期'] },
      { id: 'field_area', name: '地块面积', type: 'number', source: 'database', required: true, unit: '亩' },
    ],
    defaultOutputs: [
      { id: 'irrigation_amount', name: '建议灌溉量', type: 'number', format: '升', destination: 'display' },
      { id: 'irrigation_time', name: '最佳灌溉时间', type: 'text', format: '时间', destination: 'display' },
      { id: 'irrigation_duration', name: '灌溉持续时间', type: 'number', format: '分钟', destination: 'display' },
      { id: 'alert', name: '缺水预警', type: 'alert', format: '通知', destination: 'notification', condition: 'soil_moisture < 30' },
    ],
    sampleTriggers: ['每天早上6点检测', '土壤湿度低于30%时', '天气预报有降雨前'],
    complexity: 'medium',
    estimatedTime: '10-15分钟',
  },
  {
    id: 'pest',
    name: '病虫害预警提示',
    icon: Bug,
    description: '通过图像识别和环境监测，及时发现并预警病虫害风险',
    category: '病虫害防控',
    features: ['图像识别', '环境监测', '风险评估', '防治建议'],
    defaultInputs: [
      { id: 'image', name: '作物图像', type: 'text', source: 'manual', required: true },
      { id: 'temperature', name: '环境温度', type: 'number', source: 'sensor', required: true, unit: '°C' },
      { id: 'humidity', name: '环境湿度', type: 'number', source: 'sensor', required: true, unit: '%' },
      { id: 'crop_type', name: '作物类型', type: 'select', source: 'manual', required: true, options: ['小麦', '玉米', '水稻', '番茄'] },
    ],
    defaultOutputs: [
      { id: 'pest_type', name: '病虫害类型', type: 'text', format: '文本', destination: 'display' },
      { id: 'risk_level', name: '风险等级', type: 'text', format: '等级', destination: 'display' },
      { id: 'confidence', name: '识别置信度', type: 'number', format: '百分比', destination: 'display' },
      { id: 'treatment', name: '防治建议', type: 'text', format: '文本', destination: 'display' },
      { id: 'alert', name: '高风险预警', type: 'alert', format: '通知', destination: 'notification', condition: 'risk_level == "高"' },
    ],
    sampleTriggers: ['每周定期检测', '温湿度异常时', '人工上传图像时'],
    complexity: 'complex',
    estimatedTime: '15-20分钟',
  },
  {
    id: 'fertilizer',
    name: '施肥方案推荐',
    icon: Sprout,
    description: '根据土壤养分、作物需求和生长阶段，智能推荐施肥方案',
    category: '水肥管理',
    features: ['土壤养分分析', '作物需肥模型', '配方优化', '成本控制'],
    defaultInputs: [
      { id: 'soil_n', name: '土壤氮含量', type: 'number', source: 'sensor', required: true, unit: 'mg/kg' },
      { id: 'soil_p', name: '土壤磷含量', type: 'number', source: 'sensor', required: true, unit: 'mg/kg' },
      { id: 'soil_k', name: '土壤钾含量', type: 'number', source: 'sensor', required: true, unit: 'mg/kg' },
      { id: 'crop_stage', name: '作物生长阶段', type: 'select', source: 'manual', required: true, options: ['苗期', '生长期', '开花期', '结果期'] },
      { id: 'target_yield', name: '目标产量', type: 'number', source: 'manual', required: false, unit: '公斤/亩' },
    ],
    defaultOutputs: [
      { id: 'n_amount', name: '氮肥用量', type: 'number', format: '公斤/亩', destination: 'display' },
      { id: 'p_amount', name: '磷肥用量', type: 'number', format: '公斤/亩', destination: 'display' },
      { id: 'k_amount', name: '钾肥用量', type: 'number', format: '公斤/亩', destination: 'display' },
      { id: 'formula', name: '肥料配方', type: 'text', format: 'NPK比例', destination: 'display' },
      { id: 'cost_estimate', name: '成本估算', type: 'number', format: '元', destination: 'display' },
    ],
    sampleTriggers: ['每月定期检测', '生长阶段变化时', '土壤养分低于阈值时'],
    complexity: 'medium',
    estimatedTime: '10-15分钟',
  },
  {
    id: 'yield',
    name: '产量预测分析',
    icon: TrendingUp,
    description: '综合历史数据、气象条件和作物长势，预测产量和收获时间',
    category: '生产决策',
    features: ['历史数据分析', '气象预测', '长势监测', '收获时间预测'],
    defaultInputs: [
      { id: 'crop_type', name: '作物类型', type: 'select', source: 'manual', required: true, options: ['小麦', '玉米', '水稻', '番茄'] },
      { id: 'planting_date', name: '种植日期', type: 'date', source: 'database', required: true },
      { id: 'field_area', name: '地块面积', type: 'number', source: 'database', required: true, unit: '亩' },
      { id: 'ndvi', name: '植被指数NDVI', type: 'number', source: 'sensor', required: false, range: { min: 0, max: 1 } },
      { id: 'weather_score', name: '天气评分', type: 'number', source: 'api', required: false, range: { min: 0, max: 100 } },
    ],
    defaultOutputs: [
      { id: 'yield_estimate', name: '预测产量', type: 'number', format: '公斤/亩', destination: 'display' },
      { id: 'total_yield', name: '总产量', type: 'number', format: '公斤', destination: 'display' },
      { id: 'harvest_date', name: '预计收获日期', type: 'date', format: '日期', destination: 'display' },
      { id: 'confidence', name: '预测置信度', type: 'number', format: '百分比', destination: 'display' },
      { id: 'quality_grade', name: '品质等级', type: 'text', format: '等级', destination: 'display' },
    ],
    sampleTriggers: ['每周更新预测', '生长关键期', '气象条件剧变时'],
    complexity: 'complex',
    estimatedTime: '15-20分钟',
  },
  {
    id: 'growth',
    name: '生长状态监测',
    icon: Activity,
    description: '实时监测作物生长指标，及时发现异常并提供改善建议',
    category: '生产监测',
    features: ['多指标监测', '异常检测', '趋势分析', '改善建议'],
    defaultInputs: [
      { id: 'plant_height', name: '株高', type: 'number', source: 'sensor', required: true, unit: 'cm' },
      { id: 'leaf_area', name: '叶面积指数', type: 'number', source: 'sensor', required: false },
      { id: 'chlorophyll', name: '叶绿素含量', type: 'number', source: 'sensor', required: false },
      { id: 'growth_days', name: '生长天数', type: 'number', source: 'database', required: true },
    ],
    defaultOutputs: [
      { id: 'growth_status', name: '生长状态', type: 'text', format: '状态', destination: 'display' },
      { id: 'health_score', name: '健康评分', type: 'number', format: '分数', destination: 'display' },
      { id: 'anomaly', name: '异常项', type: 'text', format: '列表', destination: 'display' },
      { id: 'suggestions', name: '改善建议', type: 'text', format: '文本', destination: 'display' },
      { id: 'alert', name: '异常预警', type: 'alert', format: '通知', destination: 'notification', condition: 'health_score < 60' },
    ],
    sampleTriggers: ['每天监测', '生长指标异常时', '定期评估'],
    complexity: 'simple',
    estimatedTime: '8-12分钟',
  },
  {
    id: 'weather',
    name: '气象灾害预警',
    icon: Thermometer,
    description: '结合气象预报和作物特性，提前预警灾害性天气风险',
    category: '风险管理',
    features: ['气象预报', '风险评估', '灾害预警', '应对建议'],
    defaultInputs: [
      { id: 'temperature_forecast', name: '温度预报', type: 'number', source: 'api', required: true, unit: '°C' },
      { id: 'rainfall_forecast', name: '降雨预报', type: 'number', source: 'api', required: true, unit: 'mm' },
      { id: 'wind_speed', name: '风速预报', type: 'number', source: 'api', required: true, unit: 'm/s' },
      { id: 'crop_stage', name: '作物生长阶段', type: 'select', source: 'manual', required: true, options: ['苗期', '生长期', '开花期', '结果期'] },
    ],
    defaultOutputs: [
      { id: 'risk_type', name: '灾害类型', type: 'text', format: '类型', destination: 'display' },
      { id: 'risk_level', name: '风险等级', type: 'text', format: '等级', destination: 'display' },
      { id: 'impact_time', name: '影响时间', type: 'text', format: '时间范围', destination: 'display' },
      { id: 'countermeasures', name: '应对措施', type: 'text', format: '文本', destination: 'display' },
      { id: 'alert', name: '高风险预警', type: 'alert', format: '通知', destination: 'notification', condition: 'risk_level == "高"' },
    ],
    sampleTriggers: ['每6小时检测', '气象预警发布时', '极端天气预报时'],
    complexity: 'medium',
    estimatedTime: '10-15分钟',
  },
  {
    id: 'custom',
    name: '自定义应用',
    icon: Wand2,
    description: '从零开始构建自定义应用，完全自由配置',
    category: '自定义',
    features: ['自由配置', '灵活扩展', '模板保存', '代码生成'],
    defaultInputs: [],
    defaultOutputs: [],
    sampleTriggers: ['自定义触发条件'],
    complexity: 'complex',
    estimatedTime: '20-30分钟',
  },
];

// 已接入的模型服务（模拟数据）
const availableModels = [
  { id: 'model_1', name: '番茄生长预测模型', type: '作物生长预测', version: 'v2.3.1', accuracy: 94.5 },
  { id: 'model_2', name: '病虫害识别模型', type: '病虫害识别', version: 'v1.8.2', accuracy: 92.3 },
  { id: 'model_3', name: '土壤养分分析模型', type: '土壤分析', version: 'v3.1.0', accuracy: 96.7 },
  { id: 'model_4', name: '产量预测模型', type: '产量预估', version: 'v2.0.5', accuracy: 89.2 },
  { id: 'model_5', name: '灌溉决策模型', type: '灌溉优化', version: 'v1.5.3', accuracy: 91.8 },
];

export function AIApplicationGeneration({ activePath }: AIApplicationGenerationProps) {
  const [currentStep, setCurrentStep] = useState(1);
  const [selectedTemplate, setSelectedTemplate] = useState<TemplateType | null>(null);
  const [selectedModel, setSelectedModel] = useState<string>('');
  const [appName, setAppName] = useState('');
  const [appDescription, setAppDescription] = useState('');
  const [inputFields, setInputFields] = useState<InputField[]>([]);
  const [outputFields, setOutputFields] = useState<OutputField[]>([]);
  const [triggers, setTriggers] = useState<TriggerCondition[]>([]);
  const [showPreview, setShowPreview] = useState(false);
  const [showPublishDialog, setShowPublishDialog] = useState(false);
  const [generatedApps, setGeneratedApps] = useState<GeneratedApplication[]>([]);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [editingField, setEditingField] = useState<InputField | OutputField | null>(null);
  const [editType, setEditType] = useState<'input' | 'output'>('input');

  const handleTemplateSelect = (templateId: TemplateType) => {
    setSelectedTemplate(templateId);
    const template = applicationTemplates.find(t => t.id === templateId);
    if (template) {
      setAppName(template.name);
      setAppDescription(template.description);
      setInputFields([...template.defaultInputs]);
      setOutputFields([...template.defaultOutputs]);
      
      // 设置默认触发器
      if (template.sampleTriggers.length > 0) {
        setTriggers([
          {
            id: 'trigger_1',
            type: 'time',
            config: { schedule: template.sampleTriggers[0] },
            enabled: true,
          },
        ]);
      }
    }
    setCurrentStep(2);
  };

  const handleAddInputField = () => {
    const newField: InputField = {
      id: `input_${inputFields.length + 1}`,
      name: '',
      type: 'number',
      source: 'manual',
      required: false,
    };
    setEditingField(newField);
    setEditType('input');
    setShowEditDialog(true);
  };

  const handleAddOutputField = () => {
    const newField: OutputField = {
      id: `output_${outputFields.length + 1}`,
      name: '',
      type: 'number',
      format: '',
      destination: 'display',
    };
    setEditingField(newField);
    setEditType('output');
    setShowEditDialog(true);
  };

  const handleSaveField = () => {
    if (editType === 'input' && editingField) {
      const existingIndex = inputFields.findIndex(f => f.id === editingField.id);
      if (existingIndex >= 0) {
        const newInputs = [...inputFields];
        newInputs[existingIndex] = editingField as InputField;
        setInputFields(newInputs);
      } else {
        setInputFields([...inputFields, editingField as InputField]);
      }
    } else if (editType === 'output' && editingField) {
      const existingIndex = outputFields.findIndex(f => f.id === editingField.id);
      if (existingIndex >= 0) {
        const newOutputs = [...outputFields];
        newOutputs[existingIndex] = editingField as OutputField;
        setOutputFields(newOutputs);
      } else {
        setOutputFields([...outputFields, editingField as OutputField]);
      }
    }
    setShowEditDialog(false);
    setEditingField(null);
  };

  const handleDeleteInputField = (id: string) => {
    setInputFields(inputFields.filter(f => f.id !== id));
    toast.success('输入字段已删除');
  };

  const handleDeleteOutputField = (id: string) => {
    setOutputFields(outputFields.filter(f => f.id !== id));
    toast.success('输出字段已删除');
  };

  const handleAddTrigger = () => {
    const newTrigger: TriggerCondition = {
      id: `trigger_${triggers.length + 1}`,
      type: 'time',
      config: { schedule: '每天 00:00' },
      enabled: true,
    };
    setTriggers([...triggers, newTrigger]);
  };

  const handleDeleteTrigger = (id: string) => {
    setTriggers(triggers.filter(t => t.id !== id));
    toast.success('触发条件已删除');
  };

  const handleTestApplication = () => {
    toast.success('应用测试成功！所有配置正常工作');
  };

  const handlePublishApplication = () => {
    if (!selectedTemplate || !selectedModel || !appName) {
      toast.error('请完成所有必填配置');
      return;
    }

    const newApp: GeneratedApplication = {
      id: `app_${Date.now()}`,
      name: appName,
      template: selectedTemplate,
      modelId: selectedModel,
      modelName: availableModels.find(m => m.id === selectedModel)?.name || '',
      inputs: inputFields,
      outputs: outputFields,
      triggers: triggers,
      logicNodes: [],
      status: 'published',
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
    };

    setGeneratedApps([...generatedApps, newApp]);
    setShowPublishDialog(false);
    toast.success('应用已成功发布！');
    
    // 重置表单
    resetForm();
  };

  const resetForm = () => {
    setCurrentStep(1);
    setSelectedTemplate(null);
    setSelectedModel('');
    setAppName('');
    setAppDescription('');
    setInputFields([]);
    setOutputFields([]);
    setTriggers([]);
  };

  const getStepStatus = (step: number) => {
    if (step < currentStep) return 'completed';
    if (step === currentStep) return 'current';
    return 'upcoming';
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-accent-muted to-info-muted border-accent">
        <div className="flex items-start gap-3">
          <Wand2 className="w-6 h-6 text-accent-foreground flex-shrink-0 mt-1" />
          <div className="flex-1">
            <h2 className="mb-2">应用生成功能</h2>
            <p className="text-sm text-muted-foreground mb-3">
              通过可视化配置或模板化方式，快速生成面向具体生产业务的智能应用模块
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <Workflow className="w-3 h-3 mr-1" />
                可视化配置
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Layers className="w-3 h-3 mr-1" />
                模板化生成
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Code className="w-3 h-3 mr-1" />
                业务逻辑编排
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Zap className="w-3 h-3 mr-1" />
                一键部署
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      <Tabs value="generator" className="space-y-4">
        <TabsList>
          <TabsTrigger value="generator">
            <Wand2 className="w-4 h-4 mr-2" />
            应用生成器
          </TabsTrigger>
          <TabsTrigger value="my-apps">
            <Package className="w-4 h-4 mr-2" />
            我的应用
          </TabsTrigger>
        </TabsList>

        {/* 应用生成器 */}
        <TabsContent value="generator" className="space-y-6">
          {/* 步骤指示器 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              {[
                { num: 1, label: '选择模板' },
                { num: 2, label: '选择模型' },
                { num: 3, label: '配置输入' },
                { num: 4, label: '配置输出' },
                { num: 5, label: '设置触发' },
                { num: 6, label: '预览发布' },
              ].map((step, idx) => (
                <div key={step.num} className="flex items-center flex-1">
                  <div className="flex flex-col items-center flex-1">
                    <div
                      className={`w-10 h-10 rounded-full flex items-center justify-center mb-2 ${
                        getStepStatus(step.num) === 'completed'
                          ? 'bg-success text-success-foreground'
                          : getStepStatus(step.num) === 'current'
                          ? 'bg-primary text-primary-foreground'
                          : 'bg-muted text-muted-foreground'
                      }`}
                    >
                      {getStepStatus(step.num) === 'completed' ? (
                        <CheckCircle className="w-5 h-5" />
                      ) : (
                        <span>{step.num}</span>
                      )}
                    </div>
                    <div className="text-xs text-center">{step.label}</div>
                  </div>
                  {idx < 5 && (
                    <div
                      className={`h-0.5 flex-1 ${
                        getStepStatus(step.num + 1) !== 'upcoming' ? 'bg-success' : 'bg-muted'
                      }`}
                    />
                  )}
                </div>
              ))}
            </div>
          </Card>

          {/* 步骤1: 选择模板 */}
          {currentStep === 1 && (
            <Card className="p-6">
              <h3 className="mb-4">选择应用模板</h3>
              <div className="grid grid-cols-2 gap-4">
                {applicationTemplates.map((template) => {
                  const Icon = template.icon;
                  return (
                    <Card
                      key={template.id}
                      className={`p-6 cursor-pointer transition-all hover:shadow-lg ${
                        selectedTemplate === template.id
                          ? 'border-2 border-primary bg-primary-muted'
                          : 'hover:border-primary/50'
                      }`}
                      onClick={() => handleTemplateSelect(template.id)}
                    >
                      <div className="flex items-start gap-4">
                        <div className={`w-12 h-12 rounded-lg flex items-center justify-center ${
                          template.id === 'irrigation' ? 'bg-info-muted' :
                          template.id === 'pest' ? 'bg-error-muted' :
                          template.id === 'fertilizer' ? 'bg-success-muted' :
                          template.id === 'yield' ? 'bg-warning-muted' :
                          template.id === 'growth' ? 'bg-success-muted' :
                          template.id === 'weather' ? 'bg-info-muted' :
                          'bg-accent-muted'
                        }`}>
                          <Icon className={`w-6 h-6 ${
                            template.id === 'irrigation' ? 'text-info' :
                            template.id === 'pest' ? 'text-error' :
                            template.id === 'fertilizer' ? 'text-success' :
                            template.id === 'yield' ? 'text-warning' :
                            template.id === 'growth' ? 'text-success' :
                            template.id === 'weather' ? 'text-info' :
                            'text-accent-foreground'
                          }`} />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-start justify-between mb-2">
                            <h4>{template.name}</h4>
                            <Badge variant="outline" className="ml-2">
                              {template.category}
                            </Badge>
                          </div>
                          <p className="text-sm text-muted-foreground mb-3">
                            {template.description}
                          </p>
                          <div className="flex flex-wrap gap-1 mb-3">
                            {template.features.slice(0, 3).map((feature, idx) => (
                              <Badge key={idx} variant="secondary" className="text-xs">
                                {feature}
                              </Badge>
                            ))}
                          </div>
                          <div className="flex items-center justify-between text-xs text-muted-foreground">
                            <div className="flex items-center gap-1">
                              <Clock className="w-3 h-3" />
                              {template.estimatedTime}
                            </div>
                            <div className="flex items-center gap-1">
                              {template.complexity === 'simple' ? (
                                <Badge variant="outline" className="text-success border-success">
                                  简单
                                </Badge>
                              ) : template.complexity === 'medium' ? (
                                <Badge variant="outline" className="text-warning border-warning">
                                  中等
                                </Badge>
                              ) : (
                                <Badge variant="outline" className="text-destructive border-destructive">
                                  复杂
                                </Badge>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    </Card>
                  );
                })}
              </div>
            </Card>
          )}

          {/* 步骤2: 选择模型 */}
          {currentStep === 2 && (
            <Card className="p-6">
              <h3 className="mb-4">选择AI模型</h3>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>应用名称</Label>
                    <Input
                      value={appName}
                      onChange={(e) => setAppName(e.target.value)}
                      placeholder="输入应用名称"
                    />
                  </div>
                  <div>
                    <Label>选择模型</Label>
                    <Select value={selectedModel} onValueChange={setSelectedModel}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择一个AI模型" />
                      </SelectTrigger>
                      <SelectContent>
                        {availableModels.map((model) => (
                          <SelectItem key={model.id} value={model.id}>
                            <div className="flex items-center justify-between gap-4">
                              <span>{model.name}</span>
                              <Badge variant="outline">{model.version}</Badge>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                
                <div>
                  <Label>应用描述</Label>
                  <Textarea
                    value={appDescription}
                    onChange={(e) => setAppDescription(e.target.value)}
                    placeholder="描述应用的功能和用途"
                    rows={3}
                  />
                </div>

                {selectedModel && (
                  <Card className="p-4 bg-info/10 border-info/30">
                    <div className="flex items-start gap-3">
                      <Brain className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
                      <div>
                        <h4 className="mb-2">所选模型信息</h4>
                        {(() => {
                          const model = availableModels.find(m => m.id === selectedModel);
                          if (!model) return null;
                          return (
                            <div className="grid grid-cols-3 gap-4 text-sm">
                              <div>
                                <span className="text-muted-foreground">模型名称：</span>
                                <span>{model.name}</span>
                              </div>
                              <div>
                                <span className="text-muted-foreground">模型类型：</span>
                                <span>{model.type}</span>
                              </div>
                              <div>
                                <span className="text-muted-foreground">准确率：</span>
                                <span>{model.accuracy}%</span>
                              </div>
                            </div>
                          );
                        })()}
                      </div>
                    </div>
                  </Card>
                )}

                <div className="flex gap-3">
                  <Button variant="outline" onClick={() => setCurrentStep(1)}>
                    上一步
                  </Button>
                  <Button
                    onClick={() => setCurrentStep(3)}
                    disabled={!selectedModel || !appName}
                    className="bg-accent hover:bg-accent/90"
                  >
                    下一步
                  </Button>
                </div>
              </div>
            </Card>
          )}

          {/* 步骤3: 配置输入 */}
          {currentStep === 3 && (
            <Card className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h3>配置输入字段</h3>
                <Button size="sm" onClick={handleAddInputField}>
                  <Plus className="w-4 h-4 mr-2" />
                  添加字段
                </Button>
              </div>

              {inputFields.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  <Database className="w-12 h-12 mx-auto mb-3 opacity-50" />
                  <p>暂无输入字段，点击上方按钮添加</p>
                </div>
              ) : (
                <div className="space-y-3 mb-6">
                  {inputFields.map((field) => (
                    <Card key={field.id} className="p-4 hover:shadow-md transition-shadow">
                      <div className="flex items-start justify-between">
                        <div className="flex-1 grid grid-cols-4 gap-4">
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">字段名称</div>
                            <div className="font-medium">{field.name || '未命名'}</div>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">字段类型</div>
                            <Badge variant="outline">{field.type}</Badge>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">数据来源</div>
                            <Badge variant="outline">{field.source}</Badge>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">是否必填</div>
                            <Badge variant={field.required ? 'default' : 'secondary'}>
                              {field.required ? '必填' : '可选'}
                            </Badge>
                          </div>
                        </div>
                        <div className="flex gap-2 ml-4">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => {
                              setEditingField(field);
                              setEditType('input');
                              setShowEditDialog(true);
                            }}
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => handleDeleteInputField(field.id)}
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              )}

              <div className="flex gap-3">
                <Button variant="outline" onClick={() => setCurrentStep(2)}>
                  上一步
                </Button>
                <Button
                  onClick={() => setCurrentStep(4)}
                  disabled={inputFields.length === 0}
                  className="bg-accent hover:bg-accent/90"
                >
                  下一步
                </Button>
              </div>
            </Card>
          )}

          {/* 步骤4: 配置输出 */}
          {currentStep === 4 && (
            <Card className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h3>配置输出字段</h3>
                <Button size="sm" onClick={handleAddOutputField}>
                  <Plus className="w-4 h-4 mr-2" />
                  添加字段
                </Button>
              </div>

              {outputFields.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  <FileCode className="w-12 h-12 mx-auto mb-3 opacity-50" />
                  <p>暂无输出字段，点击上方按钮添加</p>
                </div>
              ) : (
                <div className="space-y-3 mb-6">
                  {outputFields.map((field) => (
                    <Card key={field.id} className="p-4 hover:shadow-md transition-shadow">
                      <div className="flex items-start justify-between">
                        <div className="flex-1 grid grid-cols-4 gap-4">
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">字段名称</div>
                            <div className="font-medium">{field.name || '未命名'}</div>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">字段类型</div>
                            <Badge variant="outline">{field.type}</Badge>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">输出格式</div>
                            <div className="text-sm">{field.format || '-'}</div>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">输出目标</div>
                            <Badge variant="outline">{field.destination}</Badge>
                          </div>
                        </div>
                        <div className="flex gap-2 ml-4">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => {
                              setEditingField(field);
                              setEditType('output');
                              setShowEditDialog(true);
                            }}
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => handleDeleteOutputField(field.id)}
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              )}

              <div className="flex gap-3">
                <Button variant="outline" onClick={() => setCurrentStep(3)}>
                  上一步
                </Button>
                <Button
                  onClick={() => setCurrentStep(5)}
                  disabled={outputFields.length === 0}
                  className="bg-accent hover:bg-accent/90"
                >
                  下一步
                </Button>
              </div>
            </Card>
          )}

          {/* 步骤5: 设置触发条件 */}
          {currentStep === 5 && (
            <Card className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h3>设置触发条件</h3>
                <Button size="sm" onClick={handleAddTrigger}>
                  <Plus className="w-4 h-4 mr-2" />
                  添加触发器
                </Button>
              </div>

              {triggers.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  <Bell className="w-12 h-12 mx-auto mb-3 opacity-50" />
                  <p>暂无触发条件，点击上方按钮添加</p>
                </div>
              ) : (
                <div className="space-y-3 mb-6">
                  {triggers.map((trigger) => (
                    <Card key={trigger.id} className="p-4 hover:shadow-md transition-shadow">
                      <div className="flex items-center justify-between">
                        <div className="flex-1 grid grid-cols-3 gap-4">
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">触发类型</div>
                            <Select defaultValue={trigger.type}>
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="time">定时触发</SelectItem>
                                <SelectItem value="event">事件触发</SelectItem>
                                <SelectItem value="threshold">阈值触发</SelectItem>
                                <SelectItem value="manual">手动触发</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">触发配置</div>
                            <Input
                              defaultValue={trigger.config.schedule || ''}
                              placeholder="如：每天 08:00"
                            />
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">启用状态</div>
                            <div className="flex items-center gap-2 h-10">
                              <Switch defaultChecked={trigger.enabled} />
                              <span className="text-sm">{trigger.enabled ? '已启用' : '已禁用'}</span>
                            </div>
                          </div>
                        </div>
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => handleDeleteTrigger(trigger.id)}
                          className="ml-4"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </Card>
                  ))}
                </div>
              )}

              <div className="flex gap-3">
                <Button variant="outline" onClick={() => setCurrentStep(4)}>
                  上一步
                </Button>
                <Button
                  onClick={() => setCurrentStep(6)}
                  disabled={triggers.length === 0}
                  className="bg-accent hover:bg-accent/90"
                >
                  下一步
                </Button>
              </div>
            </Card>
          )}

          {/* 步骤6: 预览和发布 */}
          {currentStep === 6 && (
            <div className="space-y-4">
              <Card className="p-6">
                <h3 className="mb-4">应用配置预览</h3>
                <div className="grid grid-cols-2 gap-6">
                  <div>
                    <h4 className="mb-3">基本信息</h4>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">应用名称：</span>
                        <span>{appName}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">应用模板：</span>
                        <span>
                          {applicationTemplates.find(t => t.id === selectedTemplate)?.name}
                        </span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">关联模型：</span>
                        <span>
                          {availableModels.find(m => m.id === selectedModel)?.name}
                        </span>
                      </div>
                    </div>
                  </div>

                  <div>
                    <h4 className="mb-3">配置统计</h4>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">输入字段：</span>
                        <Badge>{inputFields.length} 个</Badge>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">输出字段：</span>
                        <Badge>{outputFields.length} 个</Badge>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">触发条件：</span>
                        <Badge>{triggers.length} 个</Badge>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              <Card className="p-6">
                <h4 className="mb-3">数据流向图</h4>
                <div className="p-8 bg-muted rounded-lg">
                  <div className="flex items-center justify-between">
                    <div className="text-center">
                      <div className="w-24 h-24 bg-info-muted rounded-lg flex items-center justify-center mx-auto mb-2">
                        <Database className="w-12 h-12 text-info" />
                      </div>
                      <div className="text-sm font-medium">数据输入</div>
                      <div className="text-xs text-muted-foreground">{inputFields.length} 个字段</div>
                    </div>
                    <div className="flex-1 flex items-center justify-center">
                      <div className="w-full h-0.5 bg-border relative">
                        <div className="absolute right-0 top-1/2 -translate-y-1/2 w-3 h-3 border-t-2 border-r-2 border-border rotate-45" />
                      </div>
                    </div>
                    <div className="text-center">
                      <div className="w-24 h-24 bg-accent-muted rounded-lg flex items-center justify-center mx-auto mb-2">
                        <Brain className="w-12 h-12 text-accent" />
                      </div>
                      <div className="text-sm font-medium">AI模型</div>
                      <div className="text-xs text-muted-foreground">推理处理</div>
                    </div>
                    <div className="flex-1 flex items-center justify-center">
                      <div className="w-full h-0.5 bg-border relative">
                        <div className="absolute right-0 top-1/2 -translate-y-1/2 w-3 h-3 border-t-2 border-r-2 border-border rotate-45" />
                      </div>
                    </div>
                    <div className="text-center">
                      <div className="w-24 h-24 bg-success-muted rounded-lg flex items-center justify-center mx-auto mb-2">
                        <FileCode className="w-12 h-12 text-success" />
                      </div>
                      <div className="text-sm font-medium">结果输出</div>
                      <div className="text-xs text-muted-foreground">{outputFields.length} 个字段</div>
                    </div>
                  </div>
                </div>
              </Card>

              <div className="flex gap-3">
                <Button variant="outline" onClick={() => setCurrentStep(5)}>
                  上一步
                </Button>
                <Button variant="outline" onClick={handleTestApplication}>
                  <Play className="w-4 h-4 mr-2" />
                  测试应用
                </Button>
                <Button
                  onClick={() => setShowPublishDialog(true)}
                  className="bg-success hover:bg-success/90"
                >
                  <CheckCircle className="w-4 h-4 mr-2" />
                  发布应用
                </Button>
              </div>
            </div>
          )}
        </TabsContent>

        {/* 我的应用 */}
        <TabsContent value="my-apps">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>已生成的应用</h3>
              <div className="flex gap-2">
                <Button size="sm" variant="outline">
                  <Filter className="w-4 h-4 mr-2" />
                  筛选
                </Button>
                <Button size="sm" variant="outline">
                  <Download className="w-4 h-4 mr-2" />
                  导出
                </Button>
              </div>
            </div>

            {generatedApps.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <Package className="w-16 h-16 mx-auto mb-4 opacity-50" />
                <p className="mb-2">暂无已生成的应用</p>
                <p className="text-sm">使用应用生成器创建您的第一个应用</p>
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-4">
                {generatedApps.map((app) => {
                  const template = applicationTemplates.find(t => t.id === app.template);
                  const Icon = template?.icon || Package;
                  return (
                    <Card key={app.id} className="p-6 hover:shadow-lg transition-shadow">
                      <div className="flex items-start gap-4">
                        <div className="w-12 h-12 bg-accent-muted rounded-lg flex items-center justify-center flex-shrink-0">
                          <Icon className="w-6 h-6 text-accent" />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-start justify-between mb-2">
                            <h4>{app.name}</h4>
                            <Badge
                              variant={
                                app.status === 'published'
                                  ? 'default'
                                  : app.status === 'testing'
                                  ? 'secondary'
                                  : 'outline'
                              }
                            >
                              {app.status === 'published'
                                ? '已发布'
                                : app.status === 'testing'
                                ? '测试中'
                                : '草稿'}
                            </Badge>
                          </div>
                          <div className="text-sm text-muted-foreground mb-3">
                            {template?.description}
                          </div>
                          <div className="grid grid-cols-2 gap-2 text-xs mb-3">
                            <div>
                              <span className="text-muted-foreground">模型：</span>
                              {app.modelName}
                            </div>
                            <div>
                              <span className="text-muted-foreground">创建时间：</span>
                              {new Date(app.createTime).toLocaleDateString()}
                            </div>
                          </div>
                          <div className="flex gap-2">
                            <Button size="sm" variant="outline">
                              <Eye className="w-3 h-3 mr-1" />
                              查看
                            </Button>
                            <Button size="sm" variant="outline">
                              <Edit className="w-3 h-3 mr-1" />
                              编辑
                            </Button>
                            <Button size="sm" variant="outline">
                              <Copy className="w-3 h-3 mr-1" />
                              复制
                            </Button>
                          </div>
                        </div>
                      </div>
                    </Card>
                  );
                })}
              </div>
            )}
          </Card>
        </TabsContent>
      </Tabs>

      {/* 字段编辑对话框 */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {editType === 'input' ? '编辑输入字段' : '编辑输出字段'}
            </DialogTitle>
            <DialogDescription>
              配置字段的详细信息
            </DialogDescription>
          </DialogHeader>

          {editingField && editType === 'input' && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>字段名称</Label>
                  <Input
                    value={(editingField as InputField).name}
                    onChange={(e) =>
                      setEditingField({ ...editingField, name: e.target.value })
                    }
                    placeholder="如：土壤湿度"
                  />
                </div>
                <div>
                  <Label>字段类型</Label>
                  <Select
                    value={(editingField as InputField).type}
                    onValueChange={(value) =>
                      setEditingField({
                        ...editingField,
                        type: value as InputField['type'],
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="number">数字</SelectItem>
                      <SelectItem value="text">文本</SelectItem>
                      <SelectItem value="date">日期</SelectItem>
                      <SelectItem value="boolean">布尔值</SelectItem>
                      <SelectItem value="select">下拉选择</SelectItem>
                      <SelectItem value="sensor">传感器</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>数据来源</Label>
                  <Select
                    value={(editingField as InputField).source}
                    onValueChange={(value) =>
                      setEditingField({
                        ...editingField,
                        source: value as InputField['source'],
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="manual">手动输入</SelectItem>
                      <SelectItem value="sensor">传感器</SelectItem>
                      <SelectItem value="database">数据库</SelectItem>
                      <SelectItem value="api">API接口</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>单位</Label>
                  <Input
                    value={(editingField as InputField).unit || ''}
                    onChange={(e) =>
                      setEditingField({ ...editingField, unit: e.target.value })
                    }
                    placeholder="如：%、°C"
                  />
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Switch
                  checked={(editingField as InputField).required}
                  onCheckedChange={(checked) =>
                    setEditingField({ ...editingField, required: checked })
                  }
                />
                <Label>必填字段</Label>
              </div>
            </div>
          )}

          {editingField && editType === 'output' && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>字段名称</Label>
                  <Input
                    value={(editingField as OutputField).name}
                    onChange={(e) =>
                      setEditingField({ ...editingField, name: e.target.value })
                    }
                    placeholder="如：建议灌溉量"
                  />
                </div>
                <div>
                  <Label>字段类型</Label>
                  <Select
                    value={(editingField as OutputField).type}
                    onValueChange={(value) =>
                      setEditingField({
                        ...editingField,
                        type: value as OutputField['type'],
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="number">数字</SelectItem>
                      <SelectItem value="text">文本</SelectItem>
                      <SelectItem value="boolean">布尔值</SelectItem>
                      <SelectItem value="json">JSON</SelectItem>
                      <SelectItem value="alert">告警</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>输出格式</Label>
                  <Input
                    value={(editingField as OutputField).format}
                    onChange={(e) =>
                      setEditingField({ ...editingField, format: e.target.value })
                    }
                    placeholder="如：升、分钟"
                  />
                </div>
                <div>
                  <Label>输出目标</Label>
                  <Select
                    value={(editingField as OutputField).destination}
                    onValueChange={(value) =>
                      setEditingField({
                        ...editingField,
                        destination: value as OutputField['destination'],
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="display">显示</SelectItem>
                      <SelectItem value="database">数据库</SelectItem>
                      <SelectItem value="notification">通知</SelectItem>
                      <SelectItem value="api">API</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              {(editingField as OutputField).type === 'alert' && (
                <div>
                  <Label>触发条件</Label>
                  <Input
                    value={(editingField as OutputField).condition || ''}
                    onChange={(e) =>
                      setEditingField({ ...editingField, condition: e.target.value })
                    }
                    placeholder="如：soil_moisture < 30"
                  />
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSaveField} className="bg-accent hover:bg-accent/90">
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 发布确认对话框 */}
      <Dialog open={showPublishDialog} onOpenChange={setShowPublishDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认发布应用</DialogTitle>
            <DialogDescription>
              应用发布后将立即可用，确定要发布吗？
            </DialogDescription>
          </DialogHeader>

          <div className="p-4 bg-success/10 rounded-lg">
            <div className="flex items-start gap-3">
              <CheckCircle className="w-5 h-5 text-success flex-shrink-0 mt-0.5" />
              <div className="text-sm">
                <p className="font-medium text-success mb-1">应用配置检查通过</p>
                <ul className="space-y-1 text-success/90">
                  <li>✓ 已选择应用模板和AI模型</li>
                  <li>✓ 输入输出字段配置完整</li>
                  <li>✓ 触发条件设置正确</li>
                  <li>✓ 应用可以正常运行</li>
                </ul>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowPublishDialog(false)}>
              取消
            </Button>
            <Button onClick={handlePublishApplication} className="bg-success hover:bg-success/90">
              <CheckCircle className="w-4 h-4 mr-2" />
              确认发布
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
