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:smart_hotel_app/views/report/index/cubit/report_index_cubit.dart';
import 'package:smart_hotel_app/views/report/index/cubit/report_index_state.dart';
import 'package:smart_hotel_app/views/report/index/widget/device_online_rate.dart';
import 'package:smart_hotel_app/views/report/index/widget/quick_actions_block.dart';
import 'package:smart_hotel_app/views/report/index/widget/report_header_block.dart';
import 'package:smart_hotel_app/views/report/index/widget/report_metrics_block.dart';
import 'package:smart_hotel_app/views/report/index/widget/room_status_distribution.dart';
import 'package:smart_hotel_app/views/report/index/widget/weekly_power_chart.dart';

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

  @override
  State<ReportIndexView> createState() => _ReportIndexViewState();
}

class _ReportIndexViewState extends State<ReportIndexView> with AutoRouteAwareStateMixin<ReportIndexView> {
  @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 2)
    if (tabsRouter.activeIndex == 2) {
      // Reload data when tab is activated
      context.read<ReportIndexCubit>().reloadData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ReportIndexCubit, ReportIndexState>(
        builder: (context, state) {
          if (state.isLoading) {
            return Container(
              color: const Color.fromRGBO(242, 243, 245, 1),
              child: const Center(child: CircularProgressIndicator()),
            );
          }
          if (state.error != null) {
            return Container(
              color: const Color.fromRGBO(242, 243, 245, 1),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      '加载失败: ${state.error}',
                      style: TextStyle(
                        fontSize: 28.sp,
                        color: const Color.fromRGBO(100, 116, 139, 1),
                      ),
                    ),
                    SizedBox(height: 16.h),
                    ElevatedButton(
                      onPressed: () =>
                          context.read<ReportIndexCubit>().loadData(),
                      child: const Text('重试'),
                    ),
                  ],
                ),
              ),
            );
          }
          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.only(
                        left: 28.w,
                        right: 28.w,
                        top: ScreenUtil().statusBarHeight),
                    child: Column(
                      children: [
                        ReportHeaderBlock(
                            reportHeader: state.reportHeader),
                        SizedBox(height: 10.h),
                        ReportMetricsBlock(
                            reportMetrics: state.reportMetrics),
                        SizedBox(height: 10.h),
                        WeeklyPowerChart(
                            weeklyPowerUsage: state.weeklyPowerUsage),
                        SizedBox(height: 10.h),
                        RoomStatusDistribution(
                            roomStatusDistribution:
                                state.roomStatusDistribution),
                        SizedBox(height: 10.h),
                        DeviceOnlineRate(
                            deviceOnlineRate: state.deviceOnlineRate),
                        SizedBox(height: 10.h),
                        QuickActionsBlock(
                            quickActions: state.quickActions),
                        SizedBox(height: 10.h),
                      ],
                    ),
                  ),
                ),
              );
            },
          );
        },
    );
  }
}
