/**
 * filekorolheader: 应用运行对话框 - 模型应用运行和结果展示
 * 功能：应用参数输入、运行执行、结果可视化展示
 * 路径：/ai-crop-model/model-application/generation/components/ApplicationRunDialog
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式
 */
'use client';

import { useState } from 'react';
import { ApplicationGenerationState, ApplicationGenerationAction } from './ApplicationGenerationReducer';
import { Application } from '@/types/ai-model';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import {
  PlayCircle,
  StopCircle,
  Loader2,
  CheckCircle,
  XCircle,
  AlertTriangle,
  LineChart as LineChartIcon,
  PieChart as PieChartIcon,
  Table as TableIcon,
  FileText,
} 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';

interface ApplicationRunDialogProps {
  state: ApplicationGenerationState;
  dispatch: React.Dispatch<ApplicationGenerationAction>;
}

export default function ApplicationRunDialog({ state, dispatch }: ApplicationRunDialogProps) {
  const { showRunDialog, runningApp, inputData, isRunning, runResult, dataSourceOptions, iotDeviceOptions } = state;
  const [selectedDataSources, setSelectedDataSources] = useState<Record<string, string>>({});

  if (!runningApp) return null;

  const handleInputChange = (field: string, value: string) => {
    dispatch({
      type: 'SET_INPUT_DATA',
      payload: { ...inputData, [field]: value }
    });
  };

  const handleDataSourceChange = (field: string, dataSource: string) => {
    setSelectedDataSources(prev => ({ ...prev, [field]: dataSource }));
  };

  const handleRunApplication = async () => {
    // 验证必填字段
    const missingFields = runningApp.inputConfig.fields.filter(field => !inputData[field]);
    if (missingFields.length > 0) {
      toast.error(`请填写以下字段: ${missingFields.join(', ')}`);
      return;
    }

    dispatch({ type: 'SET_IS_RUNNING', payload: true });
    dispatch({ type: 'SET_RUN_RESULT', payload: null });

    try {
      // 模拟应用运行过程
      await new Promise(resolve => setTimeout(resolve, 2000));

      // 生成模拟结果数据
      const mockResult = generateMockResult(runningApp);
      dispatch({ type: 'SET_RUN_RESULT', payload: mockResult });
      toast.success('应用运行成功！');
    } catch (error) {
      toast.error('应用运行失败');
    } finally {
      dispatch({ type: 'SET_IS_RUNNING', payload: false });
    }
  };

  const generateMockResult = (app: Application) => {
    switch (app.outputConfig.format) {
      case '折线图':
        return {
          type: 'line',
          data: [
            { name: '1月', value: Math.random() * 100 },
            { name: '2月', value: Math.random() * 100 },
            { name: '3月', value: Math.random() * 100 },
            { name: '4月', value: Math.random() * 100 },
            { name: '5月', value: Math.random() * 100 },
            { name: '6月', value: Math.random() * 100 },
          ],
          analysis: `${app.name}分析完成，建议继续当前策略。`
        };
      case '饼状图':
        return {
          type: 'pie',
          data: [
            { name: '正常', value: 65, color: '#10b981' },
            { name: '注意', value: 25, color: '#f59e0b' },
            { name: '警告', value: 10, color: '#ef4444' },
          ],
          analysis: `${app.name}分析完成，65%区域状态正常，需要关注25%区域。`
        };
      case '表格':
        return {
          type: 'table',
          data: [
            { 项目: '土壤湿度', 数值: '65%', 状态: '正常', 建议: '保持当前灌溉策略' },
            { 项目: '氮含量', 数值: '120mg/kg', 状态: '偏低', 建议: '建议补充氮肥' },
            { 项目: 'pH值', 数值: '6.8', 状态: '正常', 建议: '无需调节' },
            { 项目: '温度', 数值: '25°C', 状态: '适宜', 建议: '适合作物生长' },
          ],
          analysis: `${app.name}分析完成，各项指标基本正常，建议适当补充氮肥。`
        };
      case '文字':
        return {
          type: 'text',
          content: `
## ${app.name}分析报告

### 总体评估
根据当前输入数据分析，${app.name}系统运行状态良好。

### 详细分析
1. **环境条件**: 当前温度25°C，湿度65%，pH值6.8，均处于适宜范围。
2. **营养状况**: 氮含量120mg/kg，略低于推荐值，建议适当补充。
3. **水分管理**: 土壤湿度65%，处于理想状态，可维持当前灌溉策略。

### 建议措施
- 建议在未来一周内补充氮肥，用量为15kg/亩
- 继续保持当前灌溉策略，每周监测土壤湿度变化
- 密切关注天气变化，如遇降雨需调整灌溉计划

### 预期效果
按照建议措施实施，预计作物产量可提升5-8%，品质得到改善。
          `,
          analysis: `${app.name}综合分析报告生成完成。`
        };
      default:
        return null;
    }
  };

  const handleClose = () => {
    dispatch({ type: 'SET_SHOW_RUN_DIALOG', payload: false });
    dispatch({ type: 'SET_RUNNING_APP', payload: null });
    dispatch({ type: 'SET_INPUT_DATA', payload: {} });
    dispatch({ type: 'SET_RUN_RESULT', payload: null });
    setSelectedDataSources({});
  };

  const renderOutputResult = () => {
    if (!runResult) return null;

    switch (runResult.type) {
      case 'line':
        return (
          <div className="space-y-4">
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={runResult.data}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Line
                    type="monotone"
                    dataKey="value"
                    stroke="#3b82f6"
                    strokeWidth={2}
                    dot={{ fill: '#3b82f6' }}
                  />
                </LineChart>
              </ResponsiveContainer>
            </div>
            <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
              <p className="text-sm text-blue-900 dark:text-blue-100">{runResult.analysis}</p>
            </Card>
          </div>
        );

      case 'pie':
        return (
          <div className="space-y-4">
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={runResult.data}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {runResult.data.map((entry: any, index: number) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <RechartsTooltip />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <Card className="p-4 bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800">
              <p className="text-sm text-green-900 dark:text-green-100">{runResult.analysis}</p>
            </Card>
          </div>
        );

      case 'table':
        return (
          <div className="space-y-4">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>项目</TableHead>
                  <TableHead>数值</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>建议</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {runResult.data.map((row: any, index: number) => (
                  <TableRow key={index}>
                    <TableCell className="font-medium">{row.项目}</TableCell>
                    <TableCell>{row.数值}</TableCell>
                    <TableCell>
                      <span className={`px-2 py-1 rounded text-xs ${
                        row.状态 === '正常'
                          ? 'bg-green-100 text-green-800'
                          : row.状态 === '偏低'
                          ? 'bg-yellow-100 text-yellow-800'
                          : 'bg-gray-100 text-gray-800'
                      }`}>
                        {row.状态}
                      </span>
                    </TableCell>
                    <TableCell className="text-sm">{row.建议}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            <Card className="p-4 bg-purple-50 dark:bg-purple-950 border-purple-200 dark:border-purple-800">
              <p className="text-sm text-purple-900 dark:text-purple-100">{runResult.analysis}</p>
            </Card>
          </div>
        );

      case 'text':
        return (
          <div className="space-y-4">
            <Card className="p-6">
              <div className="prose prose-sm max-w-none dark:prose-invert">
                <pre className="whitespace-pre-wrap text-sm font-sans">
                  {runResult.content}
                </pre>
              </div>
            </Card>
            <Card className="p-4 bg-orange-50 dark:bg-orange-950 border-orange-200 dark:border-orange-800">
              <p className="text-sm text-orange-900 dark:text-orange-100">{runResult.analysis}</p>
            </Card>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <Dialog open={showRunDialog} onOpenChange={handleClose}>
      <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <PlayCircle className="w-5 h-5 text-blue-600" />
            运行应用：{runningApp.name}
          </DialogTitle>
          <DialogDescription>
            填写输入参数并运行应用，查看分析结果
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* 应用信息 */}
          <Card className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div>
                <Label className="text-xs text-muted-foreground">应用类型</Label>
                <div className="font-medium">{runningApp.type}</div>
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">模型</Label>
                <div className="font-medium">{runningApp.modelName}</div>
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">版本</Label>
                <div className="font-mono text-xs">{runningApp.modelVersion}</div>
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">输出格式</Label>
                <div className="font-medium">{runningApp.outputConfig.format}</div>
              </div>
            </div>
          </Card>

          {/* 输入参数 */}
          {!runResult && (
            <Card className="p-4">
              <h3 className="font-semibold mb-4">输入参数</h3>
              <div className="space-y-4">
                {runningApp.inputConfig.fields.map((field) => (
                  <div key={field} className="space-y-2">
                    <Label>{field} *</Label>
                    <div className="flex gap-2">
                      <div className="flex-1">
                        {field.includes('图像') || field.includes('图片') ? (
                          <Textarea
                            placeholder={`请输入${field}的描述或上传图片链接`}
                            value={inputData[field] || ''}
                            onChange={(e) => handleInputChange(field, e.target.value)}
                            rows={3}
                          />
                        ) : field.includes('选择') || field.includes('类型') ? (
                          <Select
                            value={inputData[field] || ''}
                            onValueChange={(value) => handleInputChange(field, value)}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder={`请选择${field}`} />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="选项1">选项1</SelectItem>
                              <SelectItem value="选项2">选项2</SelectItem>
                              <SelectItem value="选项3">选项3</SelectItem>
                            </SelectContent>
                          </Select>
                        ) : field.includes('时间') || field.includes('日期') ? (
                          <Input
                            type="datetime-local"
                            value={inputData[field] || ''}
                            onChange={(e) => handleInputChange(field, e.target.value)}
                          />
                        ) : (
                          <Input
                            placeholder={`请输入${field}`}
                            value={inputData[field] || ''}
                            onChange={(e) => handleInputChange(field, e.target.value)}
                          />
                        )}
                      </div>
                      <div className="w-48">
                        <Select
                          value={selectedDataSources[field] || ''}
                          onValueChange={(value) => handleDataSourceChange(field, value)}
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="数据来源" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="手动输入">手动输入</SelectItem>
                            {dataSourceOptions.map((source) => (
                              <SelectItem key={source} value={source}>
                                {source}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    {selectedDataSources[field] && selectedDataSources[field] !== '手动输入' && (
                      <div className="text-xs text-muted-foreground">
                        数据来源: {selectedDataSources[field]}
                        {selectedDataSources[field].includes('传感器') && (
                          <Select defaultValue="">
                            <SelectTrigger className="w-full mt-1">
                              <SelectValue placeholder="选择设备" />
                            </SelectTrigger>
                            <SelectContent>
                              {iotDeviceOptions.map((device) => (
                                <SelectItem key={device} value={device}>
                                  {device}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        )}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </Card>
          )}

          {/* 运行结果 */}
          {runResult && (
            <Card className="p-4">
              <div className="flex items-center gap-2 mb-4">
                <CheckCircle className="w-5 h-5 text-green-600" />
                <h3 className="font-semibold">运行结果</h3>
              </div>
              {renderOutputResult()}
            </Card>
          )}
        </div>

        <DialogFooter>
          <div className="flex justify-between w-full">
            <Button variant="outline" onClick={handleClose}>
              {runResult ? '关闭' : '取消'}
            </Button>
            {!runResult && (
              <Button
                onClick={handleRunApplication}
                disabled={isRunning}
                className="bg-blue-600 hover:bg-blue-700"
              >
                {isRunning ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    运行中...
                  </>
                ) : (
                  <>
                    <PlayCircle className="w-4 h-4 mr-2" />
                    运行应用
                  </>
                )}
              </Button>
            )}
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}