import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:smart_hotel_app/repositories/alert_list_repository.dart';
import 'package:smart_hotel_app/routes/app_router.gr.dart';
import 'package:smart_hotel_app/services/alert_list_service.dart';
import 'package:smart_hotel_app/views/home/abnormal_list/cubit/abnormal_list_state.dart';

/// AlarmStatus → 告警状态码（API 入参）
String? alarmStatusToApi(AlarmStatus filter) {
  switch (filter) {
    case AlarmStatus.all:
      return null;
    case AlarmStatus.pending:
      return '0';
    case AlarmStatus.processed:
      return '2';
    case AlarmStatus.falseAlarm:
      return '3';
  }
}

class AbnormalListCubit extends Cubit<AbnormalListState> {
  final AlertListService _service;

  static const int pageSize = 20;

  PagingController<int, AlarmItem>? _pagingController;

  AbnormalListCubit()
      : _service = AlertListService(
              repository: AlertListRepository(),
            ),
        super(const AbnormalListState());

  /// 绑定 PagingController（View initState 中调用）
  void bindPagingController(PagingController<int, AlarmItem> controller) {
    _pagingController = controller;
  }

  /// 解绑 PagingController（View dispose 中调用）
  void unbindPagingController() {
    _pagingController = null;
  }

  /// 供 PagingController.fetchPage 回调使用，每次加载新的一页
  Future<List<AlarmItem>> fetchPage(int pageKey) async {
    final alertList = await _service.getList(
      pageSize: pageSize,
      pageNum: pageKey,
      alertStatus: alarmStatusToApi(state.currentFilter),
    );

    // 首页时更新 tab 统计数和总数
    if (pageKey == 1) {
      emit(state.copyWith(
        totalCount: alertList.total,
        allCount: alertList.tabCount.all,
        pendingCount: alertList.tabCount.pending,
        processedCount: alertList.tabCount.processed,
        falseAlarmCount: alertList.tabCount.falseAlarm,
      ));
    }

    return alertList.rows
        .map((e) => AlarmItem.fromAlertListItemBO(e))
        .toList();
  }

  /// 切换筛选 Tab，触发重新请求
  void setFilter(AlarmStatus filter) {
    if (state.currentFilter == filter) return;
    emit(state.copyWith(currentFilter: filter));
    _pagingController?.refresh();
  }

  void onAlarmItemTap(AlarmItem item, BuildContext context) {
    final alertId = int.tryParse(item.id) ?? 0;
    context.pushRoute(AbnormalDetailRoute(alertId: alertId));
  }
}
