/**
 * filekorolheader: 设备类型状态管理 - 集中化状态管理核心
 * 功能：设备类型数据管理、弹窗状态控制、筛选条件管理
 * 路径：/ai-crop-model/data-sense-center/device-type/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: any }[];
  unit?: string;
  min?: number;
  max?: number;
  description?: string;
}

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


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

  // 对话框状态
  showAddDialog: boolean;
  showEditDialog: boolean;
  showViewDialog: boolean;
  showParamsDialog: boolean;
  showDeleteDialog: boolean;

  // 编辑/查看数据
  editingType: DeviceType | null;
  viewingType: DeviceType | null;
  viewingParams: DeviceType | null;
  pendingDeleteId: string | null;
}

// Action类型定义
export type DeviceTypeAction =
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_DEVICE_TYPES'; payload: DeviceType[] }
  | { type: 'ADD_DEVICE_TYPE'; payload: DeviceType }
  | { type: 'UPDATE_DEVICE_TYPE'; payload: DeviceType }
  | { type: 'DELETE_DEVICE_TYPE'; payload: string }
  | { type: 'SHOW_ADD_DIALOG' }
  | { type: 'SHOW_EDIT_DIALOG'; payload: DeviceType }
  | { type: 'SHOW_VIEW_DIALOG'; payload: DeviceType }
  | { type: 'SHOW_PARAMS_DIALOG'; payload: DeviceType }
  | { type: 'SHOW_DELETE_DIALOG'; payload: string }
  | { type: 'SET_ADD_DIALOG'; payload: boolean }
  | { type: 'SET_EDIT_DIALOG'; payload: boolean }
  | { type: 'SET_VIEW_DIALOG'; payload: boolean }
  | { type: 'SET_PARAMS_DIALOG'; payload: boolean }
  | { type: 'SET_DELETE_DIALOG'; payload: boolean }
  | { type: 'LOAD_DATA' };

// 初始状态
export const initialState: DeviceTypeState = {
  deviceTypes: [],
  loading: false,
  error: null,
  showAddDialog: false,
  showEditDialog: false,
  showViewDialog: false,
  showParamsDialog: false,
  showDeleteDialog: false,
  editingType: null,
  viewingType: null,
  viewingParams: null,
  pendingDeleteId: null,
};

// Reducer函数
export function deviceTypeReducer(state: DeviceTypeState, action: DeviceTypeAction): DeviceTypeState {
  switch (action.type) {
    case 'SET_LOADING':
      return { ...state, loading: action.payload };

    case 'SET_ERROR':
      return { ...state, error: action.payload, loading: false };

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

    case 'ADD_DEVICE_TYPE':
      return {
        ...state,
        deviceTypes: [...state.deviceTypes, action.payload],
        showAddDialog: false,
        editingType: null,
      };

    case 'UPDATE_DEVICE_TYPE':
      return {
        ...state,
        deviceTypes: state.deviceTypes.map(type =>
          type.id === action.payload.id ? action.payload : type
        ),
        showEditDialog: false,
        showAddDialog: false,
        editingType: null,
      };

    case 'DELETE_DEVICE_TYPE':
      return {
        ...state,
        deviceTypes: state.deviceTypes.filter(type => type.id !== action.payload),
        showDeleteDialog: false,
        pendingDeleteId: null,
      };

    case 'SHOW_ADD_DIALOG':
      return {
        ...state,
        showAddDialog: true,
        editingType: null,
      };

    case 'SHOW_EDIT_DIALOG':
      return {
        ...state,
        showEditDialog: true,
        editingType: action.payload,
      };

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

    case 'SHOW_PARAMS_DIALOG':
      return {
        ...state,
        showParamsDialog: true,
        viewingParams: action.payload,
      };

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

    case 'SET_ADD_DIALOG':
      return {
        ...state,
        showAddDialog: action.payload,
        editingType: action.payload ? null : state.editingType,
      };

    case 'SET_EDIT_DIALOG':
      return {
        ...state,
        showEditDialog: action.payload,
        editingType: action.payload ? null : state.editingType,
      };

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

    case 'SET_PARAMS_DIALOG':
      return {
        ...state,
        showParamsDialog: action.payload,
        viewingParams: action.payload ? null : state.viewingParams,
      };

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

    case 'LOAD_DATA':
      return loadData(state);

    default:
      return state;
  }
}

// 加载数据
function loadData(state: DeviceTypeState): DeviceTypeState {
  const savedData = localStorage.getItem('smart_agriculture_ai_device_types');
  if (savedData) {
    try {
      const deviceTypes = JSON.parse(savedData);
      return {
        ...state,
        deviceTypes,
        loading: false,
      };
    } catch (error) {
      console.error('Failed to load device types:', error);
      // 如果加载失败，初始化测试数据
      return {
        ...state,
        deviceTypes: initializeTestData(),
        loading: false,
      };
    }
  } else {
    // 初始化测试数据
    return {
      ...state,
      deviceTypes: initializeTestData(),
      loading: false,
    };
  }
}

// 初始化测试数据
function initializeTestData(): DeviceType[] {
  const testDeviceTypes: DeviceType[] = [
    {
      id: '1',
      name: '智能土壤监测传感器',
      manufacturer: 'GreenTech',
      model: 'GT-SS-100',
      category: '环境监测',
      description: '用于实时监测土壤温度、湿度、pH值等环境参数的多功能传感器',
      protocol: 'LoRaWAN',
      connectivity: '无线',
      powerSupply: '太阳能+电池',
      operatingTemperature: '-30°C ~ 70°C',
      protectionRating: 'IP67',
      parameterDefinitions: [
        {
          key: 'temperature',
          label: '土壤温度',
          type: 'number',
          required: true,
          unit: '°C',
          min: -30,
          max: 70,
          description: '土壤温度监测，用于判断作物生长环境',
        },
        {
          key: 'humidity',
          label: '土壤湿度',
          type: 'number',
          required: true,
          unit: '%',
          min: 0,
          max: 100,
          description: '土壤相对湿度百分比',
        },
        {
          key: 'ph',
          label: 'pH值',
          type: 'number',
          required: true,
          unit: 'pH',
          min: 0,
          max: 14,
          defaultValue: 7,
          description: '土壤酸碱度，影响作物养分吸收',
        },
      ],
      createdAt: '2024-01-15T08:00:00Z',
      updatedAt: '2024-01-15T08:00:00Z',
    },
    {
      id: '2',
      name: '智能气象站',
      manufacturer: 'WeatherPro',
      model: 'WP-WS-200',
      category: '气象监测',
      description: '综合气象监测设备，可监测温度、湿度、风速、风向、降雨量等',
      protocol: 'MQTT',
      connectivity: '4G/WiFi',
      powerSupply: '市电+电池',
      operatingTemperature: '-40°C ~ 85°C',
      protectionRating: 'IP66',
      parameterDefinitions: [
        {
          key: 'air_temp',
          label: '空气温度',
          type: 'number',
          required: true,
          unit: '°C',
          min: -40,
          max: 85,
          description: '环境空气温度',
        },
        {
          key: 'air_humidity',
          label: '空气湿度',
          type: 'number',
          required: true,
          unit: '%',
          min: 0,
          max: 100,
          description: '相对空气湿度',
        },
        {
          key: 'wind_speed',
          label: '风速',
          type: 'number',
          required: false,
          unit: 'm/s',
          min: 0,
          max: 50,
          description: '风速监测',
        },
        {
          key: 'rainfall',
          label: '降雨量',
          type: 'number',
          required: false,
          unit: 'mm',
          min: 0,
          max: 500,
          defaultValue: 0,
          description: '累计降雨量',
        },
      ],
      createdAt: '2024-01-16T09:30:00Z',
      updatedAt: '2024-01-16T09:30:00Z',
    },
    {
      id: '3',
      name: '智能灌溉控制器',
      manufacturer: 'IrrigationTech',
      model: 'IT-IC-300',
      category: '灌溉控制',
      description: '自动化灌溉控制系统，支持定时灌溉、土壤湿度阈值控制等多种模式',
      protocol: 'Modbus RTU',
      connectivity: 'RS485',
      powerSupply: 'DC 12V',
      operatingTemperature: '-20°C ~ 60°C',
      protectionRating: 'IP65',
      parameterDefinitions: [
        {
          key: 'valve_status',
          label: '阀门状态',
          type: 'boolean',
          required: true,
          defaultValue: false,
          description: '灌溉阀门开启/关闭状态',
        },
        {
          key: 'flow_rate',
          label: '流量',
          type: 'number',
          required: true,
          unit: 'L/min',
          min: 0,
          max: 100,
          defaultValue: 0,
          description: '实时流量监测',
        },
        {
          key: 'irrigation_mode',
          label: '灌溉模式',
          type: 'select',
          required: true,
          options: [
            { label: '手动控制', value: 'manual' },
            { label: '定时灌溉', value: 'scheduled' },
            { label: '湿度控制', value: 'humidity' },
            { label: '智能控制', value: 'smart' },
          ],
          defaultValue: 'manual',
          description: '灌溉控制模式选择',
        },
      ],
      createdAt: '2024-01-17T10:15:00Z',
      updatedAt: '2024-01-17T10:15:00Z',
    },
  ];

  // 保存到 localStorage
  localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(testDeviceTypes));

  return testDeviceTypes;
}