/**
 * filekorolheader: 设备参数管理状态管理器 - 参数模板配置中心
 * 功能：设备类型数据管理、参数模板配置、对话框状态控制、操作处理
 * 路径：/ai-crop-model/data-sense-center/device-parameter/components
 * 规范：遵循crop-x/docs/开发项目规范.md，useReducer状态管理模式
 */

import { toast } from 'sonner';

// 参数定义接口
export interface ParameterDefinition {
  key: string;
  label: string;
  type: 'string' | 'number' | 'boolean' | 'select';
  required?: boolean;
  defaultValue?: any;
  options?: { label: string; value: string }[];
  unit?: string;
  min?: number;
  max?: number;
  description?: string;
}

// 设备类型接口
export interface DeviceType {
  id: string;
  name: string;
  manufacturer?: string;
  model?: string;
  description?: string;
  parameterDefinitions: ParameterDefinition[];
  createdAt: string;
  updatedAt: string;
}

// 状态接口
export interface DeviceParameterState {
  deviceTypes: DeviceType[];
  selectedType: DeviceType | null;
  loading: boolean;
  error: string | null;

  // 对话框状态
  showAddParamDialog: boolean;
  showViewParamDialog: boolean;
  showDeleteConfirm: boolean;

  // 编辑/查看数据
  editingParam: ParameterDefinition | null;
  viewingParam: ParameterDefinition | null;
  pendingDeleteParam: string | null;
}

// Action类型定义
export type DeviceParameterAction =
  | { type: 'LOAD_DATA' }
  | { type: 'SET_DEVICE_TYPES'; payload: DeviceType[] }
  | { type: 'SET_SELECTED_TYPE'; payload: DeviceType | null }
  | { type: 'SHOW_ADD_PARAM_DIALOG' }
  | { type: 'SET_ADD_PARAM_DIALOG'; payload: boolean }
  | { type: 'SHOW_EDIT_PARAM_DIALOG'; payload: ParameterDefinition }
  | { type: 'SHOW_VIEW_PARAM_DIALOG'; payload: ParameterDefinition }
  | { type: 'SET_VIEW_PARAM_DIALOG'; payload: boolean }
  | { type: 'SHOW_DELETE_CONFIRM'; payload: string }
  | { type: 'SET_DELETE_CONFIRM'; payload: boolean }
  | { type: 'ADD_PARAMETER'; payload: ParameterDefinition }
  | { type: 'UPDATE_PARAMETER'; payload: ParameterDefinition }
  | { type: 'DELETE_PARAMETER'; payload: string }
  | { type: 'CLEAR_EDITING_PARAM' };

// 初始状态
export const initialState: DeviceParameterState = {
  deviceTypes: [],
  selectedType: null,
  loading: false,
  error: null,
  showAddParamDialog: false,
  showViewParamDialog: false,
  showDeleteConfirm: false,
  editingParam: null,
  viewingParam: null,
  pendingDeleteParam: null,
};

// Reducer函数
export function deviceParameterReducer(state: DeviceParameterState, action: DeviceParameterAction): DeviceParameterState {
  switch (action.type) {
    case 'LOAD_DATA':
      return loadData(state);

    case 'SET_DEVICE_TYPES':
      return { ...state, deviceTypes: action.payload };

    case 'SET_SELECTED_TYPE':
      return { ...state, selectedType: action.payload };

    case 'SHOW_ADD_PARAM_DIALOG':
      return {
        ...state,
        showAddParamDialog: true,
        editingParam: null
      };

    case 'SET_ADD_PARAM_DIALOG':
      return {
        ...state,
        showAddParamDialog: action.payload,
        editingParam: action.payload ? null : state.editingParam
      };

    case 'SHOW_EDIT_PARAM_DIALOG':
      return {
        ...state,
        showAddParamDialog: true,
        editingParam: action.payload
      };

    case 'SHOW_VIEW_PARAM_DIALOG':
      return {
        ...state,
        showViewParamDialog: true,
        viewingParam: action.payload
      };

    case 'SET_VIEW_PARAM_DIALOG':
      return {
        ...state,
        showViewParamDialog: action.payload,
        viewingParam: action.payload ? null : state.viewingParam
      };

    case 'SHOW_DELETE_CONFIRM':
      return {
        ...state,
        showDeleteConfirm: true,
        pendingDeleteParam: action.payload
      };

    case 'SET_DELETE_CONFIRM':
      return {
        ...state,
        showDeleteConfirm: action.payload,
        pendingDeleteParam: action.payload ? null : state.pendingDeleteParam
      };

    case 'ADD_PARAMETER':
      return addParameter(state, action.payload);

    case 'UPDATE_PARAMETER':
      return updateParameter(state, action.payload);

    case 'DELETE_PARAMETER':
      return deleteParameter(state, action.payload);

    case 'CLEAR_EDITING_PARAM':
      return { ...state, editingParam: null };

    default:
      return state;
  }
}

// 加载数据
function loadData(state: DeviceParameterState): DeviceParameterState {
  try {
    const data = localStorage.getItem('smart_agriculture_ai_device_types');
    if (data) {
      const types = JSON.parse(data);
      const normalizedTypes = types.map((type: any) => ({
        ...type,
        parameterDefinitions: type.parameterDefinitions || []
      }));
      return {
        ...state,
        deviceTypes: normalizedTypes,
        selectedType: normalizedTypes.length > 0 ? normalizedTypes[0] : null
      };
    } else {
      // 创建模拟数据
      const mockTypes: DeviceType[] = [
        {
          id: 'device-type-1',
          name: '土壤传感器',
          manufacturer: '施耐德',
          model: 'SOIL-100',
          description: '高精度土壤温湿度、养分监测传感器',
          parameterDefinitions: [
            {
              key: 'measurementInterval',
              label: '测量间隔',
              type: 'number',
              unit: '分钟',
              required: true,
              defaultValue: 30,
              min: 5,
              max: 120,
              description: '数据测量时间间隔'
            },
            {
              key: 'uploadMode',
              label: '上传模式',
              type: 'select',
              options: [
                { label: '实时上传', value: 'realtime' },
                { label: '定时上传', value: 'scheduled' }
              ],
              defaultValue: 'scheduled',
              description: '数据上传方式'
            },
            {
              key: 'depth',
              label: '测量深度',
              type: 'number',
              unit: 'cm',
              required: true,
              defaultValue: 10,
              min: 5,
              max: 100,
              description: '传感器在土壤中的测量深度'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-2',
          name: '气象站',
          manufacturer: '华为',
          model: 'WEATHER-200',
          description: '多参数气象监测站，支持温度、湿度、风速、降雨量等监测',
          parameterDefinitions: [
            {
              key: 'sampleRate',
              label: '采样频率',
              type: 'number',
              unit: '次/小时',
              required: true,
              defaultValue: 12,
              min: 1,
              max: 60,
              description: '每小时采集次数'
            },
            {
              key: 'windSpeedUnit',
              label: '风速单位',
              type: 'select',
              options: [
                { label: '米/秒', value: 'm/s' },
                { label: '公里/小时', value: 'km/h' }
              ],
              defaultValue: 'm/s'
            },
            {
              key: 'autoCalibration',
              label: '自动校准',
              type: 'boolean',
              defaultValue: true,
              description: '是否启用设备自动校准功能'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-3',
          name: '虫情监测仪',
          manufacturer: '托普云农',
          model: 'PEST-300',
          description: 'AI智能虫情监测仪，自动拍照识别害虫种类和数量',
          parameterDefinitions: [
            {
              key: 'photoInterval',
              label: '拍照间隔',
              type: 'number',
              unit: '小时',
              required: true,
              defaultValue: 2,
              min: 1,
              max: 24,
              description: '自动拍照时间间隔'
            },
            {
              key: 'aiRecognition',
              label: 'AI识别',
              type: 'boolean',
              defaultValue: true,
              description: '是否启用AI自动识别'
            },
            {
              key: 'detectionSensitivity',
              label: '检测灵敏度',
              type: 'select',
              options: [
                { label: '高灵敏度', value: 'high' },
                { label: '中灵敏度', value: 'medium' },
                { label: '低灵敏度', value: 'low' }
              ],
              defaultValue: 'medium',
              description: '害虫检测的灵敏度设置'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-4',
          name: '水质监测仪',
          manufacturer: '海康威视',
          model: 'WATER-400',
          description: '多参数水质在线监测仪，支持pH、溶解氧、浊度等监测',
          parameterDefinitions: [
            {
              key: 'measurementCycle',
              label: '测量周期',
              type: 'number',
              unit: '分钟',
              required: true,
              defaultValue: 15,
              min: 5,
              max: 60
            },
            {
              key: 'alarmEnabled',
              label: '启用预警',
              type: 'boolean',
              defaultValue: true
            },
            {
              key: 'phThreshold',
              label: 'pH阈值',
              type: 'number',
              unit: 'pH',
              defaultValue: 7.0,
              min: 6.0,
              max: 8.5,
              description: 'pH值异常预警阈值'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-5',
          name: '灌溉控制器',
          manufacturer: '大疆',
          model: 'IRRI-500',
          description: '智能灌溉控制器，支持远程控制和定时灌溉',
          parameterDefinitions: [
            {
              key: 'controlMode',
              label: '控制模式',
              type: 'select',
              options: [
                { label: '手动控制', value: 'manual' },
                { label: '自动控制', value: 'auto' },
                { label: '定时控制', value: 'scheduled' }
              ],
              required: true,
              defaultValue: 'auto'
            },
            {
              key: 'flowRateLimit',
              label: '流量限制',
              type: 'number',
              unit: 'L/min',
              defaultValue: 100,
              min: 10,
              max: 500
            },
            {
              key: 'moistureThreshold',
              label: '湿度阈值',
              type: 'number',
              unit: '%',
              defaultValue: 30,
              min: 10,
              max: 80,
              description: '土壤湿度触发灌溉的阈值'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ];
      localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(mockTypes));
      localStorage.setItem('smart_agriculture_device_types', JSON.stringify(mockTypes));
      return {
        ...state,
        deviceTypes: mockTypes,
        selectedType: mockTypes[0]
      };
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    toast.error('加载数据失败');
    return state;
  }
}

// 添加参数
function addParameter(state: DeviceParameterState, newParam: ParameterDefinition): DeviceParameterState {
  try {
    if (!state.selectedType) return state;

    const updatedParams = [...state.selectedType.parameterDefinitions, newParam];
    const updatedType: DeviceType = {
      ...state.selectedType,
      parameterDefinitions: updatedParams,
      updatedAt: new Date().toISOString()
    };

    const updatedTypes = state.deviceTypes.map(t =>
      t.id === state.selectedType?.id ? updatedType : t
    );

    localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(updatedTypes));
    localStorage.setItem('smart_agriculture_device_types', JSON.stringify(updatedTypes));
    toast.success('参数添加成功');

    return {
      ...state,
      deviceTypes: updatedTypes,
      selectedType: updatedType,
      showAddParamDialog: false,
      editingParam: null
    };
  } catch (error) {
    console.error('添加失败:', error);
    toast.error('添加失败');
    return state;
  }
}

// 更新参数
function updateParameter(state: DeviceParameterState, updatedParam: ParameterDefinition): DeviceParameterState {
  try {
    if (!state.selectedType) return state;

    const updatedParams = state.selectedType.parameterDefinitions.map(p =>
      p.key === updatedParam.key ? updatedParam : p
    );
    const updatedType: DeviceType = {
      ...state.selectedType,
      parameterDefinitions: updatedParams,
      updatedAt: new Date().toISOString()
    };

    const updatedTypes = state.deviceTypes.map(t =>
      t.id === state.selectedType?.id ? updatedType : t
    );

    localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(updatedTypes));
    localStorage.setItem('smart_agriculture_device_types', JSON.stringify(updatedTypes));
    toast.success('参数更新成功');

    return {
      ...state,
      deviceTypes: updatedTypes,
      selectedType: updatedType,
      showAddParamDialog: false,
      editingParam: null
    };
  } catch (error) {
    console.error('更新失败:', error);
    toast.error('更新失败');
    return state;
  }
}

// 删除参数
function deleteParameter(state: DeviceParameterState, paramKey: string): DeviceParameterState {
  try {
    if (!state.selectedType) return state;

    const updatedParams = state.selectedType.parameterDefinitions.filter(p => p.key !== paramKey);
    const updatedType: DeviceType = {
      ...state.selectedType,
      parameterDefinitions: updatedParams,
      updatedAt: new Date().toISOString()
    };

    const updatedTypes = state.deviceTypes.map(t =>
      t.id === state.selectedType?.id ? updatedType : t
    );

    localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(updatedTypes));
    localStorage.setItem('smart_agriculture_device_types', JSON.stringify(updatedTypes));
    toast.success('参数删除成功');

    return {
      ...state,
      deviceTypes: updatedTypes,
      selectedType: updatedType,
      showDeleteConfirm: false,
      pendingDeleteParam: null
    };
  } catch (error) {
    console.error('删除失败:', error);
    toast.error('删除失败');
    return state;
  }
}