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/report/device/cubit/device_list_cubit.dart';
import 'package:smart_hotel_app/views/report/device/cubit/device_list_state.dart';
import 'package:smart_hotel_app/views/report/device/widget/device_card.dart';
import 'package:smart_hotel_app/views/report/device/widget/device_filter_tab.dart';

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

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

class _ReportDeviceListBody extends StatefulWidget {
  const _ReportDeviceListBody();

  @override
  State<_ReportDeviceListBody> createState() => _ReportDeviceListBodyState();
}

class _ReportDeviceListBodyState extends State<_ReportDeviceListBody> {
  late final PagingController<int, DeviceInfo> _pagingController;
  late final DeviceListCubit _cubit;

  @override
  void initState() {
    super.initState();
    _cubit = context.read<DeviceListCubit>();
    _pagingController = PagingController<int, DeviceInfo>(
      getNextPageKey: (state) {
        if (state.keys == null || state.keys!.isEmpty) return 1;
        final total = _cubit.state.totalCount;
        final nextKey = state.nextIntPageKey;
        if (nextKey == null) return null;
        if ((nextKey - 1) * DeviceListCubit.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) {
    return BlocBuilder<DeviceListCubit, DeviceListState>(
      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, color: Colors.black),
              onPressed: () {
                context.popRoute();
              },
            ),
            title: Text(
              '全部设备',
              style: TextStyle(
                color: Colors.black,
                fontSize: 32.sp,
                fontWeight: FontWeight.bold,
              ),
            ),
            centerTitle: true,
          ),
          body: PagingListener<int, DeviceInfo>(
            controller: _pagingController,
            builder: (context, pagingState, fetchNextPage) {
              return CustomScrollView(
                slivers: [
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 28.w),
                      child: Column(
                        children: [
                          SizedBox(height: 10.h),
                          DeviceFilterTab(
                            selectedType: state.selectedType,
                            onSelect: (type) {
                              context
                                  .read<DeviceListCubit>()
                                  .selectType(type);
                            },
                          ),
                          SizedBox(height: 10.h),
                        ],
                      ),
                    ),
                  ),
                  SliverPadding(
                    padding: EdgeInsets.symmetric(horizontal: 28.w),
                    sliver: PagedSliverList<int, DeviceInfo>(
                      state: pagingState,
                      fetchNextPage: fetchNextPage,
                      builderDelegate:
                          PagedChildBuilderDelegate<DeviceInfo>(
                        firstPageErrorIndicatorBuilder: (_) => Center(
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              SizedBox(height: 60.h),
                              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 Padding(
                            padding: EdgeInsets.only(bottom: 10.h),
                            child: DeviceCard(device: item),
                          );
                        },
                      ),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: SizedBox(height: 20.h),
                  ),
                ],
              );
            },
          ),
        );
      },
    );
  }
}
