import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:lasertag_app/l10n/app_localizations.dart';

import '../../constants.dart';
import '../../models/device_model.dart';
import '../../providers/device_provider.dart';
import '../widgets/rename_dialog.dart';
import 'leader_config_screen.dart';

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

  @override
  State<DeviceSelectionScreen> createState() => _DeviceSelectionScreenState();
}

class _DeviceSelectionScreenState extends State<DeviceSelectionScreen> {
  @override
  void initState() {
    super.initState();
    // Scan beim Starten genau einmal triggern
    // "listen: false" ist wichtig in initState
    Provider.of<DeviceProvider>(context, listen: false).startScan();
  }

  @override
  Widget build(BuildContext context) {
    // Hier "lauscht" der Screen jetzt auf Änderungen im Provider
    final provider = context.watch<DeviceProvider>();
    final l10n = AppLocalizations.of(context)!;

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.appTitle),
        actions: [
          IconButton(
            onPressed: () => context.read<DeviceProvider>().startScan(),
            icon: Icon(Icons.refresh),
          ),
        ],
      ),
      body: CustomScrollView(
        slivers: [
          _buildHeader(context, l10n.listTypeLeader),
          _buildDeviceList(context, provider.leaders, isLeader: true),

          _buildHeader(context, l10n.listTypeEquipment),
          _buildDeviceList(context, provider.peripherals, isLeader: false),
        ],
      ),
    );
  }

  Widget _buildHeader(BuildContext context, String title) {
    return SliverToBoxAdapter(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(16, 24, 16, 8),
        child: Text(
          title.toUpperCase(),
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.bold,
            color: Theme.of(context).colorScheme.secondary,
            letterSpacing: 1.2,
          ),
        ),
      ),
    );
  }

  Widget _buildDeviceList(
    BuildContext context,
    List<LasertagDevice> devices, {
    required bool isLeader,
  }) {
    return SliverList(
      delegate: SliverChildBuilderDelegate((context, index) {
        final device = devices[index];
        return ListTile(
          leading: Icon(
            _getIconForType(device.type), // Dynamisches Icon
            color: Theme.of(context).colorScheme.primary,
          ),
          title: Text(
            device.name,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontStyle: device.isNameVerified
                  ? FontStyle.normal
                  : FontStyle.italic, // Kursiv, wenn nicht verifiziert
              color: device.isNameVerified
                  ? Theme.of(context).colorScheme.onSurface
                  : Theme.of(
                      context,
                    ).colorScheme.onSurface.withValues(alpha: 0.7),
            ),
          ),
          subtitle: Text("BTLE-ID: ${device.id}"),
          trailing: const Icon(Icons.chevron_right),
          onTap: () {
            if (device.isLeader) {
              _showLeaderOptions(context, device);
            } else {
              showDialog(
                context: context,
                builder: (context) => RenameDialog(device: device),
              );
            }
          },
        );
      }, childCount: devices.length),
    );
  }

  IconData _getIconForType(int type) {
    switch (type) {
      case LasertagConfig.typeLeader:
        return Icons.hub;
      case LasertagConfig.typeWeapon:
        return Icons.flash_on; // Blitz für Waffe
      case LasertagConfig.typeVest:
        return Icons.accessibility_new; // Person für Weste
      case LasertagConfig.typeBeacon:
        return Icons.flag; // Flagge für Basis
      default:
        return Icons.device_unknown;
    }
  }

  void _showLeaderOptions(BuildContext context, LasertagDevice device) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min, // Nur so groß wie der Inhalt
            children: [
              // Ein kleiner Griff oben für die Optik
              Container(
                margin: const EdgeInsets.only(top: 12, bottom: 8),
                height: 4,
                width: 40,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(
                  device.name,
                  style: Theme.of(context).textTheme.titleLarge,
                ),
              ),
              ListTile(
                leading: const Icon(Icons.edit),
                title: const Text('Anzeigename ändern'),
                onTap: () {
                  Navigator.pop(context); // Bottom Sheet schließen
                  showDialog(
                    context: context,
                    builder: (context) => RenameDialog(device: device),
                  );
                },
              ),
              ListTile(
                leading: const Icon(Icons.hub),
                title: const Text('Als Game-Leader konfigurieren'),
                onTap: () {
                  Navigator.pop(context); // Bottom Sheet zu
                  Navigator.push(
                    // Config Screen auf
                    context,
                    MaterialPageRoute(
                      builder: (context) => LeaderConfigScreen(device: device),
                    ),
                  );
                },
              ),
              const SizedBox(height: 16), // Abstand nach unten
            ],
          ),
        );
      },
    );
  }
}
