/**
 * filekorolheader: 应用列表组件 - 模型应用列表展示
 * 功能：应用列表展示、状态管理、操作按钮
 * 路径：/ai-crop-model/model-application/generation/components/ApplicationList
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式
 */
'use client';

import { ApplicationGenerationState, ApplicationGenerationAction } from './ApplicationGenerationReducer';
import { Application } from '@/types/ai-model';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  PlayCircle,
  PauseCircle,
  StopCircle,
  Eye,
  Edit,
  Clock,
  CheckCircle,
  XCircle,
  AlertTriangle,
  Droplets,
  Bug,
  Sprout,
  TrendingUp,
  Activity,
  Server,
  Terminal,
  LineChart as LineChartIcon,
  PieChart as PieChartIcon,
  Table as TableIcon,
  Type,
  Rocket,
} from 'lucide-react';
import { toast } from 'sonner';

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

export default function ApplicationList({ state, dispatch }: ApplicationListProps) {
  // 辅助函数
  const getAppTypeIcon = (type: string) => {
    switch (type) {
      case '智能灌溉': return <Droplets className="w-4 h-4 text-green-600" />;
      case '病虫害预警': return <Bug className="w-4 h-4 text-orange-600" />;
      case '施肥推荐': return <Sprout className="w-4 h-4 text-purple-600" />;
      case '产量预测': return <TrendingUp className="w-4 h-4 text-blue-600" />;
      case '生长监测': return <Activity className="w-4 h-4 text-cyan-600" />;
      default: return <Server className="w-4 h-4 text-gray-600" />;
    }
  };

  const getOutputFormatIcon = (format: string) => {
    switch (format) {
      case '折线图': return <LineChartIcon className="w-4 h-4 text-blue-600" />;
      case '饼状图': return <PieChartIcon className="w-4 h-4 text-green-600" />;
      case '表格': return <TableIcon className="w-4 h-4 text-purple-600" />;
      case '文字': return <Type className="w-4 h-4 text-gray-600" />;
      default: return <Server className="w-4 h-4 text-gray-600" />;
    }
  };

  const handleRunApplication = (app: Application) => {
    dispatch({ type: 'SET_RUNNING_APP', payload: app });
    dispatch({ type: 'SET_SHOW_RUN_DIALOG', payload: true });
    dispatch({ type: 'SET_INPUT_DATA', payload: {} });
    dispatch({ type: 'SET_RUN_RESULT', payload: null });
  };

  const handleToggleStatus = (appId: string) => {
    dispatch({ type: 'TOGGLE_APPLICATION_STATUS', payload: appId });
    const app = state.applications.find(a => a.id === appId);
    toast.success(`应用已${app?.status === '运行中' ? '停止' : '启动'}`);
  };

  const handleEditApp = (app: Application) => {
    dispatch({ type: 'SET_EDITING_APP', payload: app });
    dispatch({
      type: 'SET_EDIT_APP_DATA',
      payload: {
        name: app.name,
        type: app.type,
        description: app.description,
        modelName: app.modelName,
        modelVersion: app.modelVersion,
        inputFields: app.inputConfig.fields,
        outputFormat: app.outputConfig.format,
      }
    });
    dispatch({ type: 'SET_EDIT_STEP', payload: 1 });
    dispatch({ type: 'SET_SHOW_EDIT_DIALOG', payload: true });
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case '运行中':
        return <PlayCircle className="w-4 h-4 text-green-600" />;
      case '已停止':
        return <StopCircle className="w-4 h-4 text-gray-600" />;
      case '故障':
        return <XCircle className="w-4 h-4 text-red-600" />;
      default:
        return <AlertCircle className="w-4 h-4 text-gray-600" />;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case '运行中':
        return 'bg-green-100 text-green-700 border-green-300';
      case '已停止':
        return 'bg-gray-100 text-gray-700 border-gray-300';
      case '故障':
        return 'bg-red-100 text-red-700 border-red-300';
      default:
        return 'bg-gray-100 text-gray-700 border-gray-300';
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case '运行中':
        return (
          <Badge className="bg-green-100 text-green-800 border-green-200 font-light">
            <CheckCircle className="w-3 h-3 mr-1" />
            运行中
          </Badge>
        );
      case '已停止':
        return (
          <Badge className="bg-red-100 text-red-800 border-red-200 font-light">
            <XCircle className="w-3 h-3 mr-1" />
            已停止
          </Badge>
        );
      case '故障':
        return (
          <Badge className="bg-orange-100 text-orange-800 border-orange-200 font-light">
            <AlertTriangle className="w-3 h-3 mr-1" />
            故障
          </Badge>
        );
      default:
        return (
          <Badge variant="outline" className="font-light">
            <Clock className="w-3 h-3 mr-1" />
            未知
          </Badge>
        );
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case '智能灌溉':
        return 'bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800';
      case '病虫害预警':
        return 'bg-red-50 dark:bg-red-950 border-red-200 dark:border-red-800';
      case '施肥推荐':
        return 'bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800';
      case '产量预测':
        return 'bg-purple-50 dark:bg-purple-950 border-purple-200 dark:border-purple-800';
      case '生长监测':
        return 'bg-orange-50 dark:bg-orange-950 border-orange-200 dark:border-orange-800';
      default:
        return 'bg-gray-50 dark:bg-gray-950 border-gray-200 dark:border-gray-800';
    }
  };

  return (
    <div>
      <h3 className="mb-4 flex items-center gap-2">
        <Rocket className="w-5 h-5 text-blue-600" />
        我的应用
      </h3>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {state.applications.map((app) => (
          <Card key={app.id} className="p-6 hover:shadow-lg transition-shadow">
            <div className="space-y-4">
              {/* 头部 */}
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-blue-50 rounded-lg flex items-center justify-center">
                    {getAppTypeIcon(app.type)}
                  </div>
                  <div>
                    <h4 className="text-base">{app.name}</h4>
                    <Badge variant="outline" className="mt-1">{app.type}</Badge>
                  </div>
                </div>
              </div>
              {/* 描述 */}
              <p className="text-sm text-muted-foreground line-clamp-2">
                {app.description}
              </p>
              {/* 模型信息 */}
              <div className="space-y-2">
                <div className="flex items-center gap-2 text-sm">
                  <Server className="w-4 h-4 text-gray-500" />
                  <span className="text-muted-foreground">模型:</span>
                  <span>{app.modelName}</span>
                </div>
                <div className="flex items-center gap-2 text-sm">
                  <Terminal className="w-4 h-4 text-gray-500" />
                  <span className="text-muted-foreground">版本:</span>
                  <span>{app.modelVersion}</span>
                </div>
              </div>
              {/* 输入字段 */}
              <div>
                <p className="text-xs text-muted-foreground mb-2">输入字段:</p>
                <div className="flex flex-wrap gap-1">
                  {app.inputConfig.fields.slice(0, 3).map((field, idx) => (
                    <Badge key={idx} variant="outline" className="text-xs">
                      {field}
                    </Badge>
                  ))}
                  {app.inputConfig.fields.length > 3 && (
                    <Badge variant="outline" className="text-xs">
                      +{app.inputConfig.fields.length - 3}
                    </Badge>
                  )}
                </div>
              </div>
              {/* 输出格式 */}
              <div className="flex items-center gap-2">
                {getOutputFormatIcon(app.outputConfig.format)}
                <span className="text-sm text-muted-foreground">输出:</span>
                <Badge className="bg-purple-100 text-purple-700 border-purple-300">
                  {app.outputConfig.format}
                </Badge>
              </div>
              {/* 统计信息 */}
              <div className="pt-4 border-t">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <p className="text-xs text-muted-foreground">执行次数</p>
                    <p className="text-lg">{app.runCount}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">成功率</p>
                    <p className="text-lg text-green-600">{app.successRate}%</p>
                  </div>
                </div>
              </div>
              {/* 状态和操作 */}
              <div className="space-y-3 pt-4 border-t">
                <div className="flex items-center gap-2">
                  {getStatusIcon(app.status)}
                  <Badge className={getStatusColor(app.status)}>{app.status}</Badge>
                </div>
                <div className="flex gap-2">
                  {/* 运行按钮 - 仅在非停止状态显示 */}
                  {app.status !== '已停止' && (
                    <Button
                      size="sm"
                      className="flex-1 bg-blue-600 hover:bg-blue-700"
                      onClick={() => handleRunApplication(app)}
                    >
                      <PlayCircle className="w-3 h-3 mr-1" />
                      运行
                    </Button>
                  )}
                  {/* 停止/启动按钮 */}
                  {app.status === '运行中' ? (
                    <Button
                      size="sm"
                      variant="outline"
                      className={app.status === '已停止' ? 'flex-1' : ''}
                      onClick={() => handleToggleStatus(app.id)}
                    >
                      <PauseCircle className="w-3 h-3" />
                    </Button>
                  ) : (
                    <Button
                      size="sm"
                      variant="outline"
                      className={app.status === '已停止' ? 'flex-1' : ''}
                      onClick={() => handleToggleStatus(app.id)}
                    >
                      <PlayCircle className="w-3 h-3" />
                    </Button>
                  )}
                  <Button size="sm" variant="outline" onClick={() => {/* 查看详情 */}}>
                    <Eye className="w-3 h-3" />
                  </Button>
                  <Button size="sm" variant="outline" onClick={() => handleEditApp(app)}>
                    <Edit className="w-3 h-3" />
                  </Button>
                </div>
              </div>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}