import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:laki_icu_app/utils/bluetooth/index.dart';
import 'package:laki_icu_app/views/monitoring/index/cubit/monitoring_index_cubit.dart';
import 'package:laki_icu_app/views/monitoring/index/cubit/monitoring_index_state.dart';

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

  @override
  State<BluetoothBindDialog> createState() => _BluetoothBindDialogState();
}

class _BluetoothBindDialogState extends State<BluetoothBindDialog> {
  bool _hasAutoStartedScan = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted || _hasAutoStartedScan) return;
      _hasAutoStartedScan = true;
      final cubit = context.read<MonitoringIndexCubit>();
      if (!cubit.state.isBluetoothScanning) {
        cubit.scanBluetoothDevices();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: const Color(0xFFF4F4F4),
      insetPadding: EdgeInsets.zero,
      child: BlocBuilder<MonitoringIndexCubit, MonitoringIndexState>(
        builder: (context, state) {
          return SizedBox.expand(
            child: _buildContent(context, state),
          );
        },
      ),
    );
  }

  Widget _buildContent(BuildContext context, MonitoringIndexState state) {
    return Container(
      width: double.infinity,
      // margin: EdgeInsets.fromLTRB(16.w, 0, 16.w, 16.h),
      padding: EdgeInsets.fromLTRB(108.w, 52.h, 108.w, 94.h),
      decoration: BoxDecoration(
        color: const Color(0xFF79A9EE),
        border: Border.all(color: const Color(0xFF0799FF), width: 3.w),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildTopBar(context),
          SizedBox(height: 38.h),
          Expanded(child: _buildDevicePanel(context, state)),
        ],
      ),
    );
  }

  Widget _buildTopBar(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '设备连接',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 49.sp,
                  fontWeight: FontWeight.w400,
                ),
              ),
              SizedBox(height: 14.h),
              Text(
                '搜索蓝牙设备完成配对连接',
                style: TextStyle(
                  color: Colors.white.withValues(alpha: 0.84),
                  fontSize: 29.sp,
                ),
              ),
            ],
          ),
        ),
        IconButton(
          onPressed: () => Navigator.of(context).pop(),
          icon: Icon(Icons.close, color: Colors.white, size: 48.w),
          tooltip: '关闭',
          padding: EdgeInsets.zero,
          constraints: BoxConstraints.tight(Size(64.w, 64.w)),
        ),
      ],
    );
  }

  Widget _buildDevicePanel(BuildContext context, MonitoringIndexState state) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.fromLTRB(72.w, 56.h, 72.w, 34.h),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Color(0xFF0028E8), Color(0xFF001646)],
        ),
        borderRadius: BorderRadius.circular(14.r),
        border: Border.all(color: Colors.white.withValues(alpha: 0.2)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.26),
            blurRadius: 12.r,
            offset: Offset(0, 6.h),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildPanelStatus(context, state),
          SizedBox(height: 28.h),
          Expanded(child: _buildDeviceList(context, state)),
        ],
      ),
    );
  }

  Widget _buildPanelStatus(BuildContext context, MonitoringIndexState state) {
    final message = state.isBluetoothScanning
        ? '自动发现附近可配对的监护舱设备，搜索中...'
        : state.bluetoothDevices.isEmpty
            ? '未发现设备，可重新搜索附近蓝牙设备'
            : '蓝牙扫描结束，共发现 ${state.bluetoothDevices.length} 个设备';

    return Row(
      children: [
        Expanded(
          child: Text(
            message,
            style: TextStyle(
              color: Colors.white.withValues(alpha: 0.88),
              fontSize: 28.sp,
              fontWeight: FontWeight.w400,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        SizedBox(width: 16.w),
        TextButton.icon(
          onPressed: state.isBluetoothScanning
              ? null
              : () =>
                  context.read<MonitoringIndexCubit>().scanBluetoothDevices(),
          icon: state.isBluetoothScanning
              ? SizedBox(
                  width: 18.w,
                  height: 18.w,
                  child: CircularProgressIndicator(
                    strokeWidth: 2.w,
                    color: Colors.white,
                  ),
                )
              : Icon(Icons.refresh, size: 22.w),
          label: Text(state.isBluetoothScanning ? '搜索中' : '重新搜索'),
          style: TextButton.styleFrom(
            foregroundColor: Colors.white,
            disabledForegroundColor: Colors.white70,
            textStyle: TextStyle(fontSize: 24.sp),
          ),
        ),
      ],
    );
  }

  Widget _buildDeviceList(BuildContext context, MonitoringIndexState state) {
    if (state.bluetoothDevices.isEmpty) {
      return Center(
        child: Text(
          state.isBluetoothScanning ? '正在扫描附近设备...' : '暂无设备',
          style: TextStyle(
            color: Colors.white.withValues(alpha: 0.76),
            fontSize: 31.sp,
          ),
        ),
      );
    }

    final devices = _sortDevicesForDisplay(state);

    return ListView.separated(
      padding: EdgeInsets.zero,
      itemCount: devices.length,
      separatorBuilder: (_, __) => SizedBox(height: 18.h),
      itemBuilder: (context, index) {
        final device = devices[index];
        final isBound = state.boundBluetoothDeviceId == device.remoteId;
        final isBinding = state.bindingBluetoothDeviceId == device.remoteId;

        return _BluetoothDeviceRow(
          key: ValueKey(device.remoteId),
          device: device,
          isBound: isBound,
          isBinding: isBinding,
          isDisabled: state.isBluetoothBinding,
          onTap: isBound
              ? () => _confirmUnbindBluetoothDevice(context, device)
              : () => context.read<MonitoringIndexCubit>().bindBluetoothDevice(
                    device,
                  ),
        );
      },
    );
  }

  List<BluetoothScanDevice> _sortDevicesForDisplay(MonitoringIndexState state) {
    final boundDeviceId = state.boundBluetoothDeviceId;
    if (boundDeviceId == null || boundDeviceId.isEmpty) {
      return state.bluetoothDevices;
    }

    return List<BluetoothScanDevice>.from(state.bluetoothDevices)
      ..sort((left, right) {
        final leftIsBound = left.remoteId == boundDeviceId;
        final rightIsBound = right.remoteId == boundDeviceId;
        if (leftIsBound == rightIsBound) {
          return 0;
        }
        return leftIsBound ? -1 : 1;
      });
  }

  Future<void> _confirmUnbindBluetoothDevice(
    BuildContext context,
    BluetoothScanDevice device,
  ) async {
    final shouldUnbind = await showDialog<bool>(
      context: context,
      builder: (dialogContext) {
        return AlertDialog(
          title: const Text('解绑蓝牙设备'),
          content: Text('是否要解绑 ${device.name}？解绑后可重新选择设备绑定。'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(dialogContext).pop(false),
              child: const Text('取消'),
            ),
            FilledButton(
              onPressed: () => Navigator.of(dialogContext).pop(true),
              child: const Text('确认解绑'),
            ),
          ],
        );
      },
    );

    if (shouldUnbind == true && context.mounted) {
      await context.read<MonitoringIndexCubit>().unbindBluetoothDevice();
    }
  }
}

class _BluetoothDeviceRow extends StatelessWidget {
  const _BluetoothDeviceRow({
    super.key,
    required this.device,
    required this.isBound,
    required this.isBinding,
    required this.isDisabled,
    required this.onTap,
  });

  final BluetoothScanDevice device;
  final bool isBound;
  final bool isBinding;
  final bool isDisabled;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    const highlightColor = Color(0xFF00F6FF);
    final textColor = isBound ? highlightColor : Colors.white;
    final statusText = isBound
        ? '已连接'
        : isBinding
            ? '连接中'
            : '未连接';

    return InkWell(
      onTap: isDisabled ? null : onTap,
      borderRadius: BorderRadius.circular(8.r),
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 0, vertical: 14.h),
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    device.name,
                    style: TextStyle(
                      color: textColor,
                      fontSize: 33.sp,
                      fontWeight: isBound ? FontWeight.w600 : FontWeight.w400,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 5.h),
                  Text(
                    '${device.remoteId}  RSSI ${device.rssi}',
                    style: TextStyle(
                      color: Colors.white.withValues(alpha: 0.42),
                      fontSize: 20.sp,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            SizedBox(width: 32.w),
            SizedBox(
              width: 138.w,
              child: Text(
                statusText,
                textAlign: TextAlign.left,
                style: TextStyle(
                  color: textColor,
                  fontSize: 32.sp,
                  fontWeight: isBound ? FontWeight.w600 : FontWeight.w400,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
