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:laki_icu_app/blocs/device_control/device_control_bloc.dart';
import 'package:laki_icu_app/blocs/device_control/device_control_event.dart';
import 'package:laki_icu_app/blocs/device_control/device_control_state.dart';
import 'package:laki_icu_app/models/bo/monitoring_bo.dart';

import 'cubit/device_control_index_cubit.dart';
import 'cubit/device_control_index_state.dart';
import 'widgets/device_control_care_panel.dart';
import 'widgets/device_control_info_panel.dart';
import 'widgets/device_control_metric_card.dart';
import 'widgets/device_control_mode_panel.dart';
import 'widgets/device_control_oxygen_timer_panel.dart';
import 'widgets/device_control_time_panel.dart';
import 'widgets/device_control_wind_panel.dart';

@RoutePage()
class DeviceControlIndexView extends StatelessWidget {
  const DeviceControlIndexView({
    super.key,
    // this.selectedMetricLabel = '',
  });

  // final String selectedMetricLabel;

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

class DeviceControlIndexContent extends StatelessWidget {
  const DeviceControlIndexContent({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DeviceControlIndexCubit, DeviceControlIndexState>(
      builder: (context, state) {
        if (state.isLoading && state.metrics.isEmpty) {
          return const Scaffold(
            backgroundColor: Color(0xFF010B1D),
            body: Center(
              child: CircularProgressIndicator(color: Colors.white),
            ),
          );
        }
        if (state.status == DeviceControlIndexStatus.failure &&
            state.metrics.isEmpty) {
          return Scaffold(
            backgroundColor: const Color(0xFF010B1D),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '加载失败: ${state.error ?? "未知错误"}',
                    style: TextStyle(color: Colors.white, fontSize: 22.sp),
                  ),
                  SizedBox(height: 22.h),
                  ElevatedButton(
                    onPressed: () =>
                        context.read<DeviceControlIndexCubit>().loadMetrics(),
                    child: const Text('重试'),
                  ),
                ],
              ),
            ),
          );
        }

        return _DeviceControlLayout(
          metrics: state.metrics,
          selectedLabel: state.selectedMetricLabel,
          onBack: () => context.router.popForced(),
          onMetricSelected:
              context.read<DeviceControlIndexCubit>().selectMetric,
        );
      },
    );
  }
}

/// 设备控制主布局
class _DeviceControlLayout extends StatelessWidget {
  const _DeviceControlLayout({
    required this.metrics,
    required this.selectedLabel,
    required this.onBack,
    required this.onMetricSelected,
  });

  final List<MonitoringMetricBO> metrics;
  final String selectedLabel;
  final VoidCallback onBack;
  final ValueChanged<String> onMetricSelected;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF010B1D),
      body: SafeArea(
        maintainBottomViewPadding: true,
        child: Row(
          children: [
            Expanded(
              flex: 74,
              child: Column(
                children: [
                  Expanded(
                    flex: 42,
                    child: Row(
                      children: [
                        for (int index = 0;
                            index < metrics.length;
                            index++) ...[
                          Expanded(
                            child: DeviceControlMetricCard(
                              metric: metrics[index],
                            ),
                          ),
                          if (index < metrics.length - 1)
                            SizedBox(width: 24.w),
                        ],
                      ],
                    ),
                  ),
                  SizedBox(height: 24.h),
                  Expanded(
                    flex: 58,
                    child: LayoutBuilder(
                      builder: (context, constraints) {
                        final gap = 24.w;
                        final metricCardWidth =
                            (constraints.maxWidth - gap * 3) / 4;
                        final modePanelWidth = metricCardWidth * 2 + gap;

                        return Row(
                          children: [
                            SizedBox(
                              width: modePanelWidth,
                              child: const DeviceControlModePanel(),
                            ),
                            SizedBox(width: gap),
                            SizedBox(
                              width: metricCardWidth,
                              child: const DeviceControlWindPanel(),
                            ),
                            SizedBox(width: gap),
                            SizedBox(
                              width: metricCardWidth,
                              child: const DeviceControlTimePanel(),
                            ),
                          ],
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(width: 24.w),
            Expanded(
              flex: 26,
              child: Column(
                children: [
                  const Expanded(flex: 21, child: DeviceControlCarePanel()),
                  SizedBox(height: 24.h),
                  const Expanded(
                    flex: 20,
                    child: DeviceControlInfoPanel(
                      title: '新风进化',
                      actionText: 'Auto',
                      icon: Icons.cyclone,
                      body: 'CO₂超过设定值时自动启动外循环\n净化，当降至2000ppm后，本\n功能自动关闭',
                    ),
                  ),
                  SizedBox(height: 24.h),
                  Expanded(
                    flex: 20,
                    child:
                        BlocBuilder<DeviceControlBloc, DeviceControlState>(
                      buildWhen: (previous, current) =>
                          previous.data.openOxygen !=
                          current.data.openOxygen,
                      builder: (context, state) {
                        final isOn = state.data.openOxygen.isOn;
                        return DeviceControlInfoPanel(
                          title: '开放供氧',
                          actionText: isOn ? 'ON' : 'Off',
                          active: isOn,
                          icon: Icons.air,
                          body: '开启后风扇打开、制冷、加热和\n循环等设备暂停。',
                          warning: '*保持设备周围空气相对禁止，严禁烟火',
                          onTap: () => context.read<DeviceControlBloc>().add(
                                DeviceControlOpenOxygenSwitchChanged(!isOn),
                              ),
                        );
                      },
                    ),
                  ),
                  SizedBox(height: 24.h),
                  const Expanded(
                    flex: 26,
                    child: DeviceControlOxygenTimerPanel(),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
