'use client';

export interface SensorDevice {
  id: string;
  name: string;
  type: string;
  location: string;
  fieldId: string;
  fieldName: string;
  status: 'online' | 'offline' | 'warning';
  battery: number;
  lastUpdate: string;
  sensors: {
    temperature?: number;
    humidity?: number;
    co2?: number;
    light?: number;
    pm25?: number;
  };
}

export interface IoTDevice {
  id: string;
  code: string;
  name: string;
  type: string;
  manufacturer: string;
  model: string;
  location: string;
  fieldId: string;
  fieldName: string;
  protocol: string;
  ipAddress?: string;
  mqttTopic?: string;
  status: string;
  bindingStatus: '未绑定' | '已绑定';
  bindingSystem?: string;
  lastReportTime: string;
  dataFrequency: string;
  batteryLevel?: number;
  signalStrength?: number;
  sensors: {
    name: string;
    unit: string;
    currentValue: number;
    normalRange: string;
  }[];
}

export interface EnvironmentMonitoringState {
  selectedDevice: string;
  showDeviceDialog: boolean;
  showViewDialog: boolean;
  editingDevice: SensorDevice | null;
  viewingDevice: SensorDevice | null;
  timeRange: '1h' | '6h' | '24h' | '7d';
  availableIoTDevices: IoTDevice[];
  sensorDevices: SensorDevice[];
  deviceForm: {
    iotDeviceId: string;
    location: string;
    fieldId: string;
  };
}

export type EnvironmentMonitoringAction =
  | { type: 'SET_SELECTED_DEVICE'; payload: string }
  | { type: 'SET_SHOW_DEVICE_DIALOG'; payload: boolean }
  | { type: 'SET_SHOW_VIEW_DIALOG'; payload: boolean }
  | { type: 'SET_EDITING_DEVICE'; payload: SensorDevice | null }
  | { type: 'SET_VIEWING_DEVICE'; payload: SensorDevice | null }
  | { type: 'SET_TIME_RANGE'; payload: '1h' | '6h' | '24h' | '7d' }
  | { type: 'SET_AVAILABLE_IOT_DEVICES'; payload: IoTDevice[] }
  | { type: 'SET_SENSOR_DEVICES'; payload: SensorDevice[] }
  | { type: 'SET_DEVICE_FORM'; payload: Partial<EnvironmentMonitoringState['deviceForm']> }
  | { type: 'ADD_SENSOR_DEVICE'; payload: SensorDevice }
  | { type: 'UPDATE_SENSOR_DEVICE'; payload: { id: string; updates: Partial<SensorDevice> } }
  | { type: 'DELETE_SENSOR_DEVICE'; payload: string }
  | { type: 'LOAD_IOT_DEVICES' }
  | { type: 'RESET_DEVICE_FORM' };

const availableFields = [
  { id: 'field-1', name: '东区1号地' },
  { id: 'field-2', name: '西区2号地' },
  { id: 'field-3', name: '南区3号地' },
  { id: 'field-4', name: '北区4号地' },
];

const initialSensorDevices: SensorDevice[] = [
  {
    id: 'device-1',
    name: 'ENV-001',
    type: '综合环境监测站',
    location: '东区1号地中心',
    fieldId: 'field-1',
    fieldName: '东区1号地',
    status: 'online',
    battery: 85,
    lastUpdate: '2024-10-18 15:30',
    sensors: {
      temperature: 24.5,
      humidity: 62,
      co2: 420,
      light: 45000,
      pm25: 35,
    },
  },
  {
    id: 'device-2',
    name: 'ENV-002',
    type: '气象传感器',
    location: '西区2号地北侧',
    fieldId: 'field-2',
    fieldName: '西区2号地',
    status: 'online',
    battery: 92,
    lastUpdate: '2024-10-18 15:28',
    sensors: {
      temperature: 23.8,
      humidity: 68,
      co2: 410,
      light: 42000,
      pm25: 28,
    },
  },
  {
    id: 'device-3',
    name: 'ENV-003',
    type: 'CO2监测器',
    location: '南区3号地温室',
    fieldId: 'field-3',
    fieldName: '南区3号地',
    status: 'warning',
    battery: 35,
    lastUpdate: '2024-10-18 15:25',
    sensors: {
      temperature: 26.2,
      humidity: 75,
      co2: 550,
      light: 38000,
      pm25: 42,
    },
  },
];

export const initialState: EnvironmentMonitoringState = {
  selectedDevice: 'device-1',
  showDeviceDialog: false,
  showViewDialog: false,
  editingDevice: null,
  viewingDevice: null,
  timeRange: '24h',
  availableIoTDevices: [],
  sensorDevices: initialSensorDevices,
  deviceForm: {
    iotDeviceId: '',
    location: '',
    fieldId: '',
  },
};

export function environmentMonitoringReducer(
  state: EnvironmentMonitoringState,
  action: EnvironmentMonitoringAction
): EnvironmentMonitoringState {
  switch (action.type) {
    case 'SET_SELECTED_DEVICE':
      return { ...state, selectedDevice: action.payload };

    case 'SET_SHOW_DEVICE_DIALOG':
      return { ...state, showDeviceDialog: action.payload };

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

    case 'SET_EDITING_DEVICE':
      return { ...state, editingDevice: action.payload };

    case 'SET_VIEWING_DEVICE':
      return { ...state, viewingDevice: action.payload };

    case 'SET_TIME_RANGE':
      return { ...state, timeRange: action.payload };

    case 'SET_AVAILABLE_IOT_DEVICES':
      return { ...state, availableIoTDevices: action.payload };

    case 'SET_SENSOR_DEVICES':
      return { ...state, sensorDevices: action.payload };

    case 'SET_DEVICE_FORM':
      return {
        ...state,
        deviceForm: { ...state.deviceForm, ...action.payload }
      };

    case 'ADD_SENSOR_DEVICE':
      return {
        ...state,
        sensorDevices: [...state.sensorDevices, action.payload]
      };

    case 'UPDATE_SENSOR_DEVICE':
      return {
        ...state,
        sensorDevices: state.sensorDevices.map(device =>
          device.id === action.payload.id
            ? { ...device, ...action.payload.updates }
            : device
        )
      };

    case 'DELETE_SENSOR_DEVICE':
      return {
        ...state,
        sensorDevices: state.sensorDevices.filter(device => device.id !== action.payload)
      };

    case 'LOAD_IOT_DEVICES':
      try {
        const data = localStorage.getItem('smart_agriculture_ai_iot_devices');
        if (data) {
          const devices: IoTDevice[] = JSON.parse(data);
          const environmentDevices = devices.filter(
            d => d.type === '环境监测站' && d.bindingStatus === '未绑定'
          );
          return { ...state, availableIoTDevices: environmentDevices };
        }
      } catch (error) {
        console.error('Failed to load IoT devices:', error);
      }
      return { ...state, availableIoTDevices: [] };

    case 'RESET_DEVICE_FORM':
      return {
        ...state,
        deviceForm: {
          iotDeviceId: '',
          location: '',
          fieldId: '',
        }
      };

    default:
      return state;
  }
}