import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/views/service/index/cubit/service_index_cubit.dart';
import 'package:smart_hotel_app/views/service/index/cubit/service_index_state.dart';
import 'package:smart_hotel_app/views/service/index/widget/room_management_block.dart';
import 'package:smart_hotel_app/views/service/index/widget/service_head_block.dart';
import 'package:smart_hotel_app/views/service/index/widget/service_stats_block.dart';

@RoutePage()
class ServiceIndexView extends StatefulWidget {
  const ServiceIndexView({super.key});

  @override
  State<ServiceIndexView> createState() => _ServiceIndexViewState();
}

class _ServiceIndexViewState extends State<ServiceIndexView> with AutoRouteAwareStateMixin<ServiceIndexView> {
  TabsRouter? _tabsRouter;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final newRouter = AutoTabsRouter.of(context);
    if (newRouter != _tabsRouter) {
      _tabsRouter?.removeListener(_onTabChange);
      _tabsRouter = newRouter;
      _tabsRouter?.addListener(_onTabChange);
    }
  }

  @override
  void dispose() {
    _tabsRouter?.removeListener(_onTabChange);
    super.dispose();
  }

  void _onTabChange() {
    if (!mounted) return;

    if (_tabsRouter?.activeIndex == 1) {
      context.read<ServiceIndexCubit>().reloadDataIfStale();
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
        builder: (context, constraints) {
          return SingleChildScrollView(
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: constraints.maxHeight,
              ),
              child: Container(
                width: double.infinity,
                color: const Color.fromRGBO(242, 243, 245, 1),
                padding: EdgeInsets.symmetric(horizontal: 28.w),
                child: BlocBuilder<ServiceIndexCubit, ServiceIndexState>(
                  builder: (context, state) {
                    return Column(
                      children: [
                        const ServiceHeadBlock(),
                        ServiceStatsBlock(
                          pendingCount: state.pendingCount,
                          occupiedCount: state.occupiedRooms,
                          vacantCount: state.vacantRooms,
                        ),
                        const RoomManagementBlock(),
                        SizedBox(height: 18.h),
                      ],
                    );
                  },
                ),
              ),
            ),
          );
        },
    );
  }
}
