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 '../../routes/app_router.gr.dart';
import '../../utils/event_bus.dart';
import 'cubit/default_layout_cubit.dart';
import 'cubit/default_layout_state.dart';
import 'widgets/monitoring_bottom_menu.dart';
import 'widgets/monitoring_top_status_bar.dart';

@RoutePage()
class DefaultLayoutView extends StatelessWidget {
  const DefaultLayoutView({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => DefaultLayoutCubit(),
      child: const _DefaultLayoutContent(),
    );
  }
}

class _DefaultLayoutContent extends StatelessWidget {
  const _DefaultLayoutContent();

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DefaultLayoutCubit, DefaultLayoutState>(
      builder: (context, state) {
        if (state.isLoading) {
          return const Scaffold(
            backgroundColor: Color(0xFF010B1D),
            body: Center(
              child: CircularProgressIndicator(color: Colors.white),
            ),
          );
        }

        if (state.error != null && state.menuItems.isEmpty) {
          return Scaffold(
            backgroundColor: const Color(0xFF010B1D),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '菜单加载失败: ${state.error}',
                    style: const TextStyle(color: Colors.white),
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () =>
                        context.read<DefaultLayoutCubit>().refresh(),
                    child: const Text('重试'),
                  ),
                ],
              ),
            ),
          );
        }

        return AutoTabsScaffold(
          backgroundColor: const Color(0xFF010B1D),
          resizeToAvoidBottomInset: false,
          homeIndex: 0,
          routes: const [
            MonitoringIndexRoute(),
            BloodPressureIndexRoute(),
            VitalSignsIndexRoute(),
            EcgSystemIndexRoute(),
            TsaasIndexRoute(),
            RecordIndexRoute(),
            SettingsIndexRoute(),
            DeviceControlIndexRoute(), // index=7,该路由实际不在菜单栏。
          ],
          appBarBuilder: (context, tabsRouter) {
            return PreferredSize(
              preferredSize: Size.fromHeight(104.h),
              child: Container(
                decoration: const BoxDecoration(),
                child: Stack(
                  children: [
                    Positioned(
                      right: 10,
                      top: 20,
                      child: Image.asset(
                        'lib/assets/monitoring/top_line.png',
                        width: 906.w,
                        height: 162.h,
                      ),
                    ),
                    SizedBox(
                      height: 104.h,
                      child: const MonitoringTopStatusBar(),
                    ),
                  ],
                ),
              ),
            );
          },
          bottomNavigationBuilder: (context, tabsRouter) {
            final selectedMenuId = menuIdFromIndex(tabsRouter.activeIndex);
            return MonitoringBottomMenu(
              menuItems: state.menuItems,
              selectedMenuId: selectedMenuId,
              onMenuItemTap: (menuId) {
                if (menuId == 'tsaas') {
                  if (tabsRouter.activeIndex != 0) {
                    tabsRouter.setActiveIndex(0);
                  }
                  WidgetsBinding.instance.addPostFrameCallback((_) {
                    eventBus.emit(OpenBluetoothScanEvent());
                  });
                  return;
                }
                final index = indexFromMenuId(menuId);
                tabsRouter.setActiveIndex(index);
              },
            );
          },
        );
      },
    );
  }
}
