import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/device_model.dart';
import '../../providers/device_provider.dart';

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

  @override
  Widget build(BuildContext context) {
    // watch sorgt dafür, dass der Dialog reagiert, wenn sich der Cache füllt
    final activeConfig = context.watch<DeviceProvider>().activeConfig;

    return AlertDialog(
      title: const Text("Leader Details"),
      content: activeConfig == null 
        ? const Text("Keine Konfigurationsdaten im Cache gefunden.")
        : Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildInfoRow("Game ID", "0x${activeConfig.gameId.toRadixString(16).toUpperCase()}"),
              _buildInfoRow("Status", _stateToString(activeConfig.systemState)),
              const Divider(),
              _buildInfoRow("Netzwerk", activeConfig.networkName),
              _buildInfoRow("Kanal", activeConfig.channel.toString()),
              _buildInfoRow("PAN ID", "0x${activeConfig.panId.toRadixString(16).toUpperCase()}"),
              const SizedBox(height: 16),
              
              // Neuer Button für Batch-Provisioning
              SizedBox(
                width: double.infinity,
                child: FilledButton.icon(
                  onPressed: () {
                    Navigator.pop(context);
                    context.read<DeviceProvider>().batchProvisionFoundDevices();
                  },
                  icon: const Icon(Icons.bolt),
                  label: const Text("Alle Knoten provisionieren"),
                ),
              ),
            ],
          ),
      actions: [
        TextButton(onPressed: () => Navigator.pop(context), child: const Text("Schließen")),
      ],
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(color: Colors.grey)),
          Text(value, style: const TextStyle(fontFamily: 'monospace', fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }

  String _stateToString(int state) {
    const states = {1: "IDLE", 2: "LOBBY", 3: "STARTING", 4: "RUNNING", 5: "POST_GAME"};
    return states[state] ?? "Unbekannt ($state)";
  }
}