/**
 * filekorolheader: 应用生成对话框 - 模型应用生成流程对话框
 * 功能：多步骤应用生成流程、表单验证、应用发布
 * 路径：/ai-crop-model/model-application/generation/components/ApplicationGenerateDialog
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式
 */
'use client';

import { ApplicationGenerationState, ApplicationGenerationAction } from './ApplicationGenerationReducer';
import { Application, ApplicationType, OutputFormat } 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 { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Sparkles,
  ChevronLeft,
  ChevronRight,
  FileText,
  Server,
  BarChart3,
  LineChart as LineChartIcon,
  PieChart as PieChartIcon,
  Table as TableIcon,
  Type,
  CheckCircle,
} from 'lucide-react';
import { toast } from 'sonner';

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

export default function ApplicationGenerateDialog({ state, dispatch }: ApplicationGenerateDialogProps) {
  const { showGenerateDialog, generateStep, newAppData, availableModels, inputFieldOptions } = state;

  const handleNextStep = () => {
    if (generateStep === 1) {
      if (!newAppData.name || !newAppData.type || !newAppData.description) {
        toast.error('请填写完整的基本信息');
        return;
      }
    } else if (generateStep === 2) {
      if (!newAppData.modelName || !newAppData.modelVersion) {
        toast.error('请选择模型');
        return;
      }
    } else if (generateStep === 3) {
      if (newAppData.inputFields.length === 0) {
        toast.error('请选择至少一个输入字段');
        return;
      }
    } else if (generateStep === 4) {
      if (!newAppData.outputFormat) {
        toast.error('请选择输出格式');
        return;
      }
    }
    dispatch({ type: 'SET_GENERATE_STEP', payload: generateStep + 1 });
  };

  const handlePrevStep = () => {
    dispatch({ type: 'SET_GENERATE_STEP', payload: generateStep - 1 });
  };

  const handlePublishApp = () => {
    const newApp: Application = {
      id: `app-${Date.now()}`,
      name: newAppData.name,
      type: newAppData.type as ApplicationType,
      description: newAppData.description,
      modelName: newAppData.modelName,
      modelVersion: newAppData.modelVersion,
      inputConfig: {
        fields: newAppData.inputFields,
      },
      outputConfig: {
        format: newAppData.outputFormat as OutputFormat,
      },
      status: '已停止',
      createTime: new Date().toISOString().split('T')[0],
      runCount: 0,
      successRate: 0,
      avgExecutionTime: 0,
    };

    dispatch({ type: 'ADD_APPLICATION', payload: newApp });
    dispatch({ type: 'SET_SHOW_GENERATE_DIALOG', payload: false });
    dispatch({ type: 'SET_GENERATE_STEP', payload: 1 });
    dispatch({ type: 'RESET_NEW_APP_DATA' });

    toast.success('应用创建成功！');
  };

  const handleClose = () => {
    dispatch({ type: 'SET_SHOW_GENERATE_DIALOG', payload: false });
    dispatch({ type: 'SET_GENERATE_STEP', payload: 1 });
    dispatch({ type: 'RESET_NEW_APP_DATA' });
  };

  const getStepIcon = (step: number) => {
    switch (step) {
      case 1:
        return <FileText className="w-4 h-4" />;
      case 2:
        return <Server className="w-4 h-4" />;
      case 3:
        return <FileText className="w-4 h-4" />;
      case 4:
        return <BarChart3 className="w-4 h-4" />;
      default:
        return <CheckCircle className="w-4 h-4" />;
    }
  };

  const getStepTitle = (step: number) => {
    switch (step) {
      case 1:
        return '基本信息';
      case 2:
        return '选择模型';
      case 3:
        return '输入配置';
      case 4:
        return '输出格式';
      case 5:
        return '确认发布';
      default:
        return '';
    }
  };

  return (
    <Dialog open={showGenerateDialog} onOpenChange={handleClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Sparkles className="w-5 h-5 text-blue-600" />
            创建应用 - {['填写基本信息', '选择模型', '配置输入', '配置输出', '预览发布'][generateStep - 1]}
          </DialogTitle>
          <DialogDescription>
            步骤 {generateStep} / 5
          </DialogDescription>
        </DialogHeader>

        {/* 步骤指示器 */}
        <div className="flex items-center justify-between mb-6">
          {[1, 2, 3, 4, 5].map((step) => (
            <div key={step} className="flex items-center">
              <div
                className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
                  step <= generateStep
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-200 text-gray-600'
                }`}
              >
                {step < generateStep ? <CheckCircle className="w-4 h-4" /> : getStepIcon(step)}
              </div>
              <span
                className={`ml-2 text-sm ${
                  step <= generateStep ? 'text-blue-600 font-medium' : 'text-gray-500'
                }`}
              >
                {getStepTitle(step)}
              </span>
              {step < 5 && (
                <ChevronRight className="w-4 h-4 mx-4 text-gray-400" />
              )}
            </div>
          ))}
        </div>

        {/* 步骤内容 */}
        <div className="min-h-[400px]">
          {/* 步骤1: 基本信息 */}
          {generateStep === 1 && (
            <div className="space-y-4">
              <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
                <div className="flex items-center gap-2 text-blue-900 dark:text-blue-100">
                  <FileText className="w-4 h-4" />
                  <span className="text-sm">请填写应用的基本信息</span>
                </div>
              </Card>
              <div>
                <Label>应用名称 *</Label>
                <Input
                  placeholder="请输入应用名称，如：智能灌溉策略生成"
                  value={newAppData.name}
                  onChange={(e) => dispatch({ type: 'SET_NEW_APP_DATA', payload: { name: e.target.value } })}
                />
              </div>
              <div>
                <Label>应用类型 *</Label>
                <Select
                  value={newAppData.type}
                  onValueChange={(value) => dispatch({ type: 'SET_NEW_APP_DATA', payload: { type: value } })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择应用类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="智能灌溉">智能灌溉</SelectItem>
                    <SelectItem value="病虫害预警">病虫害预警</SelectItem>
                    <SelectItem value="施肥推荐">施肥推荐</SelectItem>
                    <SelectItem value="产量预测">产量预测</SelectItem>
                    <SelectItem value="生长监测">生长监测</SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>应用描述 *</Label>
                <Textarea
                  placeholder="请详细描述应用的功能和使用场景"
                  value={newAppData.description}
                  onChange={(e) => dispatch({ type: 'SET_NEW_APP_DATA', payload: { description: e.target.value } })}
                  rows={4}
                />
              </div>
            </div>
          )}

          {/* 步骤2: 选择模型 */}
          {generateStep === 2 && (
            <div className="space-y-4">
              <Card className="p-4 bg-purple-50 dark:bg-purple-950 border-purple-200 dark:border-purple-800">
                <div className="flex items-center gap-2 text-purple-900 dark:text-purple-100">
                  <Server className="w-4 h-4" />
                  <span className="text-sm">选择用于此应用的AI模型</span>
                </div>
              </Card>
              <div>
                <Label>选择模型 *</Label>
                <div className="grid grid-cols-1 gap-3 mt-2">
                  {availableModels.map((model) => (
                    <div
                      key={model.id}
                      className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                        newAppData.modelName === model.name
                          ? 'border-blue-500 bg-blue-50 dark:bg-blue-950'
                          : 'border-gray-200 dark:border-gray-700 hover:border-blue-300 dark:hover:border-blue-600'
                      }`}
                      onClick={() =>
                        dispatch({
                          type: 'SET_NEW_APP_DATA',
                          payload: { modelName: model.name, modelVersion: model.version }
                        })
                      }
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <div className="font-medium">{model.name}</div>
                          <div className="text-sm text-muted-foreground">
                            版本: {model.version} | 类型: {model.type}
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          <div className={`w-2 h-2 rounded-full ${
                            model.status === '运行中' ? 'bg-green-500' : 'bg-red-500'
                          }`} />
                          <span className="text-sm">{model.status}</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* 步骤3: 输入配置 */}
          {generateStep === 3 && (
            <div className="space-y-4">
              <Card className="p-4 bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800">
                <div className="flex items-center gap-2 text-green-900 dark:text-green-100">
                  <FileText className="w-4 h-4" />
                  <span className="text-sm">配置应用的输入字段</span>
                </div>
              </Card>
              <div>
                <Label>输入字段 * (选择至少一个)</Label>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3 mt-2 max-h-64 overflow-y-auto p-2 border rounded-lg">
                  {inputFieldOptions.map((field) => (
                    <div key={field} className="flex items-center space-x-2">
                      <Checkbox
                        id={field}
                        checked={newAppData.inputFields.includes(field)}
                        onCheckedChange={(checked) => {
                          if (checked) {
                            dispatch({
                              type: 'SET_NEW_APP_DATA',
                              payload: {
                                inputFields: [...newAppData.inputFields, field]
                              }
                            });
                          } else {
                            dispatch({
                              type: 'SET_NEW_APP_DATA',
                              payload: {
                                inputFields: newAppData.inputFields.filter(f => f !== field)
                              }
                            });
                          }
                        }}
                      />
                      <Label htmlFor={field} className="text-sm font-normal cursor-pointer">
                        {field}
                      </Label>
                    </div>
                  ))}
                </div>
                <div className="mt-2 text-sm text-muted-foreground">
                  已选择 {newAppData.inputFields.length} 个字段
                </div>
              </div>
            </div>
          )}

          {/* 步骤4: 输出格式 */}
          {generateStep === 4 && (
            <div className="space-y-4">
              <Card className="p-4 bg-orange-50 dark:bg-orange-950 border-orange-200 dark:border-orange-800">
                <div className="flex items-center gap-2 text-orange-900 dark:text-orange-100">
                  <BarChart3 className="w-4 h-4" />
                  <span className="text-sm">配置应用的输出格式</span>
                </div>
              </Card>
              <div>
                <Label>输出格式 *</Label>
                <div className="grid grid-cols-2 gap-3 mt-2">
                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      newAppData.outputFormat === '折线图'
                        ? 'border-blue-500 bg-blue-50 dark:bg-blue-950'
                        : 'border-gray-200 dark:border-gray-700 hover:border-blue-300 dark:hover:border-blue-600'
                    }`}
                    onClick={() => dispatch({ type: 'SET_NEW_APP_DATA', payload: { outputFormat: '折线图' } })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center">
                        <LineChartIcon className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                      </div>
                      <div>
                        <div className="font-medium">折线图</div>
                        <div className="text-xs text-muted-foreground">趋势数据可视化</div>
                      </div>
                    </div>
                  </div>

                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      newAppData.outputFormat === '饼状图'
                        ? 'border-blue-500 bg-blue-50 dark:bg-blue-950'
                        : 'border-gray-200 dark:border-gray-700 hover:border-blue-300 dark:hover:border-blue-600'
                    }`}
                    onClick={() => dispatch({ type: 'SET_NEW_APP_DATA', payload: { outputFormat: '饼状图' } })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-green-100 dark:bg-green-900 rounded-lg flex items-center justify-center">
                        <PieChartIcon className="w-5 h-5 text-green-600 dark:text-green-400" />
                      </div>
                      <div>
                        <div className="font-medium">饼状图</div>
                        <div className="text-xs text-muted-foreground">比例数据可视化</div>
                      </div>
                    </div>
                  </div>

                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      newAppData.outputFormat === '表格'
                        ? 'border-blue-500 bg-blue-50 dark:bg-blue-950'
                        : 'border-gray-200 dark:border-gray-700 hover:border-blue-300 dark:hover:border-blue-600'
                    }`}
                    onClick={() => dispatch({ type: 'SET_NEW_APP_DATA', payload: { outputFormat: '表格' } })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-purple-100 dark:bg-purple-900 rounded-lg flex items-center justify-center">
                        <TableIcon className="w-5 h-5 text-purple-600 dark:text-purple-400" />
                      </div>
                      <div>
                        <div className="font-medium">表格</div>
                        <div className="text-xs text-muted-foreground">结构化数据展示</div>
                      </div>
                    </div>
                  </div>

                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      newAppData.outputFormat === '文字'
                        ? 'border-blue-500 bg-blue-50 dark:bg-blue-950'
                        : 'border-gray-200 dark:border-gray-700 hover:border-blue-300 dark:hover:border-blue-600'
                    }`}
                    onClick={() => dispatch({ type: 'SET_NEW_APP_DATA', payload: { outputFormat: '文字' } })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-orange-100 dark:bg-orange-900 rounded-lg flex items-center justify-center">
                        <Type className="w-5 h-5 text-orange-600 dark:text-orange-400" />
                      </div>
                      <div>
                        <div className="font-medium">文字</div>
                        <div className="text-xs text-muted-foreground">文本分析报告</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* 步骤5: 确认发布 */}
          {generateStep === 5 && (
            <div className="space-y-4">
              <Card className="p-4 bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800">
                <div className="flex items-center gap-2 text-green-900 dark:text-green-100">
                  <CheckCircle className="w-4 h-4" />
                  <span className="text-sm">确认应用信息并发布</span>
                </div>
              </Card>
              <Card className="p-6">
                <h3 className="font-semibold mb-4">应用信息确认</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-sm text-muted-foreground">应用名称</Label>
                    <div className="font-medium">{newAppData.name}</div>
                  </div>
                  <div>
                    <Label className="text-sm text-muted-foreground">应用类型</Label>
                    <div className="font-medium">{newAppData.type}</div>
                  </div>
                  <div>
                    <Label className="text-sm text-muted-foreground">模型名称</Label>
                    <div className="font-medium">{newAppData.modelName}</div>
                  </div>
                  <div>
                    <Label className="text-sm text-muted-foreground">模型版本</Label>
                    <div className="font-medium">{newAppData.modelVersion}</div>
                  </div>
                  <div className="col-span-2">
                    <Label className="text-sm text-muted-foreground">应用描述</Label>
                    <div className="text-sm">{newAppData.description}</div>
                  </div>
                  <div className="col-span-2">
                    <Label className="text-sm text-muted-foreground">输入字段 ({newAppData.inputFields.length})</Label>
                    <div className="flex flex-wrap gap-1 mt-1">
                      {newAppData.inputFields.map((field) => (
                        <span
                          key={field}
                          className="px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-xs rounded"
                        >
                          {field}
                        </span>
                      ))}
                    </div>
                  </div>
                  <div>
                    <Label className="text-sm text-muted-foreground">输出格式</Label>
                    <div className="font-medium">{newAppData.outputFormat}</div>
                  </div>
                </div>
              </Card>
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        <DialogFooter>
          <div className="flex justify-between w-full">
            <Button
              variant="outline"
              onClick={handleClose}
              disabled={generateStep === 5}
            >
              取消
            </Button>
            <div className="flex gap-2">
              {generateStep > 1 && generateStep < 5 && (
                <Button variant="outline" onClick={handlePrevStep}>
                  <ChevronLeft className="w-4 h-4 mr-2" />
                  上一步
                </Button>
              )}
              {generateStep < 5 ? (
                <Button onClick={handleNextStep}>
                  下一步
                  <ChevronRight className="w-4 h-4 ml-2" />
                </Button>
              ) : (
                <Button onClick={handlePublishApp} className="bg-green-600 hover:bg-green-700">
                  <CheckCircle className="w-4 h-4 mr-2" />
                  发布应用
                </Button>
              )}
            </div>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}