import 'dart:async';

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/enums/video_stream_mode_enum.dart';
import 'package:laki_icu_app/models/bo/monitoring_bo.dart';
import 'package:laki_icu_app/utils/event_bus.dart';


import 'cubit/monitoring_index_cubit.dart';
import 'cubit/monitoring_index_state.dart';
import 'widgets/bluetooth_bind_dialog.dart';
import 'widgets/monitoring_alert_card.dart';
import 'widgets/monitoring_alert_detail_dialog.dart';
import 'widgets/monitoring_metric_card.dart';
import 'widgets/monitoring_pet_info_card.dart';
import 'widgets/video_player_widget.dart';

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

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

class MonitoringIndexContent extends StatefulWidget {
  const MonitoringIndexContent({super.key});

  @override
  State<MonitoringIndexContent> createState() => _MonitoringIndexContentState();
}

class _MonitoringIndexContentState extends State<MonitoringIndexContent> {
  late final MonitoringIndexCubit _monitoringIndexCubit;
  StreamSubscription<OpenBluetoothScanEvent>? _bluetoothScanEventSub;
  /// 正在弹出框展示的告警，为空表示当前没有弹窗
  AlertInfoBO? _currentDialogAlert;

  @override
  void initState() {
    super.initState();
    _monitoringIndexCubit = context.read<MonitoringIndexCubit>();
    _bluetoothScanEventSub = eventBus.on<OpenBluetoothScanEvent>().listen((_) {
      if (!mounted) return;
      _showBluetoothDialog();
    });
  }

  @override
  void dispose() {
    _bluetoothScanEventSub?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<MonitoringIndexCubit, MonitoringIndexState>(
      listenWhen: (previous, current) =>
          current.selectedAlert != null &&
          current.selectedAlert != previous.selectedAlert,
      listener: (context, state) {
        _showAlertDetailDialog(state.selectedAlert!);
      },
      child: BlocBuilder<MonitoringIndexCubit, MonitoringIndexState>(
        builder: (context, state) {
          if (state.isLoading && state.metrics.isEmpty) {
            return const Center(
              child: CircularProgressIndicator(color: Colors.white),
            );
          }
          if (state.status == MonitoringIndexStatus.failure &&
              state.metrics.isEmpty) {
            return _buildError(state.error);
          }
          return _buildMainArea(state);
        },
      ),
    );
  }

  Widget _buildError(String? error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '加载失败: ${error ?? '未知错误'}',
            style: TextStyle(color: Colors.white, fontSize: 22.sp),
          ),
          SizedBox(height: 22.h),
          ElevatedButton(
            onPressed: () => _monitoringIndexCubit.loadData(),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildMainArea(MonitoringIndexState state) {
    return Row(
      children: [
        Expanded(
          flex: 26,
          child: MonitoringPetInfoCard(
            patientInfo: state.patientInfo,
            onExit: () => _monitoringIndexCubit.clearPatientInfo(),
            onBindPet: () => _monitoringIndexCubit.setTestPatientInfo(),
          ),
        ),
        SizedBox(width: 24.w),
        Expanded(
          flex: 74,
          child: Column(
            children: [
              Expanded(
                flex: 32,
                child: _buildMetrics(state.metrics),
              ),
              SizedBox(height: 24.h),
              Expanded(
                flex: 34,
                child: Row(
                  children: [
                    Expanded(
                      flex: 10,
                      child: MonitoringAlertCard(
                        alerts: [
                          ...state.cameraAlerts,
                          ...state.alerts,
                        ],
                      ),
                    ),
                    SizedBox(width: 10.w),
                    Expanded(
                      flex: 10,
                      child: VideoPlayerWidget(
                        streamMode: state.videoStreamMode,
                        isSwitchingMode: state.isSwitchingMode,
                        webrtcRenderer:
                            _monitoringIndexCubit.webrtcService.renderer,
                        webrtcConnectionState: state.videoConnectionState,
                        p2pController: _monitoringIndexCubit
                            .p2pVideoService.playerController,
                        isP2pConnected: state.isP2pConnected,
                        onRetry: () => _monitoringIndexCubit.retryCurrentMode(),
                        onToggleMode: _onToggleStreamMode,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // ignore: unused_element
  Widget _buildMetricsEmpty() {
    return Container(
      width: double.infinity,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('lib/assets/monitoring/box_no_device.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            '暂无设备连接 TSAAS ICU',
            style: TextStyle(
              color: Colors.white,
              fontSize: 30.sp,
            ),
          ),
          SizedBox(height: 80.h),
          GestureDetector(
            onTap: _showBluetoothDialog,
            child: Container(
              width: 388.w,
              height: 62.h,
              decoration:  const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('lib/assets/monitoring/title_bg_spacewalk.png'),
                  fit: BoxFit.cover,
                ),
              ),
              child: Center(
                child: Text(
                  '绑定设备',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 32.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMetrics(List<MonitoringMetricBO> metrics) {
    final displayMetrics = _environmentMetrics(metrics);
    final children = <Widget>[];
    for (int i = 0; i < displayMetrics.length; i++) {
      children.add(
        Expanded(
          child: MonitoringMetricCard(
            metric: displayMetrics[i],
            onTap: () => _openDeviceControl(displayMetrics[i]),
          ),
        ),
      );
      if (i < displayMetrics.length - 1) {
        children.add(SizedBox(width: 20.w));
      }
    }
    return Row(
      children: children,
    );
  }

  void _openDeviceControl(MonitoringMetricBO metric) {
    context.tabsRouter.setActiveIndex(7);
  }

  /// 模式切换回调
  void _onToggleStreamMode() {
    final cubit = _monitoringIndexCubit;
    final currentMode = cubit.state.videoStreamMode;
    final nextMode = currentMode == VideoStreamMode.p2p
        ? VideoStreamMode.webrtc
        : VideoStreamMode.p2p;
    cubit.switchStreamMode(nextMode);
  }

  void _showBluetoothDialog() {
    showDialog<void>(
      context: context,
      builder: (_) => BlocProvider.value(
        value: _monitoringIndexCubit,
        child: const BluetoothBindDialog(),
      ),
    );
  }

  void _showAlertDetailDialog(AlertInfoBO alert) {
    // 已有弹窗在展示，忽略新的请求
    if (_currentDialogAlert != null) return;
    _currentDialogAlert = alert;

    showDialog<void>(
      context: context,
      builder: (_) => BlocProvider.value(
        value: _monitoringIndexCubit,
        child: MonitoringAlertDetailDialog(alert: alert),
      ),
    ).whenComplete(() {
      // 使用 whenComplete 替代 then，确保无论 Future 成功或失败都会清理状态，
      // 防止 _currentDialogAlert 锁死导致后续点击永远无法弹出 dialog
      _currentDialogAlert = null;
      _monitoringIndexCubit.clearSelectedAlert();
    });
  }

  List<MonitoringMetricBO> _environmentMetrics(
      List<MonitoringMetricBO> metrics) {
    final matched = metrics
        .where((item) =>
            item.label.contains('温度') ||
            item.label.contains('湿度') ||
            item.label.contains('氧气') ||
            item.label.contains('二氧化碳') ||
            item.label.toUpperCase().contains('CO'))
        .take(4)
        .toList();

    if (matched.length == 4) return matched;

    return const [
      MonitoringMetricBO(value: '--', unit: '℃', label: '舱内温度'),
      MonitoringMetricBO(value: '--', unit: 'RH', label: '舱内湿度'),
      MonitoringMetricBO(value: '--', unit: '%', label: '氧气浓度'),
      MonitoringMetricBO(value: '--', unit: '%', label: '二氧化碳'),
    ];
  }
}
