import 'package:equatable/equatable.dart';

enum DeviceTypeEnum {
  all,
  smartBreaker,
  guestControl,
  network,
}

/// deviceTypeId 映射: all→null, smartBreaker→1, guestControl→2, network→3
int? deviceTypeIdFromEnum(DeviceTypeEnum type) {
  switch (type) {
    case DeviceTypeEnum.all:
      return null;
    case DeviceTypeEnum.smartBreaker:
      return 1;
    case DeviceTypeEnum.guestControl:
      return 2;
    case DeviceTypeEnum.network:
      return 3;
  }
}

/// 根据 API 的 deviceTypeName 匹配 DeviceTypeEnum
DeviceTypeEnum deviceTypeFromName(String typeName) {
  final name = typeName.toLowerCase();
  if (name.contains('空开') || name.contains('airswitch') || name.contains('breaker')) {
    return DeviceTypeEnum.smartBreaker;
  }
  if (name.contains('客控') || name.contains('guest')) {
    return DeviceTypeEnum.guestControl;
  }
  if (name.contains('网络') || name.contains('network')) {
    return DeviceTypeEnum.network;
  }
  return DeviceTypeEnum.smartBreaker; // fallback
}

class DeviceInfo extends Equatable {
  final int deviceId;
  final String name;
  final String room;
  final DeviceTypeEnum type;
  final bool online;
  final String status;
  final String lastUpdate;

  const DeviceInfo({
    this.deviceId = 0,
    this.name = '',
    this.room = '',
    required this.type,
    this.online = false,
    this.status = '',
    this.lastUpdate = '',
  });

  @override
  List<Object?> get props => [deviceId, name, room, type, online, status, lastUpdate];
}

class DeviceListState extends Equatable {
  final bool isLoading;
  final String? error;
  final int tabAll;
  final int tabAirSwitch;
  final int tabGuestControl;
  final int tabNetwork;
  final int totalCount;
  final DeviceTypeEnum selectedType;

  const DeviceListState({
    this.isLoading = false,
    this.error,
    this.tabAll = 0,
    this.tabAirSwitch = 0,
    this.tabGuestControl = 0,
    this.tabNetwork = 0,
    this.totalCount = 0,
    this.selectedType = DeviceTypeEnum.all,
  });

  DeviceListState copyWith({
    bool? isLoading,
    String? error,
    int? tabAll,
    int? tabAirSwitch,
    int? tabGuestControl,
    int? tabNetwork,
    int? totalCount,
    DeviceTypeEnum? selectedType,
    bool clearError = false,
  }) {
    return DeviceListState(
      isLoading: isLoading ?? this.isLoading,
      error: clearError ? null : (error ?? this.error),
      tabAll: tabAll ?? this.tabAll,
      tabAirSwitch: tabAirSwitch ?? this.tabAirSwitch,
      tabGuestControl: tabGuestControl ?? this.tabGuestControl,
      tabNetwork: tabNetwork ?? this.tabNetwork,
      totalCount: totalCount ?? this.totalCount,
      selectedType: selectedType ?? this.selectedType,
    );
  }

  @override
  List<Object?> get props => [
        isLoading,
        error,
        tabAll,
        tabAirSwitch,
        tabGuestControl,
        tabNetwork,
        totalCount,
        selectedType,
      ];
}
