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> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Subscribe to tab router events
    final tabsRouter = AutoTabsRouter.of(context);
    tabsRouter.addListener(_onTabChange);
  }

  @override
  void dispose() {
    final tabsRouter = AutoTabsRouter.of(context);
    tabsRouter.removeListener(_onTabChange);
    super.dispose();
  }

  void _onTabChange() {
    final tabsRouter = AutoTabsRouter.of(context);
    // Check if this tab is now active (index 1)
    if (tabsRouter.activeIndex == 1) {
      // Reload data when tab is activated
      context.read<ServiceIndexCubit>().reloadAll();
    }
  }

  @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,
                        ),
                        RoomManagementBlock(),
                        SizedBox(height: 18.h),
                      ],
                    );
                  },
                ),
              ),
            ),
          );
        },
    );
  }
}
