import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import '../models/device_model.dart';
import '../constants.dart';

class DeviceProvider extends ChangeNotifier {
  final List<LasertagDevice> _discoveredLeaders = [];
  final List<LasertagDevice> _discoveredPeripherals = [];
  StreamSubscription? _scanSubscription;

  List<LasertagDevice> get leaders => _discoveredLeaders;
  List<LasertagDevice> get peripherals => _discoveredPeripherals;

  void startScan() async {
    // Listen leeren für neuen Scan
    _discoveredLeaders.clear();
    _discoveredPeripherals.clear();
    notifyListeners();

    // 1. Bluetooth-Status prüfen
    await FlutterBluePlus.adapterState.where((s) => s == BluetoothAdapterState.on).first;

    // 2. Scan-Ergebnisse verarbeiten
    _scanSubscription?.cancel();
    _scanSubscription = FlutterBluePlus.scanResults.listen((results) {
      for (ScanResult r in results) {
        final mfgData = r.advertisementData.manufacturerData[65535]; // Unsere ID 0xFFFF
        
        if (mfgData != null && mfgData.isNotEmpty) {
          int type = mfgData[0]; // Typ-Byte vom nRF52
          
          final device = LasertagDevice(
            id: r.device.remoteId.toString(),
            name: r.device.platformName.isEmpty ? "Unbekannt" : r.device.platformName,
            type: type,
            isConnected: false,
          );

          _addDeviceToLists(device);
        }
      }
    });

    // 3. Scan starten (gefiltert nach unserem Service)
    try {
      await FlutterBluePlus.startScan(
        withServices: [Guid(LasertagUUIDs.provService)], //
        timeout: const Duration(seconds: 15),
      );
    } catch (e) {
      debugPrint("Scan-Fehler: $e");
    }
  }

  void _addDeviceToLists(LasertagDevice device) {
    if (device.isLeader) {
      if (!_discoveredLeaders.any((d) => d.id == device.id)) {
        _discoveredLeaders.add(device);
        _sortList(_discoveredLeaders);
        notifyListeners();
      }
    } else {
      if (!_discoveredPeripherals.any((d) => d.id == device.id)) {
        _discoveredPeripherals.add(device);
        _sortList(_discoveredPeripherals);
        notifyListeners();
      }
    }
  }

  void _sortList(List<LasertagDevice> list) {
    list.sort((a, b) {
      int typeComp = a.type.compareTo(b.type);
      if (typeComp != 0) return typeComp;
      return a.name.toLowerCase().compareTo(b.name.toLowerCase());
    });
  }

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