import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:prosappco/src/components/pop_appbar.dart';
import 'package:prosappco/src/components/primary_btn.dart';

class NewPasswordScreen extends StatefulWidget {
  NewPasswordScreen({super.key});

  @override
  State<NewPasswordScreen> createState() => _NewPasswordScreenState();
}

class _NewPasswordScreenState extends State<NewPasswordScreen> {
  final _currentPasswordController = TextEditingController();
  final _newPasswordController = TextEditingController();
  bool _obscureText = true;
  bool _obscureText2 = true;

  final FirebaseAuth _auth = FirebaseAuth.instance;

  Future<void> updatePassword(
      String currentPassword, String newPassword) async {
    final User user = _auth.currentUser!;

    final credential = EmailAuthProvider.credential(
      email: user.email!,
      password: currentPassword,
    );

    try {
      if (newPassword == currentPassword) {
        Get.snackbar(
          'Misma contraseña',
          'La nueva contraseña debe ser diferente a la contraseña actual.',
          snackPosition: SnackPosition.BOTTOM,
        );
        return;
      } else if (newPassword.isEmpty) {
        Get.snackbar(
          'Ingrese una contraseña valida',
          'La nueva contraseña no puede estar vacia.',
          snackPosition: SnackPosition.BOTTOM,
        );
        return;
      } else {
        await user.reauthenticateWithCredential(credential);
        try {
          await user.updatePassword(newPassword);
          // Muestra un mensaje de éxito
          Get.snackbar(
            'Contraseña actualizada',
            'La contraseña ha sido actualizada correctamente.',
            snackPosition: SnackPosition.BOTTOM,
          );
        } catch (e) {
          print("Error al verificar la contraseña actual: $e");
        }
      }
    } catch (e) {
      Get.snackbar(
        'Contraseña incorrecta',
        'Error al actualizar la contraseña asegurese de ingresar bien la contraseña actual.',
        snackPosition: SnackPosition.BOTTOM,
      );
      return;
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: PopAppbar(
          onPressed: () {
            Navigator.pop(context);
          },
          label: 'Cambie su contraseña',
        ),
        body: Center(
          child: SizedBox(
            width: 300,
            child: Padding(
              padding: const EdgeInsets.only(top: 100),
              child: Column(
                children: [
                  TextFormField(
                    controller: _currentPasswordController,
                    obscureText: _obscureText,
                    decoration: InputDecoration(
                        prefixIcon: const Icon(Icons.lock_outline),
                        suffixIcon: IconButton(
                          icon: Icon(
                            _obscureText
                                ? Icons.visibility
                                : Icons.visibility_off,
                            color: Colors.grey,
                          ),
                          onPressed: () {
                            setState(() {
                              _obscureText = !_obscureText;
                            });
                          },
                        ),
                        hintText: 'Contraseña (Actual)'),
                  ),
                  const SizedBox(height: 40.0),
                  TextFormField(
                    controller: _newPasswordController,
                    obscureText: _obscureText2,
                    decoration: InputDecoration(
                        prefixIcon: const Icon(Icons.lock_outline),
                        suffixIcon: IconButton(
                          icon: Icon(
                            _obscureText2
                                ? Icons.visibility
                                : Icons.visibility_off,
                            color: Colors.grey,
                          ),
                          onPressed: () {
                            setState(() {
                              _obscureText2 = !_obscureText2;
                            });
                          },
                        ),
                        hintText: 'Contraseña (Nueva)'),
                  ),
                  const SizedBox(height: 80.0),
                  PrimaryButtom(
                      onPressed: () {
                        updatePassword(_currentPasswordController.text.trim(),
                            _newPasswordController.text.trim());
                      },
                      label: 'Actualizar contraseña'),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
