import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:laki_icu_app/services/monitoring_service.dart';

import 'default_layout_state.dart';

/// 菜单 ID 与 Tab 索引的映射
///
/// Tab 顺序必须与 mock 数据中 menuItems 的定义顺序一致：
/// 0: icu_central, 1: blood_pressure, 2: vital_signs,
/// 3: ecg_system, 4: tsaas, 5: record, 6: settings

const _menuIdToIndex = <String, int>{
  'icu_central': 0,
  'blood_pressure': 1,
  'vital_signs': 2,
  'ecg_system': 3,
  'tsaas': 4,
  'record': 5,
  'settings': 6,
  'device_control': 7
};

const _indexToMenuId = <int, String>{
  0: 'icu_central',
  1: 'blood_pressure',
  2: 'vital_signs',
  3: 'ecg_system',
  4: 'tsaas',
  5: 'record',
  6: 'settings',
  7: 'device_control',
};

/// 将 Tab 索引转换为菜单 ID
String menuIdFromIndex(int index) {
  return _indexToMenuId[index] ?? 'icu_central';
}

/// 将菜单 ID 转换为 Tab 索引
int indexFromMenuId(String menuId) {
  return _menuIdToIndex[menuId] ?? 0;
}

class DefaultLayoutCubit extends Cubit<DefaultLayoutState> {
  final MonitoringService _monitoringService;

  DefaultLayoutCubit()
      : _monitoringService = MonitoringService(),
        super(const DefaultLayoutState()) {
    _loadMenuItems();
  }

  Future<void> _loadMenuItems() async {
    emit(state.copyWith(isLoading: true, error: null));
    try {
      final menuItems = await _monitoringService.getMenuItems();
      emit(state.copyWith(isLoading: false, menuItems: menuItems));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  Future<void> refresh() async {
    await _loadMenuItems();
  }
}
