import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/alert_detail_bo.dart';
import 'package:smart_hotel_app/repositories/alert_detail_repository.dart';
import 'package:smart_hotel_app/services/alert_detail_service.dart';
import 'package:smart_hotel_app/views/home/abnormal/cubit/abnormal_state.dart';

class AbnormalCubit extends Cubit<AbnormalState> {
  final AlertDetailService _service;
  final int _alertId;

  AbnormalCubit({
    AlertDetailService? service,
    required int alertId,
  })  : _service = service ??
            AlertDetailService(
              repository: AlertDetailRepository(),
            ),
        _alertId = alertId,
        super(const AbnormalState()) {
    loadDetail();
  }

  Future<void> loadDetail() async {
    emit(const AbnormalState(isLoading: true));
    try {
      final detail = await _service.getDetail(alertId: _alertId);
      emit(AbnormalState(alarmInfo: _mapToAlarmInfo(detail)));
    } catch (e) {
      emit(AbnormalState(error: e.toString()));
    }
  }

  AlarmInfo _mapToAlarmInfo(AlertDetailBO detail) {
    final basic = detail.alertBasicInfo;
    final trend = detail.trendChart;
    final info = detail.alertDetailInfo;

    return AlarmInfo(
      alarmType: basic.alertTitle,
      deviceInfo: basic.alertDeviceLocation,
      alarmLevel: basic.alertLevelText,
      urgency: _mapUrgency(basic.alertLevel),
      currentTemp: info.alertValue,
      voltage: '',
      current: '',
      triggerTime: basic.alertTime,
      threshold: info.thresholdSetting,
      duration: info.duration,
      peak: info.peakRecord,
      linkAction: info.linkageAction,
      date: trend.chartDate,
      temperatureSpots: trend.dataPoints.asMap().entries.map((entry) {
        return FlSpot(entry.key.toDouble(), entry.value.value);
      }).toList(),
      alertDeviceId: basic.alertDeviceId,
    );
  }

  String _mapUrgency(String level) {
    switch (level) {
      case 'high':
        return '紧急';
      case 'medium':
        return '一般';
      default:
        return '一般';
    }
  }

  Future<void> handleConfirm() async {
    if (state.isHandling || state.isHandled) return;
    emit(state.copyWith(isHandling: true));
    try {
      await _service.handleAlert(alertId: _alertId);
      emit(state.copyWith(isHandling: false, isHandled: true));
    } catch (e) {
      emit(state.copyWith(isHandling: false));
      rethrow;
    }
  }
}