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

import '../../../core/models/models.dart';
import '../../../utils/themes.dart';
import '../../viewmodels/viewmodels.dart';
import '../../../utils/widgets/widgets.dart';
import '../home/home_screen.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 _contrasena = TextEditingController();
  Sucursal? _selectedSucursal;

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

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

    // Verifica la sesión almacenada
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final loginViewModel =
          Provider.of<LoginViewModel>(context, listen: false);

      Provider.of<PermisoViewModel>(context, listen: false)
          .sincronizarPermisos();
      Provider.of<UsuarioViewModel>(context, listen: false)
          .sincronizarUsuarios();

      // Verificar la sesión
      loginViewModel.checkSession().then((_) {
        if (loginViewModel.status == Status.authenticated) {
          print("Sesión activa detectada, redirigiendo al HomeScreen.");
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => const HomeScreen()),
          );
        } else {
          print("No se detectó sesión, mostrando la pantalla de login.");
          final sucursalViewModel =
              Provider.of<SucursalViewModel>(context, listen: false);
          sucursalViewModel.sincronizarSucursales().then((_) {
            setState(() {
              final sucursales = sucursalViewModel.sucursales;
              _selectedSucursal = sucursales.firstWhere(
                (sucursal) => sucursal.seleccionado == 1,
                orElse: () =>
                    sucursales.isNotEmpty ? sucursales[0] : Sucursal(),
              );
            });
          });
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final loginViewModel = Provider.of<LoginViewModel>(context);

    // Mostrar la pantalla de carga `Cargando` mientras verifica la sesión
    if (loginViewModel.isLoading) {
      return const Cargando();
    }

    final size = MediaQuery.sizeOf(context);
    final sucursalViewModel = Provider.of<SucursalViewModel>(context);
    final sucursales = sucursalViewModel.sucursales;
    final obscureText = loginViewModel.obscureText;
    final errores = loginViewModel.errores;

    return Scaffold(
      backgroundColor: const 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/logo.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),
              // Campo de correo
              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: [
                        AppDropdownModel<Sucursal>(
                          etiqueta: 'Seleccione una sucursal',
                          hint: 'Elija una sucursal',
                          selectedValue: _selectedSucursal,
                          onChanged: (Sucursal? newValue) {
                            setState(() {
                              _selectedSucursal = newValue;
                            });
                          },
                          items: sucursales.map((Sucursal sucursal) {
                            return DropdownMenuItem<Sucursal>(
                              value: sucursal,
                              child: Text(
                                sucursal.nombre ?? '',
                                style: const TextStyle(color: Colors.black),
                              ),
                            );
                          }).toList(),
                        ),
                        const SizedBox(height: 5),
                        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: 5),
                        AppTextField(
                          prefixIcon: const Icon(Icons.lock),
                          obscureText: obscureText,
                          etiqueta: 'Contraseña',
                          hintText: 'Introduzca su contraseña',
                          errorText: errores?['contrasena'],
                          controller: _contrasena,
                          suffixIcon: IconButton(
                            onPressed: () {
                              loginViewModel.showPassword();
                            },
                            icon: obscureText
                                ? const Icon(Icons.remove_red_eye_outlined)
                                : const Icon(Icons.remove_red_eye),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 20),
              // Botón de login
              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, _contrasena.text);

                      if (loginViewModel.status == Status.authenticated) {
                        if (_selectedSucursal != null) {
                          await sucursalViewModel
                              .setSelectedSucursal(_selectedSucursal!);
                        }

                        Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                              builder: (context) => const HomeScreen()),
                        );
                      } else {
                        String mensaje = "";
                        if (loginViewModel.errores?["correo"] != null) {
                          mensaje += "\n${loginViewModel.errores!["correo"]}";
                        }
                        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),
            ],
          ),
        ),
      ),
    );
  }
}
