import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/linkage_rule_bo.dart';
import 'package:smart_hotel_app/repositories/linkage_rule_repository.dart';
import 'package:smart_hotel_app/services/linkage_rule_service.dart';
import 'package:smart_hotel_app/views/report/rule/cubit/rule_management_state.dart';

class RuleManagementCubit extends Cubit<RuleManagementState> {
  final LinkageRuleService _service;

  RuleManagementCubit({LinkageRuleService? service})
      : _service = service ??
            LinkageRuleService(repository: LinkageRuleRepository()),
        super(const RuleManagementState()) {
    loadRules();
  }

  Future<void> loadRules() async {
    emit(state.copyWith(isLoading: true, clearError: true));
    try {
      final rules = await _service.getRules();
      emit(state.copyWith(isLoading: false, rules: rules.map(_toRuleInfo).toList()));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  /// 根据规则名称映射图标
  IconData _mapIcon(String ruleName) {
    // final name = ruleName.toLowerCase();
    // if (name.contains('退房') || name.contains('logout')) {
    //   return Icons.logout_outlined;
    // }
    // if (name.contains('清洁') || name.contains('灯') || name.contains('clean')) {
    //   return Icons.cleaning_services_outlined;
    // }
    // if (name.contains('温度') || name.contains('thermostat')) {
    //   return Icons.thermostat_outlined;
    // }
    // if (name.contains('深夜') || name.contains('night')) {
    //   return Icons.nightlight_outlined;
    // }
    // if (name.contains('定时') || name.contains('巡检') || name.contains('time')) {
    //   return Icons.access_time_outlined;
    // }
    return Icons.tune;
  }

  RuleInfo _toRuleInfo(LinkageRuleBO bo) {
    return RuleInfo(
      ruleId: bo.ruleId,
      name: bo.ruleName,
      description: bo.description,
      enabled: bo.isEnabled,
      icon: _mapIcon(bo.ruleName),
    );
  }

  /// 启用/禁用联动规则（View 层传入 String id）
  Future<void> toggleRule(String id) async {
    final ruleId = int.tryParse(id) ?? 0;
    if (ruleId == 0) return;
    if (state.isToggling) return; // 防重复提交

    final previousRules = List<RuleInfo>.from(state.rules);
    final index = state.rules.indexWhere((r) => r.ruleId == ruleId);
    if (index == -1) return;

    final currentEnabled = state.rules[index].enabled;
    final newEnabled = !currentEnabled;

    // 乐观更新 UI
    final updatedRules = List<RuleInfo>.from(state.rules);
    updatedRules[index] = updatedRules[index].copyWith(enabled: newEnabled);
    emit(state.copyWith(
      rules: updatedRules,
      isToggling: true,
      togglingRuleId: ruleId,
    ));

    try {
      await _service.toggleRule(
        ruleId: ruleId,
        enabled: newEnabled ? '1' : '0',
      );
      emit(state.copyWith(isToggling: false));
    } catch (e) {
      // 失败回滚
      emit(state.copyWith(
        rules: previousRules,
        isToggling: false,
        error: e.toString(),
      ));
    }
  }
}
