import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class LoginScreen extends StatefulWidget {
  final void Function() onLoginSuccess;
  const LoginScreen({super.key, required this.onLoginSuccess});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _nameController = TextEditingController();
  String? _error;
  bool _loading = false;
  bool _isLogin = true;
  bool _isTrainer = false;

  Future<void> _submit() async {
    setState(() { _loading = true; _error = null; });
    try {
      if (_isLogin) {
        // Login
        UserCredential cred = await FirebaseAuth.instance.signInWithEmailAndPassword(
          email: _emailController.text.trim(),
          password: _passwordController.text.trim(),
        );
        // Firestore-Check
        final uid = cred.user!.uid;
        final userDoc = await FirebaseFirestore.instance.collection('User').doc(uid).get();
        if (userDoc.exists) {
          widget.onLoginSuccess();
        } else {
          setState(() { _error = 'Kein Benutzerprofil in der Datenbank gefunden!'; });
          await FirebaseAuth.instance.signOut();
        }
      } else {
        // Registrierung
        UserCredential cred = await FirebaseAuth.instance.createUserWithEmailAndPassword(
          email: _emailController.text.trim(),
          password: _passwordController.text.trim(),
        );
        // User-Datensatz in Firestore anlegen
        final uid = cred.user!.uid;
        await FirebaseFirestore.instance.collection('User').doc(uid).set({
          'email': _emailController.text.trim(),
          'name': _nameController.text.trim(),
          'role': _isTrainer ? 'trainer' : 'player',
          'createdAt': FieldValue.serverTimestamp(),
        });
        widget.onLoginSuccess();
      }
    } on FirebaseAuthException catch (e) {
      setState(() { _error = e.message ?? 'Fehler'; });
    } catch (e) {
      setState(() { _error = 'Unbekannter Fehler'; });
    } finally {
      setState(() { _loading = false; });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(_isLogin ? 'Login' : 'Registrieren', style: Theme.of(context).textTheme.headlineMedium),
                const SizedBox(height: 32),
                if (!_isLogin) ...[
                  TextFormField(
                    controller: _nameController,
                    decoration: const InputDecoration(labelText: 'Name'),
                    validator: (v) => v != null && v.trim().isNotEmpty ? null : 'Name angeben',
                  ),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Checkbox(
                        value: _isTrainer,
                        onChanged: (v) {
                          setState(() { _isTrainer = v ?? false; });
                        },
                      ),
                      const Text('Ich bin Trainer'),
                      const SizedBox(width: 16),
                      Checkbox(
                        value: !_isTrainer,
                        onChanged: (v) {
                          setState(() { _isTrainer = !(v ?? false); });
                        },
                      ),
                      const Text('Ich bin Spieler'),
                    ],
                  ),
                  const SizedBox(height: 16),
                ],
                TextFormField(
                  controller: _emailController,
                  decoration: const InputDecoration(labelText: 'E-Mail'),
                  keyboardType: TextInputType.emailAddress,
                  validator: (v) => v != null && v.contains('@') ? null : 'Gib eine gültige E-Mail ein',
                ),
                const SizedBox(height: 16),
                TextFormField(
                  controller: _passwordController,
                  decoration: const InputDecoration(labelText: 'Passwort'),
                  obscureText: true,
                  validator: (v) => v != null && v.length >= 6 ? null : 'Mind. 6 Zeichen',
                ),
                const SizedBox(height: 24),
                if (_error != null) ...[
                  Text(_error!, style: const TextStyle(color: Colors.red)),
                  const SizedBox(height: 12),
                ],
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: _loading
                        ? null
                        : () {
                            if (_formKey.currentState!.validate()) {
                              _submit();
                            }
                          },
                    child: _loading
                        ? const CircularProgressIndicator()
                        : Text(_isLogin ? 'Login' : 'Registrieren'),
                  ),
                ),
                const SizedBox(height: 16),
                TextButton(
                  onPressed: _loading
                      ? null
                      : () {
                          setState(() {
                            _isLogin = !_isLogin;
                            _error = null;
                          });
                        },
                  child: Text(_isLogin ? 'Noch keinen Account? Jetzt registrieren!' : 'Schon registriert? Jetzt einloggen!'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
} 