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/routes/app_router.gr.dart';
import 'package:smart_hotel_app/views/home/inspection/cubit/inspection_cubit.dart';
import 'package:smart_hotel_app/views/home/inspection/cubit/inspection_state.dart';
import 'package:smart_hotel_app/views/home/inspection/widget/device_list.dart';
import 'package:smart_hotel_app/views/home/inspection/widget/filter_panel.dart';

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

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

class _InspectionDetailBody extends StatefulWidget {
  const _InspectionDetailBody();

  @override
  State<_InspectionDetailBody> createState() => _InspectionDetailBodyState();
}

class _InspectionDetailBodyState extends State<_InspectionDetailBody> {
  late final PagingController<int, InspectionDevice> _pagingController;
  DeviceStatusTab? _lastTab;
  List<int>? _lastRoomIds;

  @override
  void initState() {
    super.initState();
    _pagingController = PagingController<int, InspectionDevice>(
      getNextPageKey: (state) {
        if (state.keys == null || state.keys!.isEmpty) return 1;
        return state.lastPageIsEmpty ? null : state.nextIntPageKey;
      },
      fetchPage: (pageKey) =>
          context.read<InspectionCubit>().fetchPage(pageKey),
    );
  }

  void _checkFilterChanged(InspectionState state) {
    if (_lastTab != state.selectedTab ||
        _lastRoomIds != state.selectedRoomIds) {
      _lastTab = state.selectedTab;
      _lastRoomIds = state.selectedRoomIds;
      _pagingController.refresh();
    }
  }

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

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

    return BlocListener<InspectionCubit, InspectionState>(
      listener: (context, state) {
        if (_lastTab != null) {
          _checkFilterChanged(state);
        }
      },
      child: BlocBuilder<InspectionCubit, InspectionState>(
        builder: (context, state) {
          _checkFilterChanged(state);

          if (state.isLoading) {
            return Scaffold(
              backgroundColor: const Color.fromRGBO(242, 243, 245, 1),
              appBar: _buildAppBar(context),
              body: const Center(child: CircularProgressIndicator()),
            );
          }

          if (state.error != null) {
            return Scaffold(
              backgroundColor: const Color.fromRGBO(242, 243, 245, 1),
              appBar: _buildAppBar(context),
              body: Center(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 28.w),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        '加载失败: ${state.error}',
                        style: TextStyle(
                          fontSize: 28.sp,
                          color:
                              const Color.fromRGBO(255, 100, 101, 1),
                        ),
                        textAlign: TextAlign.center,
                      ),
                      SizedBox(height: 24.h),
                      ElevatedButton(
                        onPressed: () => cubit.initData(),
                        child: Text('重新加载',
                            style: TextStyle(fontSize: 28.sp)),
                      ),
                    ],
                  ),
                ),
              ),
            );
          }

          return Scaffold(
            backgroundColor: const Color.fromRGBO(242, 243, 245, 1),
            appBar: _buildAppBar(context),
            body: PagingListener<int, InspectionDevice>(
              controller: _pagingController,
              builder: (context, pagingState, fetchNextPage) {
                return CustomScrollView(
                  slivers: [
                    SliverPadding(
                      padding: EdgeInsets.symmetric(
                          horizontal: 28.w, vertical: 20.h),
                      sliver: SliverToBoxAdapter(
                        child: FilterPanel(
                          selectedTab: state.selectedTab,
                          tabCounts: state.tabCounts,
                          onTabSelected: cubit.selectTab,
                          selectedRoomIds: state.selectedRoomIds,
                          allRooms: state.allRooms,
                          onRoomToggle: cubit.toggleRoom,
                        ),
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(height: 20.h),
                    ),
                    DeviceList(
                      pagingState: pagingState,
                      fetchNextPage: fetchNextPage,
                      onTap: (item, ctx) {
                        ctx.pushRoute(InspectionDeviceRoute(
                            deviceId: item.id));
                      },
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(height: 30.h),
                    ),
                  ],
                );
              },
            ),
          );
        },
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return 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.w200,
        ),
      ),
      centerTitle: true,
    );
  }
}