/**
 * filekorolheader: 模型应用中心生成页面 - AI模型应用生成管理
 * 功能：应用生成、应用管理、应用运行、结果展示
 * 路径：/ai-crop-model/model-application/generation
 * 规范：遵循crop-x/docs/开发项目规范.md，使用useReducer状态管理，shadcn语义化样式
 */
'use client';

import { useReducer } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Rocket,
  Plus,
  CheckCircle,
  XCircle,
  AlertCircle,
  PlayCircle,
  PauseCircle,
  StopCircle,
  Eye,
  Edit,
  Clock,
  Zap,
  BarChart3,
  Activity,
  Droplets,
  Bug,
  Sprout,
  Terminal,
  FileText,
  Timer,
  TrendingUp,
  Server,
  Cpu,
  AlertTriangle,
  CheckCircle2,
  ChevronRight,
  ChevronLeft,
  Sparkles,
  Table as TableIcon,
  Type,
  PieChart as PieChartIcon,
  LineChart as LineChartIcon,
} from 'lucide-react';
import { toast } from 'sonner';
import {
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { ApplicationGenerationReducer, ApplicationGenerationState, ApplicationGenerationAction } from './components/ApplicationGenerationReducer';
import ApplicationGenerateDialog from './components/ApplicationGenerateDialog';
import ApplicationRunDialog from './components/ApplicationRunDialog';
import ApplicationList from './components/ApplicationList';
import ApplicationEditDialog from './components/ApplicationEditDialog';

export default function GenerationPage() {
  const [state, dispatch] = useReducer(ApplicationGenerationReducer, {
    applications: [
      {
        id: 'app-1',
        name: '智能灌溉策略生成',
        type: '智能灌溉',
        description: '基于土壤湿度、天气预报和作物需水模型，自动生成最优灌溉方案',
        modelName: '灌溉优化模型',
        modelVersion: 'v2.1.0',
        inputConfig: {
          fields: ['土壤湿度', '温度', '降水预报', '作物类型', '生长阶段'],
        },
        outputConfig: {
          format: '折线图',
        },
        status: '运行中',
        createTime: '2024-01-15',
        lastRunTime: '2024-03-20 14:30',
        runCount: 156,
        successRate: 98.5,
        avgExecutionTime: 2.3,
      },
      {
        id: 'app-2',
        name: '病虫害智能预警',
        type: '病虫害预警',
        description: '通过图像识别和环境数据分析，提前预警病虫害风险',
        modelName: '病虫害识别模型',
        modelVersion: 'v1.8.0',
        inputConfig: {
          fields: ['作物图像', '温度', '湿度', '叶片状况', '历史发病记录'],
        },
        outputConfig: {
          format: '饼状图',
        },
        status: '运行中',
        createTime: '2024-01-20',
        lastRunTime: '2024-03-20 16:45',
        runCount: 89,
        successRate: 96.2,
        avgExecutionTime: 1.8,
      },
      {
        id: 'app-3',
        name: '精准施肥推荐',
        type: '施肥推荐',
        description: '根据土壤养分和作物需求，生成精准施肥方案',
        modelName: '营养需求模型',
        modelVersion: 'v1.5.0',
        inputConfig: {
          fields: ['土壤养分', '作物类型', '生长阶段', '目标产量', '历史施肥记录'],
        },
        outputConfig: {
          format: '表格',
        },
        status: '已停止',
        createTime: '2024-02-01',
        lastRunTime: '2024-03-18 09:15',
        runCount: 45,
        successRate: 94.7,
        avgExecutionTime: 3.1,
      },
    ],
    showGenerateDialog: false,
    generateStep: 1,
    newAppData: {
      name: '',
      type: '',
      description: '',
      modelName: '',
      modelVersion: '',
      inputFields: [],
      outputFormat: '',
    },
    showRunDialog: false,
    runningApp: null,
    inputData: {},
    isRunning: false,
    runResult: null,
    showEditDialog: false,
    editingApp: null,
    editStep: 1,
    editAppData: {
      name: '',
      type: '',
      description: '',
      modelName: '',
      modelVersion: '',
      inputFields: [],
      outputFormat: '',
    },
    availableModels: [
      { id: 'm1', name: '灌溉优化模型', version: 'v2.1.0', type: 'TensorFlow', status: '运行中' },
      { id: 'm2', name: '病虫害识别模型', version: 'v1.8.0', type: 'PyTorch', status: '运行中' },
      { id: 'm3', name: '营养需求模型', version: 'v1.5.0', type: 'TensorFlow', status: '运行中' },
      { id: 'm4', name: '产量预测模型', version: 'v2.0.0', type: 'XGBoost', status: '运行中' },
      { id: 'm5', name: '生长监测模型', version: 'v1.3.0', type: 'PyTorch', status: '运行中' },
      { id: 'm6', name: '天气预测模型', version: 'v1.6.0', type: 'LSTM', status: '运行中' },
    ],
    inputFieldOptions: [
      '土壤湿度', '温度', '湿度', '光照强度', 'pH值', '电导率', '氮含量', '磷含量', '钾含量',
      '降水预报', '风速', '风向', '大气压力', '作物图像', '叶片状况', '株高', '叶面积指数',
      '作物类型', '生长阶段', '种植密度', '目标产量', '历史发病记录', '历史施肥记录', '土壤类型',
      '地理位置', '海拔高度', '坡度', '坡向', '土壤容重', '有机质含量', '微量元素含量',
      '病虫害图像', '虫害密度', '病情指数', '天敌数量', '农药使用记录', '施肥记录', '灌溉记录',
      '农事操作记录', '气象数据', '卫星遥感数据', '无人机影像数据', '传感器实时数据',
    ],
    dataSourceOptions: [
      '传感器实时数据',
      '数据库查询',
      '手动输入',
      '第三方API',
      '历史数据',
      '配置文件',
      'IoT设备',
      '气象站',
    ],
    iotDeviceOptions: [
      '土壤传感器01 (SN:SS-001)',
      '温湿度传感器02 (SN:TH-002)',
      '光照传感器03 (SN:LS-003)',
      'pH传感器04 (SN:PH-004)',
      '水肥一体机05 (SN:WF-005)',
      '气象站06 (SN:WS-006)',
      '作物图像采集器07 (SN:IC-007)',
      '水泵控制器08 (SN:PC-008)',
    ],
  });

  return (
    <div className="space-y-6">
      {/* 页面标题和描述 */}
      <Card className="p-6 bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200">
        <div className="flex items-center gap-3 mb-4">
          <Rocket className="w-8 h-8 text-blue-600" />
          <div>
            <h1 className="text-2xl font-bold text-blue-900">应用生成</h1>
            <p className="text-blue-700">AI模型应用生成与管理平台</p>
          </div>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">应用总数</p>
                <p className="mt-2 text-3xl text-blue-600">{state.applications.length}</p>
                <p className="text-xs text-blue-600 mt-1">已创建应用</p>
              </div>
              <Rocket className="w-12 h-12 text-blue-600 opacity-50" />
            </div>
          </Card>
          <Card className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">运行中</p>
                <p className="mt-2 text-3xl text-green-600">
                  {state.applications.filter(app => app.status === '运行中').length}
                </p>
                <p className="text-xs text-green-600 mt-1">正常运行</p>
              </div>
              <PlayCircle className="w-12 h-12 text-green-600 opacity-50" />
            </div>
          </Card>
          <Card className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">总执行次数</p>
                <p className="mt-2 text-3xl text-purple-600">
                  {state.applications.reduce((sum, app) => sum + app.runCount, 0)}
                </p>
                <p className="text-xs text-purple-600 mt-1">累计运行</p>
              </div>
              <Zap className="w-12 h-12 text-purple-600 opacity-50" />
            </div>
          </Card>
          <Card className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">成功率</p>
                <p className="mt-2 text-3xl text-orange-600">
                  {(state.applications.reduce((sum, app) => sum + app.successRate, 0) / state.applications.length).toFixed(1)}%
                </p>
                <p className="text-xs text-orange-600 mt-1">平均成功率</p>
              </div>
              <CheckCircle2 className="w-12 h-12 text-orange-600 opacity-50" />
            </div>
          </Card>
        </div>
      </Card>

      {/* 应用生成功能说明 */}
      <Card className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 dark:from-blue-950 dark:to-cyan-950 border-blue-200 dark:border-blue-800">
        <div className="flex items-start gap-2">
          <Rocket 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">应用生成功能：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>可视化配置</strong>: 通过配置化方式快速生成业务应用</li>
              <li>• <strong>灵活定制</strong>: 自定义输入字段与输出格式</li>
              <li>• <strong>多种输出</strong>: 支持折线图、饼状图、表格、文字等多种输出格式</li>
              <li>• <strong>场景融合</strong>: 实现AI模型与农业生产场景深度融合</li>
            </ul>
          </div>
        </div>
        <div className="mt-4">
          <Button
            onClick={() => dispatch({ type: 'SET_SHOW_GENERATE_DIALOG', payload: true })}
            className="bg-blue-600 hover:bg-blue-700"
          >
            <Plus className="w-4 h-4 mr-2" />
            创建应用
          </Button>
        </div>
      </Card>

      {/* 应用列表 */}
      <ApplicationList state={state} dispatch={dispatch} />

      {/* 应用生成对话框 */}
      <ApplicationGenerateDialog state={state} dispatch={dispatch} />

      {/* 应用运行对话框 */}
      <ApplicationRunDialog state={state} dispatch={dispatch} />

      {/* 应用编辑对话框 */}
      <ApplicationEditDialog state={state} dispatch={dispatch} />
    </div>
  );
}