import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

/// A dialog that displays a list of paired Bluetooth devices for the user to select.
Future<BluetoothDevice?> showBluetoothDeviceListDialog({
  required BuildContext context,
  required List<BluetoothDevice> devices,
}) {
  return showDialog<BluetoothDevice>(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('Select a Paired Device'),
        content: SizedBox(
          width: double.maxFinite,
          child: ListView.builder(
            itemCount: devices.length,
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              final device = devices[index];
              return ListTile(
                title: Text(device.name ?? 'Unknown Device'),
                subtitle: Text(device.address),
                onTap: () {
                  // When a device is tapped, pop the dialog and return the selected device.
                  Navigator.of(context).pop(device);
                },
              );
            },
          ),
        ),
        actions: <Widget>[
          TextButton(
            child: const Text('Cancel'),
            onPressed: () {
              // Pop the dialog and return null if canceled.
              Navigator.of(context).pop(null);
            },
          ),
        ],
      );
    },
  );
}
