import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../themes/themes.dart';
import '../../viewmodels/viewmodels.dart';
import '../../widgets/widgets.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

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

class _LoginScreenState extends State<LoginScreen> {
  final _correo = TextEditingController();
  final _pass = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    _correo.dispose();
    _pass.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    final loginViewModel = Provider.of<LoginViewModel>(context);
    final obscureText = loginViewModel.obscureText;
    final errores = loginViewModel.errores;

    return Scaffold(
      backgroundColor: Color.fromRGBO(245, 245, 245, 1),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: size.width < 1200 ? 20 : 100),
              const Image(
                image: AssetImage('assets/icono.png'),
                height: 250,
              ),
              const Text(
                'Inicie sesión para acceder al sistema',
                style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 20),
              SizedBox(
                width: size.width < 1200 ? size.width : size.width * .35,
                child: Card(
                  elevation: 5,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(15)),
                  child: Padding(
                    padding: const EdgeInsets.all(15),
                    child: Column(
                      children: [
                        //CORREO ELECTRONICO
                        AppTextField(
                          autofillHints: [AutofillHints.username],
                          prefixIcon: const Icon(Icons.mail),
                          etiqueta: 'Correo electrónico',
                          hintText: 'Introduzca su correo electrónico',
                          errorText: errores?['correo'],
                          controller: _correo,
                          keyboardType: TextInputType.emailAddress,
                        ),
                        const SizedBox(height: 15),
                        //CONTRASEÑA
                        AppTextField(
                          autofillHints: [AutofillHints.newPassword],
                          maxLines: 1,
                          obscureText: obscureText,
                          prefixIcon: const Icon(Icons.lock),
                          suffixIcon: IconButton(
                            onPressed: () {
                              loginViewModel.showPassword();
                            },
                            icon: obscureText
                                ? const Icon(Icons.remove_red_eye_outlined)
                                : const Icon(Icons.remove_red_eye),
                          ),
                          onSubmitted: (v) async {
                            if (v.isEmpty) return;
                            await loginViewModel.login(
                                _correo.text, _pass.text);
                          },
                          etiqueta: 'Contraseña',
                          hintText: 'Introduzca su contraseña',
                          errorText: errores?['clave'],
                          controller: _pass,
                          keyboardType: TextInputType.visiblePassword,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 20),
              Align(
                alignment: Alignment.center,
                child: SizedBox(
                  height: 75,
                  width: 380,
                  child: ElevatedButton(
                    style: ButtonStyle(
                      shape: MaterialStatePropertyAll(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      backgroundColor:
                          MaterialStatePropertyAll(AppTheme.secondary),
                    ),
                    onPressed: () async {
                      await loginViewModel.login(_correo.text, _pass.text);
                      String mensaje = "";
                      if (loginViewModel.errores!["correo"] != null) {
                        mensaje += "\n${loginViewModel.errores!["correo"]}";
                      }
                      if (loginViewModel.errores!["pass"] != null) {
                        mensaje += "\n${loginViewModel.errores!["pass"]}";
                      }
                      if (mensaje.isNotEmpty && context.mounted) {
                        return showDialog(
                          context: context,
                          builder: (context) {
                            return AlertDialog(
                              title: const Text("Alerta"),
                              content: Text(mensaje),
                              actions: [
                                Row(children: [
                                  Expanded(
                                      child: TextButton(
                                    onPressed: () async {
                                      Navigator.pop(context);
                                    },
                                    child: const Text('Continuar'),
                                  ))
                                ])
                              ],
                            );
                          },
                        );
                      }
                    },
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          'Iniciar Sesión',
                          style: TextStyle(fontSize: 18, color: Colors.white),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }
}
