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> {
  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 == 2) {
      context.read<ReportIndexCubit>().reloadDataIfStale();
    }
  }

  @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(color: Color.fromRGBO(66, 165, 245, 1.0))),
            );
          }

          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, bottom: 15.h),
                    child: Column(
                      spacing: 15.h,
                      children: [
                        const ReportHeaderBlock(),
                        ReportMetricsBlock(reportMetrics: state.reportMetrics),
                        WeeklyPowerChart(weeklyPowerUsage: state.weeklyPowerUsage),
                        RoomStatusDistribution(roomStatusDistribution: state.roomStatusDistribution),
                        DeviceOnlineRate(deviceOnlineRate: state.deviceOnlineRate),
                        QuickActionsBlock(quickActions: state.quickActions),
                      ],
                    ),
                  ),
                ),
              );
            },
          );
        },
    );
  }
}
