import 'package:flutter/material.dart';
import 'package:werwolf/screens/settings.dart';

// Define the PlayerRegistry StatefulWidget
class PlayerRegistry extends StatefulWidget {
  const PlayerRegistry({super.key});

  @override
  // Create the state for the PlayerRegistry widget
  // ignore: library_private_types_in_public_api
  _PlayerRegistryState createState() => _PlayerRegistryState();
}

// Define the state for the PlayerRegistry widget
class _PlayerRegistryState extends State<PlayerRegistry> {
  final TextEditingController _playerController = TextEditingController(); // Controller for player name input
  final _formKey = GlobalKey<FormState>(); // Key for form validation
  String _errorMessage = ""; // Error message string
  List<String> playernames = []; // List to store player names

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Werwolf"), // App bar title
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(15),
              child: TextField(
                key: _formKey,
                controller: _playerController,
                decoration: InputDecoration(
                  errorText: _errorMessage == "" ? null : _errorMessage, // Display error message if exists
                  labelText: 'Spielername', // Label for text field
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.primary),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.primary),
                  ),
                  errorBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.secondary),
                  ),
                  focusedErrorBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.secondary),
                  ),
                ),
                onSubmitted: (value) {
                  setState(() {
                    if (_playerController.text.isEmpty) {
                      _errorMessage = "Spielername ist leer!"; // Error for empty name
                    } else if (playernames.contains(value)) {
                      _errorMessage = "Dieser Spieler existiert bereits"; // Error for duplicate name
                      _playerController.clear();
                    } else {
                      _errorMessage = "";
                      _playerController.clear();
                      playernames.add(value); // Add valid player name to list
                    }
                  });
                },
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: playernames.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(
                      playernames[index], // Display player name
                    ),
                    trailing: IconButton(
                        onPressed: () {
                          setState(() {
                            playernames.remove(playernames[index]); // Remove player name from list
                          });
                        },
                        icon: const Icon(Icons.remove)), // Remove icon button
                  );
                },
              ),
            ),
            ElevatedButton(
              onPressed: () {
                if (playernames.length >= 6) {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => GameSettings(
                          playernames: playernames, // Pass player names to next screen
                        ),
                      ));
                } else {
                  setState(() {
                    _errorMessage = "Es müssen mindestens 6 Spieler sein!"; // Error for not enough players
                  });
                }
              },
              child: const Text('Spiel einstellen'), // Button to start game settings
            ),
            const Padding(padding: EdgeInsets.all(30))
          ],
        ),
      ),
    );
  }
}
