import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lasertag_app/constants.dart';
import 'package:provider/provider.dart';
import 'dart:math';
import '../../models/device_model.dart';
import '../../models/device_config_model.dart';
import '../../providers/device_provider.dart';
import "../screens/lobby_screen.dart";

class LeaderConfigScreen extends StatefulWidget {
  final LasertagDevice device;
  const LeaderConfigScreen({super.key, required this.device});

  @override
  State<LeaderConfigScreen> createState() => _LeaderConfigScreenState();
}

class _LeaderConfigScreenState extends State<LeaderConfigScreen> {
  final _formKey = GlobalKey<FormState>();
  
  final TextEditingController _nameCtrl = TextEditingController();
  final TextEditingController _netNameCtrl = TextEditingController();
  final TextEditingController _panCtrl = TextEditingController();
  final TextEditingController _extPanCtrl = TextEditingController();
  final TextEditingController _netKeyCtrl = TextEditingController();
  
  int _selectedChannel = 15;
  bool _isLoading = true;
  bool _isSaving = false;

  // Speichert die aktuelle Konfiguration der Hardware (für RAM-Werte wie Game-ID)
  late DeviceConfig _currentConfig;

  @override
  void initState() {
    super.initState();
    _loadCurrentConfig();
  }

  /// Lädt die kompakte Konfiguration über die neue 0x100C Charakteristik
  Future<void> _loadCurrentConfig() async {
    try {
      final config = await context.read<DeviceProvider>().readDeviceConfig(widget.device);
      _currentConfig = config;

      if (mounted) {
        setState(() {
          _nameCtrl.text = config.nodeName;
          _netNameCtrl.text = config.networkName;
          _selectedChannel = config.channel;
          _panCtrl.text = "0x${config.panId.toRadixString(16).toUpperCase()}";
          _extPanCtrl.text = config.extPanId;
          _netKeyCtrl.text = config.networkKey;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text("Fehler beim Laden: $e"), backgroundColor: Colors.red),
        );
        Navigator.pop(context);
      }
    }
  }

  String? _validateHex(String? value, int requiredLength, String fieldName, {bool with0x = false}) {
    if (value == null || value.isEmpty) return "$fieldName darf nicht leer sein";
    
    String cleanValue = with0x ? value.replaceFirst('0x', '') : value;
    final hexRegex = RegExp(r'^[0-9A-Fa-f]+$');
    
    if (!hexRegex.hasMatch(cleanValue)) return "Nur Hex-Zeichen (0-9, A-F) erlaubt";
    if (cleanValue.length != requiredLength && requiredLength > 0) {
      return "Muss genau $requiredLength Zeichen lang sein";
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Leader-Konfiguration")),
      body: _isLoading 
        ? const Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16),
                Text("Lade Konfiguration via BLE..."),
              ],
            ),
          )
        : Form(
            key: _formKey,
            autovalidateMode: AutovalidateMode.onUserInteraction,
            child: ListView(
              padding: const EdgeInsets.all(16),
              children: [
                _buildSectionTitle("Allgemein"),
                TextFormField(
                  controller: _nameCtrl,
                  decoration: const InputDecoration(labelText: "Knoten-Name", helperText: "Max. 31 Zeichen"),
                  maxLength: 31,
                  validator: (v) => (v == null || v.isEmpty) ? "Name erforderlich" : null,
                  enabled: !_isSaving,
                ),

                TextFormField(
                  controller: _netNameCtrl,
                  decoration: const InputDecoration(labelText: "Thread Netzwerk-Name", helperText: "1-16 Zeichen"),
                  maxLength: 16,
                  validator: (v) => (v == null || v.isEmpty || v.length > 16) ? "1-16 Zeichen erlaubt" : null,
                  enabled: !_isSaving,
                ),

                DropdownButtonFormField<int>(
                  initialValue: _selectedChannel,
                  decoration: const InputDecoration(labelText: "Thread-Kanal (11-26)"),
                  items: List.generate(16, (i) => 11 + i)
                      .map((ch) => DropdownMenuItem(value: ch, child: Text("Kanal $ch")))
                      .toList(),
                  onChanged: _isSaving ? null : (v) => setState(() => _selectedChannel = v!),
                ),
                
                const SizedBox(height: 24),
                _buildSectionTitle("Thread Security"),

                _buildValidatedHexField("PAN ID (16-bit)", _panCtrl, 4, true),
                _buildValidatedHexField("Extended PAN ID (64-bit)", _extPanCtrl, 16, false),
                _buildValidatedHexField("Network Key (128-bit)", _netKeyCtrl, 32, false),
                
                const SizedBox(height: 32),
                _buildActionButtons(),
              ],
            ),
          ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Text(
        title, 
        style: TextStyle(
          color: Theme.of(context).colorScheme.primary, 
          fontWeight: FontWeight.bold
        )
      ),
    );
  }

  Widget _buildValidatedHexField(String label, TextEditingController ctrl, int len, bool with0x) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: TextFormField(
        controller: ctrl,
        enabled: !_isSaving,
        decoration: InputDecoration(
          labelText: label,
          suffixIcon: IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _isSaving ? null : () => setState(() {
              ctrl.text = (with0x ? "0x" : "") + _generateRandomHex(len ~/ 2);
            }),
          ),
        ),
        inputFormatters: [
          FilteringTextInputFormatter.allow(RegExp(with0x ? r'[0-9A-Fa-fXx]' : r'[0-9A-Fa-f]')),
        ],
        validator: (v) => _validateHex(v, len, label, with0x: with0x),
      ),
    );
  }

  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: OutlinedButton(
            onPressed: _isSaving ? null : () => Navigator.pop(context),
            child: const Text("Abbrechen"),
          ),
        ),
        const SizedBox(width: 16),
        Expanded(
          child: ElevatedButton(
            onPressed: _isSaving ? null : _startProvisioning,
            child: _isSaving 
              ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2)) 
              : const Text("Lobby"),
          ),
        ),
      ],
    );
  }

  /// Erstellt das neue DeviceConfig Objekt und sendet es als Block an die Hardware
  Future<void> _startProvisioning() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isSaving = true);
    try {
      // Neues Model-Objekt erstellen
      final newConfig = DeviceConfig(
        systemState: LasertagConfig.sysStateLobby, // Immer Lobby setzen
        gameId: _currentConfig.gameId == BigInt.from(0)
            ? _generateRandom64BitId()
            : _currentConfig.gameId,
        nodeName: _nameCtrl.text.trim(),
        networkName: _netNameCtrl.text.trim(),
        channel: _selectedChannel,
        panId: int.parse(_panCtrl.text.replaceFirst('0x', ''), radix: 16),
        extPanId: _extPanCtrl.text.trim(),
        networkKey: _netKeyCtrl.text.trim(),
      );

      context.read<DeviceProvider>().setActiveConfig(newConfig);
      await context.read<DeviceProvider>().provisionDevice(
        widget.device,
        newConfig,
        keepConnected: true,
      );

      if (mounted) {
        // Navigation zum Lobby Screen statt pop
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => LobbyScreen(leaderDevice: widget.device),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text("Fehler beim Speichern: $e"), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) setState(() => _isSaving = false);
    }
  }

  String _generateRandomHex(int bytes) {
    final rand = Random();
    return List.generate(bytes, (_) => rand.nextInt(256).toRadixString(16).padLeft(2, '0'))
        .join()
        .toUpperCase();
  }

  BigInt _generateRandom64BitId() {
  final random = Random.secure(); // Sicherer Zufall
  // Generiere zwei 32-Bit Werte und kombiniere sie
  final low = random.nextInt(0xFFFFFFFF);
  final high = random.nextInt(0xFFFFFFFF);
  return (BigInt.from(high) << 32) | BigInt.from(low);
}

  @override
  void dispose() {
    _nameCtrl.dispose();
    _netNameCtrl.dispose();
    _panCtrl.dispose();
    _extPanCtrl.dispose();
    _netKeyCtrl.dispose();
    super.dispose();
  }
}