import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/alert_dashboard_bo.dart';
import 'package:smart_hotel_app/repositories/alert_dashboard_repository.dart';
import 'package:smart_hotel_app/services/alert_dashboard_service.dart';
import 'package:smart_hotel_app/views/home/index/cubit/home_index_state.dart';

class HomeIndexCubit extends Cubit<HomeIndexState> {
  final AlertDashboardService _service;

  HomeIndexCubit({AlertDashboardService? service})
      : _service = service ??
            AlertDashboardService(
              repository: AlertDashboardRepository(),
            ),
        super(const HomeIndexState()) {
    loadDashboard();
  }

  Future<void> loadDashboard() async {
    emit(state.copyWith(isLoading: true, error: null));
    try {
      final dashboard = await _service.getDashboard();
      _emitFromDashboard(dashboard);
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  Future<void> reloadDashboard() async {
    loadDashboard();
  }

  void _emitFromDashboard(AlertDashboardBO dashboard) {
    emit(state.copyWith(
      isLoading: false,
      error: null,
      highAlarmCount: dashboard.statistics.highAlertCount,
      mediumAlarmCount: dashboard.statistics.mediumAlertCount,
      onlineDeviceCount: dashboard.statistics.onlineDeviceCount,
      alerts: dashboard.alerts.take(5).toList(),
      equipmentList: dashboard.devices
          .map((d) => _mapDeviceToEquipment(d))
          .toList(),
    ));
  }

  EquipmentItem _mapDeviceToEquipment(DeviceItemBO d) {
    return EquipmentItem(
      icon: _mapDeviceIcon(d.deviceTypeIcon),
      title: d.deviceName,
      subtitle: _buildDeviceSubtitle(d),
      status: d.onlineStatus == '1' ? d.runStatusText : '离线',
      statusColor: _mapStatusColor(d.onlineStatus, d.runStatus),
    );
  }

  IconData _mapDeviceIcon(String icon) {
    switch (icon) {
      case 'power':
        return Icons.power;
      case 'wifi':
        return Icons.wifi;
      case 'thermostat':
        return Icons.thermostat;
      case 'light':
        return Icons.light;
      default:
        return Icons.devices_other;
    }
  }

  String _buildDeviceSubtitle(DeviceItemBO d) {
    final parts = <String>[];
    if (d.roomName.isNotEmpty) parts.add(d.roomName);
    if (d.temperature.isNotEmpty) parts.add('${d.temperature}°C');
    if (d.voltage.isNotEmpty) parts.add('${d.voltage}V');
    if (d.power.isNotEmpty) parts.add('${d.power}kW');
    if (d.current.isNotEmpty) parts.add('${d.current}A');
    return parts.isNotEmpty ? parts.join('·') : '';
  }

  Color _mapStatusColor(String onlineStatus, String runStatus) {
    if (onlineStatus == '0') {
      return const Color.fromRGBO(102, 102, 102, 1.0);
    }
    switch (runStatus) {
      case 'alert':
      case 'alarm':
        return const Color.fromRGBO(255, 77, 79, 1.0);
      case 'warning':
      case '注意':
        return const Color.fromRGBO(255, 193, 7, 1.0);
      default:
        return const Color.fromRGBO(26, 188, 156, 1.0);
    }
  }
}
