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/utils/deal_utils.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> {
  TabsRouter? _tabsRouter;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 缓存引用，避免在 dispose 中通过 context 查找（此时树已不稳定）
    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 == 0) {
      context.read<HomeIndexCubit>().reloadDataIfStale();
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<HomeIndexCubit, HomeIndexState>(
      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<HomeIndexCubit>().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.symmetric(horizontal: 28.w),
                  child: 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.deviceLocation, alert.deviceCode + alert.deviceName]
          .where((s) => s.isNotEmpty)
          .join('·');

      switch (alert.alertCategory) {
        case 'temperature':
          blocks.addAll([
            SizedBox(height: 20.h),
            TemperatureBlock(
              alertId: alert.alertId,
              temperatureAlarmTitle: alert.alertTitle,
              temperatureAlarmLocation: location,
              currentTemperature: alert.temperature,
              currentVoltage: DealUtils.formatVoltage(alert.voltage),
              currentCurrent: DealUtils.formatVoltage(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: DealUtils.formatVoltage(alert.voltage),
              alertContent: alert.alertContent.isNotEmpty ?
              '${alert.alertContent}·' : '',
              voltageWaitTime: alert.waitingDurationDesc,
              voltageAlarmLevel: alert.alertLevelText,
              alertCategory: alert.alertCategory,
            ),
          ]);
      }
    }
    return blocks;
  }
}
