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/models/bo/alert_dashboard_bo.dart';
import 'package:smart_hotel_app/views/home/index/cubit/home_index_cubit.dart';
import 'package:smart_hotel_app/views/home/index/cubit/home_index_state.dart';
import 'package:smart_hotel_app/views/home/index/widget/equipment_list_block.dart';
import 'package:smart_hotel_app/views/home/index/widget/task_head_block.dart';
import 'package:smart_hotel_app/views/home/index/widget/task_total_block.dart';
import 'package:smart_hotel_app/views/home/index/widget/temperature_block.dart';
import 'package:smart_hotel_app/views/home/index/widget/voltage_operate_block.dart';

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

  @override
  State<HomeView> createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> with AutoRouteAwareStateMixin<HomeView> {
  @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
    if (tabsRouter.activeIndex == 0) {
      // Reload data when tab is activated
      context.read<HomeIndexCubit>().reloadDashboard();
    }
  }

  @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<HomeIndexCubit, HomeIndexState>(
                  builder: (context, state) {
                    return Column(
                      children: [
                        const TaskHeadBlock(),
                        SizedBox(height: 20.h),
                        TaskTotalBlock(
                          highAlarmCount: state.highAlarmCount,
                          mediumAlarmCount: state.mediumAlarmCount,
                          onlineDeviceCount: state.onlineDeviceCount,
                        ),
                        ..._buildAlertBlocks(state.alerts),
                        SizedBox(height: 20.h),
                        EquipmentListBlock(
                          equipmentList: state.equipmentList,
                        ),
                        SizedBox(height: 20.h),
                      ],
                    );
                  },
                ),
              ),
            ),
          );
        },
    );
  }

  List<Widget> _buildAlertBlocks(List<AlertItemBO> alerts) {
    final blocks = <Widget>[];
    for (final alert in alerts) {
      final location = '${alert.roomName}·${alert.deviceName}';
      switch (alert.alertCategory) {
        case 'temperature':
          blocks.addAll([
            SizedBox(height: 20.h),
            TemperatureBlock(
              alertId: alert.alertId,
              temperatureAlarmTitle: alert.alertTitle,
              temperatureAlarmLocation: location,
              currentTemperature: alert.temperature,
              currentVoltage: alert.voltage,
              currentCurrent: alert.current,
              waitTime: alert.waitingDurationDesc,
              alarmLevel: alert.alertLevelText,
            ),
          ]);
        case 'voltage':
        case 'current':
        case 'device':
        case 'power':
          blocks.addAll([
            SizedBox(height: 20.h),
            VoltageOperateBlock(
              alertId: alert.alertId,
              voltageAlarmTitle: alert.alertTitle,
              voltageAlarmLocation: location,
              voltageValue: alert.voltage,
              normalVoltage: '',
              voltageWaitTime: alert.waitingDurationDesc,
              voltageAlarmLevel: alert.alertLevelText,
            ),
          ]);
      }
    }
    return blocks;
  }
}
