import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:smart_hotel_app/views/home/abnormal_list/cubit/abnormal_list_cubit.dart';
import 'package:smart_hotel_app/views/home/abnormal_list/cubit/abnormal_list_state.dart';
import 'package:smart_hotel_app/views/home/abnormal_list/widget/alarm_list_item.dart';
import 'package:smart_hotel_app/views/home/abnormal_list/widget/filter_tab_block.dart';

@RoutePage()
class AbnormalListView extends StatelessWidget {
  const AbnormalListView({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => AbnormalListCubit(),
      child: const _AbnormalListBody(),
    );
  }
}

class _AbnormalListBody extends StatefulWidget {
  const _AbnormalListBody();

  @override
  State<_AbnormalListBody> createState() => _AbnormalListBodyState();
}

class _AbnormalListBodyState extends State<_AbnormalListBody> {
  late final PagingController<int, AlarmItem> _pagingController;
  late final AbnormalListCubit _cubit;

  @override
  void initState() {
    super.initState();
    _cubit = context.read<AbnormalListCubit>();
    _pagingController = PagingController<int, AlarmItem>(
      getNextPageKey: (state) {
        if (state.keys == null || state.keys!.isEmpty) return 1;
        final total = _cubit.state.totalCount;
        final nextKey = state.nextIntPageKey;
        if ((nextKey - 1) * AbnormalListCubit.pageSize >= total) {
          return null;
        }
        return nextKey;
      },
      fetchPage: (pageKey) => _cubit.fetchPage(pageKey),
    );
    _cubit.bindPagingController(_pagingController);
  }

  @override
  void dispose() {
    _pagingController.dispose();
    _cubit.unbindPagingController();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final cubit = context.read<AbnormalListCubit>();

    return BlocBuilder<AbnormalListCubit, AbnormalListState>(
      builder: (context, state) {
        return Scaffold(
          backgroundColor: const Color.fromRGBO(242, 243, 245, 1),
          appBar: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios,
                  color: Color.fromRGBO(100, 116, 139, 1)),
              onPressed: () {
                context.popRoute();
              },
            ),
            title: Text(
              '告警信息',
              style: TextStyle(
                color: const Color.fromRGBO(10, 13, 20, 1),
                fontSize: 32.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
            centerTitle: true,
          ),
          body: PagingListener<int, AlarmItem>(
            controller: _pagingController,
            builder: (context, pagingState, fetchNextPage) {
              return CustomScrollView(
                slivers: [
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 28.w),
                      child: FilterTabBlock(
                        currentFilter: state.currentFilter,
                        onFilterChanged: cubit.setFilter,
                        allCount: state.allCount,
                        pendingCount: state.pendingCount,
                        processedCount: state.processedCount,
                        falseAlarmCount: state.falseAlarmCount,
                      ),
                    ),
                  ),
                  SliverPadding(
                    padding: EdgeInsets.symmetric(horizontal: 28.w),
                    sliver: PagedSliverList<int, AlarmItem>(
                      state: pagingState,
                      fetchNextPage: fetchNextPage,
                      builderDelegate: PagedChildBuilderDelegate<AlarmItem>(
                        firstPageProgressIndicatorBuilder: (_) => const Center(
                          child: CircularProgressIndicator(
                            color: Color.fromRGBO(66, 165, 245, 1.0),
                          ),
                        ),
                        newPageProgressIndicatorBuilder: (_) => const Center(
                          child: Padding(
                            padding: EdgeInsets.all(16),
                            child: CircularProgressIndicator(
                              color: Color.fromRGBO(66, 165, 245, 1.0),
                            ),
                          ),
                        ),
                        firstPageErrorIndicatorBuilder: (_) => Center(
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                '加载失败: ${pagingState.error}',
                                style: TextStyle(
                                  fontSize: 28.sp,
                                  color: const Color.fromRGBO(
                                      255, 100, 101, 1),
                                ),
                                textAlign: TextAlign.center,
                              ),
                              SizedBox(height: 24.h),
                              ElevatedButton(
                                onPressed: fetchNextPage,
                                child: Text('重新加载',
                                    style:
                                        TextStyle(fontSize: 28.sp)),
                              ),
                            ],
                          ),
                        ),
                        noItemsFoundIndicatorBuilder: (_) => Padding(
                          padding: EdgeInsets.only(top: 60.h),
                          child: Text(
                            '暂无数据',
                            style: TextStyle(
                              fontSize: 28.sp,
                              color: const Color.fromRGBO(
                                  100, 116, 139, 1),
                            ),
                          ),
                        ),
                        newPageErrorIndicatorBuilder: (_) => Center(
                          child: Padding(
                            padding:
                                EdgeInsets.symmetric(vertical: 20.h),
                            child: Column(
                              children: [
                                Text(
                                  '加载失败: ${pagingState.error}',
                                  style: TextStyle(
                                    fontSize: 24.sp,
                                    color: const Color.fromRGBO(
                                        255, 100, 101, 1),
                                  ),
                                ),
                                SizedBox(height: 12.h),
                                TextButton(
                                  onPressed: fetchNextPage,
                                  child: Text('重试',
                                      style:
                                          TextStyle(fontSize: 24.sp)),
                                ),
                              ],
                            ),
                          ),
                        ),
                        itemBuilder: (_, item, __) {
                          return AlarmListItem(
                            item: item,
                            onTap: (i) { cubit.onAlarmItemTap(i, context); },
                          );
                        },
                      ),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: SizedBox(height: 30.h),
                  ),
                ],
              );
            },
          ),
        );
      },
    );
  }
}