/**
 * filekorolheader: 模型集成管理状态管理 - 模型服务与参数集中管理
 * 功能：模型状态管理、弹窗控制、数据持久化、筛选功能
 * 路径：/ai-crop-model/model-integration/management
 * 规范：遵循crop-x/docs/开发项目规范.md，使用useReducer状态管理，shadcn语义化样式
 */

import { ModelService, FilterOptions } from '../types';

export interface ModelIntegrationState {
  // 模型服务数据
  models: ModelService[];

  // 筛选选项
  filters: FilterOptions;

  // 统计数据
  totalModels: number;
  runningModels: number;
  avgAccuracy: number;
  qps: number;

  // 弹窗状态
  showAddModelDialog: boolean;
  showConfigDialog: boolean;
  showViewDialog: boolean;
  showDeleteDialog: boolean;
  showPermissionDialog: boolean;
  showPerformanceDialog: boolean;
  showRedeployDialog: boolean;

  // 选中的模型
  selectedModel: ModelService | null;

  // 加载状态
  loading: boolean;
}

export type ModelIntegrationAction =
  | { type: 'LOAD_DATA' }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_MODELS'; payload: ModelService[] }
  | { type: 'UPDATE_FILTERS'; payload: Partial<FilterOptions> }
  | { type: 'ADD_MODEL'; payload: ModelService }
  | { type: 'UPDATE_MODEL'; payload: ModelService }
  | { type: 'DELETE_MODEL'; payload: string }
  | { type: 'TOGGLE_MODEL_STATUS'; payload: string }
  | { type: 'SET_SELECTED_MODEL'; payload: ModelService | null }
  | { type: 'SHOW_ADD_MODEL_DIALOG' }
  | { type: 'SHOW_CONFIG_DIALOG'; payload: ModelService }
  | { type: 'SHOW_VIEW_DIALOG'; payload: ModelService }
  | { type: 'SHOW_DELETE_DIALOG'; payload: ModelService }
  | { type: 'SHOW_PERMISSION_DIALOG'; payload: ModelService }
  | { type: 'SHOW_PERFORMANCE_DIALOG'; payload: ModelService }
  | { type: 'SHOW_REDEPLOY_DIALOG'; payload: ModelService }
  | { type: 'SET_ADD_MODEL_DIALOG'; payload: boolean }
  | { type: 'SET_CONFIG_DIALOG'; payload: boolean }
  | { type: 'SET_VIEW_DIALOG'; payload: boolean }
  | { type: 'SET_DELETE_DIALOG'; payload: boolean }
  | { type: 'SET_PERMISSION_DIALOG'; payload: boolean }
  | { type: 'SET_PERFORMANCE_DIALOG'; payload: boolean }
  | { type: 'SET_REDEPLOY_DIALOG'; payload: boolean };

const generateMockModels = (): ModelService[] => [
  {
    id: '1',
    name: '病虫害识别模型',
    type: 'pest_identification',
    version: 'v2.1.0',
    status: 'active',
    description: '基于深度学习的农作物病虫害图像识别模型，支持52种常见病虫害识别',
    apiEndpoint: 'https://api.smart-crop.com/v2/models/pest-detection',
    parameters: {
      input_size: [224, 224],
      confidence_threshold: 0.85,
      max_detections: 10
    },
    metrics: {
      total_calls: 15420,
      avg_response_time: 245,
      success_rate: 98.5,
      accuracy: 95.2,
      last_called: new Date(Date.now() - 1000 * 60 * 5).toISOString(),
      qps: 12.5
    },
    tags: ['图像识别', '病虫害', '深度学习'],
    visibility: 'public',
    team: 'AI算法团队',
    concurrency: 100,
    timeout: 30000,
    retryCount: 3,
    createdAt: '2024-03-15T08:00:00Z',
    updatedAt: '2024-03-20T14:30:00Z'
  },
  {
    id: '2',
    name: '产量预测模型',
    type: 'yield_prediction',
    version: 'v1.3.2',
    status: 'active',
    description: '基于历史数据和环境因素的农作物产量预测模型',
    apiEndpoint: 'https://api.smart-crop.com/v2/models/yield-prediction',
    parameters: {
      weather_features: true,
      soil_features: true,
      historical_days: 30,
      prediction_horizon: 90
    },
    metrics: {
      total_calls: 8960,
      avg_response_time: 890,
      success_rate: 99.1,
      accuracy: 88.7,
      last_called: new Date(Date.now() - 1000 * 60 * 15).toISOString(),
      qps: 8.2
    },
    tags: ['预测分析', '产量', '机器学习'],
    visibility: 'team',
    team: '数据分析团队',
    concurrency: 50,
    timeout: 60000,
    retryCount: 2,
    createdAt: '2024-02-20T10:00:00Z',
    updatedAt: '2024-03-18T16:45:00Z'
  },
  {
    id: '3',
    name: '生长状态识别模型',
    type: 'growth_status',
    version: 'v1.2.0',
    status: 'active',
    description: '基于作物图像的生长阶段自动识别模型',
    apiEndpoint: 'https://api.smart-crop.com/v2/models/growth-stage',
    parameters: {
      input_size: [256, 256],
      confidence_threshold: 0.75,
      growth_stages: ['seedling', 'vegetative', 'flowering', 'fruiting', 'mature']
    },
    metrics: {
      total_calls: 2150,
      avg_response_time: 445,
      success_rate: 94.2,
      accuracy: 89.3,
      last_called: new Date(Date.now() - 1000 * 60 * 30).toISOString(),
      qps: 4.2
    },
    tags: ['图像识别', '生长阶段', 'AI分析'],
    visibility: 'public',
    team: 'AI算法团队',
    concurrency: 20,
    timeout: 25000,
    retryCount: 1,
    createdAt: '2024-03-10T15:00:00Z',
    updatedAt: '2024-03-22T10:30:00Z'
  }
];

const calculateStatistics = (models: ModelService[]) => {
  const totalModels = models.length;
  const runningModels = models.filter(m => m.status === 'active').length;

  const avgAccuracy = models.length > 0
    ? (models.reduce((sum, model) => sum + model.metrics.accuracy, 0) / models.length).toFixed(1)
    : 0;

  const qps = models.length > 0
    ? models.reduce((sum, model) => sum + model.metrics.qps, 0).toFixed(1)
    : 0;

  return {
    totalModels,
    runningModels,
    avgAccuracy: parseFloat(avgAccuracy),
    qps: parseFloat(qps)
  };
};

export const initialState: ModelIntegrationState = {
  models: [],
  filters: {
    searchTerm: '',
    typeFilter: 'all',
    statusFilter: 'all'
  },
  totalModels: 0,
  runningModels: 0,
  avgAccuracy: 0,
  qps: 0,
  showAddModelDialog: false,
  showConfigDialog: false,
  showViewDialog: false,
  showDeleteDialog: false,
  showPermissionDialog: false,
  showPerformanceDialog: false,
  showRedeployDialog: false,
  selectedModel: null,
  loading: false
};

export const modelIntegrationReducer = (
  state: ModelIntegrationState,
  action: ModelIntegrationAction
): ModelIntegrationState => {
  switch (action.type) {
    case 'LOAD_DATA':
      const models = generateMockModels();
      const statistics = calculateStatistics(models);

      // 持久化到localStorage
      localStorage.setItem('smart_crop_model_integration_models', JSON.stringify(models));

      return {
        ...state,
        models,
        ...statistics,
        loading: false
      };

    case 'SET_LOADING':
      return {
        ...state,
        loading: action.payload
      };

    case 'SET_MODELS':
      localStorage.setItem('smart_crop_model_integration_models', JSON.stringify(action.payload));
      const updatedStatistics = calculateStatistics(action.payload);
      return {
        ...state,
        models: action.payload,
        ...updatedStatistics
      };

    case 'UPDATE_FILTERS':
      const newFilters = { ...state.filters, ...action.payload };
      return {
        ...state,
        filters: newFilters
      };

    case 'ADD_MODEL':
      const newModels = [...state.models, action.payload];
      localStorage.setItem('smart_crop_model_integration_models', JSON.stringify(newModels));
      const addStatistics = calculateStatistics(newModels);
      return {
        ...state,
        models: newModels,
        ...addStatistics
      };

    case 'UPDATE_MODEL':
      const updatedModels = state.models.map(model =>
        model.id === action.payload.id ? { ...action.payload, updatedAt: new Date().toISOString() } : model
      );
      localStorage.setItem('smart_crop_model_integration_models', JSON.stringify(updatedModels));
      const updateStatistics = calculateStatistics(updatedModels);
      return {
        ...state,
        models: updatedModels,
        ...updateStatistics
      };

    case 'DELETE_MODEL':
      const filteredModels = state.models.filter(model => model.id !== action.payload);
      localStorage.setItem('smart_crop_model_integration_models', JSON.stringify(filteredModels));
      const deleteStatistics = calculateStatistics(filteredModels);
      return {
        ...state,
        models: filteredModels,
        ...deleteStatistics
      };

    case 'TOGGLE_MODEL_STATUS':
      const toggledModels = state.models.map(model =>
        model.id === action.payload
          ? {
              ...model,
              status: model.status === 'active' ? 'inactive' : 'active' as 'active' | 'inactive',
              updatedAt: new Date().toISOString()
            }
          : model
      );
      localStorage.setItem('smart_crop_model_integration_models', JSON.stringify(toggledModels));
      const toggleStatistics = calculateStatistics(toggledModels);
      return {
        ...state,
        models: toggledModels,
        ...toggleStatistics
      };

    case 'SET_SELECTED_MODEL':
      return {
        ...state,
        selectedModel: action.payload
      };

    case 'SHOW_ADD_MODEL_DIALOG':
      return {
        ...state,
        showAddModelDialog: true
      };

    case 'SHOW_CONFIG_DIALOG':
      return {
        ...state,
        showConfigDialog: true,
        selectedModel: action.payload
      };

    case 'SHOW_VIEW_DIALOG':
      return {
        ...state,
        showViewDialog: true,
        selectedModel: action.payload
      };

    case 'SHOW_DELETE_DIALOG':
      return {
        ...state,
        showDeleteDialog: true,
        selectedModel: action.payload
      };

    case 'SHOW_PERMISSION_DIALOG':
      return {
        ...state,
        showPermissionDialog: true,
        selectedModel: action.payload
      };

    case 'SHOW_PERFORMANCE_DIALOG':
      return {
        ...state,
        showPerformanceDialog: true,
        selectedModel: action.payload
      };

    case 'SHOW_REDEPLOY_DIALOG':
      return {
        ...state,
        showRedeployDialog: true,
        selectedModel: action.payload
      };

    case 'SET_ADD_MODEL_DIALOG':
      return {
        ...state,
        showAddModelDialog: action.payload
      };

    case 'SET_CONFIG_DIALOG':
      return {
        ...state,
        showConfigDialog: action.payload
      };

    case 'SET_VIEW_DIALOG':
      return {
        ...state,
        showViewDialog: action.payload
      };

    case 'SET_DELETE_DIALOG':
      return {
        ...state,
        showDeleteDialog: action.payload
      };

    case 'SET_PERMISSION_DIALOG':
      return {
        ...state,
        showPermissionDialog: action.payload
      };

    case 'SET_PERFORMANCE_DIALOG':
      return {
        ...state,
        showPerformanceDialog: action.payload
      };

    case 'SET_REDEPLOY_DIALOG':
      return {
        ...state,
        showRedeployDialog: action.payload
      };

    default:
      return state;
  }
};