import 'package:em2rp/utils/colors.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

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

  @override
  State<ForgotPasswordDialogWidget> createState() =>
      _ForgotPasswordDialogState();
}

class _ForgotPasswordDialogState extends State<ForgotPasswordDialogWidget> {
  final _emailController = TextEditingController();
  String _errorMessage = '';
  bool _isLoading = false;
  bool _emailSent = false;

  @override
  void dispose() {
    _emailController.dispose();
    super.dispose();
  }

  Future<void> _resetPassword() async {
    setState(() {
      _errorMessage = '';
      _isLoading = true;
      _emailSent = false;
    });
    try {
      await FirebaseAuth.instance
          .sendPasswordResetEmail(email: _emailController.text.trim());
      setState(() {
        _isLoading = false;
        _emailSent = true;
      });
    } on FirebaseAuthException catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = "Erreur : ${e.message}";
        _emailSent = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Mot de passe oublié ?'),
      content: SingleChildScrollView(
        child: ListBody(
          children: <Widget>[
            if (_emailSent)
              const Text(
                  "Un email de réinitialisation a été envoyé à votre adresse.",
                  style: TextStyle(color: Colors.green)),
            if (!_emailSent) ...[
              const Text(
                  "Entrez votre adresse email pour recevoir un lien de réinitialisation."),
              const SizedBox(height: 20),
              TextField(
                controller: _emailController,
                keyboardType: TextInputType.emailAddress,
                decoration: const InputDecoration(
                  labelText: 'Email',
                  border: OutlineInputBorder(),
                ),
              ),
              if (_errorMessage.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.only(top: 10.0),
                  child: Text(_errorMessage,
                      style: const TextStyle(color: Colors.red)),
                ),
            ]
          ],
        ),
      ),
      actions: <Widget>[
        TextButton(
          child: const Text('Annuler'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        if (!_emailSent)
          ElevatedButton(
            onPressed: _isLoading ? null : _resetPassword,
            child: _isLoading
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(color: AppColors.blanc),
                  )
                : const Text('Envoyer'),
          ),
      ],
    );
  }
}
