import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:localstore/localstore.dart';
import 'package:quiosco_soler_2/memorias_calculo/pages/verificacion.dart';
import 'package:quiosco_soler_2/memorias_calculo/widgets/formatters.dart';

import '../providers/login_provider.dart';
import '../providers/nueva_cuenta_provider.dart';
import '../widgets/cargando.dart';

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

  @override
  State<LoginMemorias> createState() => _LoginMemoriasState();
}

class _LoginMemoriasState extends State<LoginMemorias> {
  final _loginProvider = LoginProvider();
  final _nuevaCuentaProvider = NuevaCuentaProvider();
  final db = Localstore.instance;

  final Map<String, String> _paisContinente = {};
  final Map<String, List<String>> _estados = {};
  final Map<String, Map<String, List<String>>> _municipios = {};
  final Map<String, String> _continentes = {
    "EUR" : "Europa",
    "ASI" : "Asia",
    "AFR" : "Africa",
    "OCE" : "Oceanía",
    "AMN" : "América del norte",
    "AMS" : "América del sur",
    "AMC" : "América central"
  };
  final List<String> _paises = [];

  final TextEditingController _nombreController = TextEditingController();
  final TextEditingController _apepatController = TextEditingController();
  final TextEditingController _apematController = TextEditingController();
  final TextEditingController _raSocController = TextEditingController();
  final TextEditingController _ciudadController = TextEditingController();
  final TextEditingController _estadoController = TextEditingController();
  final TextEditingController _numTelController = TextEditingController();
  final TextEditingController _correoController = TextEditingController();
  final TextEditingController _contraController = TextEditingController();
  final TextEditingController _confContraController = TextEditingController();

  final Map<String, bool> _errores = {
    "nombre": false,
    "ciudad": false,
    "numTel": false,
    "correo": false,
    "contra": false,
    "confContra": false,
    "estado": false,
    "raSoc": false
  };

  bool _isLoading = true;
  bool _tieneCuenta = true;
  bool _numCliente = false;
  bool _tieneEstados = true;
  bool _tieneCiudades = true;
  bool _numeroValido = true;
  bool _correoValido = true;
  bool _contraValida = true;
  bool _contrasIguales = true;
  bool _esperando = false;
  bool _obscurePass = true;
  bool _obscureConfirmPass = true;

  String _continenteAct = "AMN";
  String _esDistribuidor = "No";
  String _pais = "";
  String _paisCode = "";
  String _estado = "";
  String _estadoCode = "";
  String _municipio = "";
  String _idUsuario = "";
  String _accessToken = "";

  @override
  void initState() {
    super.initState();
    readJson().then((value){
      if(mounted) setState(() => _isLoading = false);
    });
  }

  Future<void> readJson() async{
    final String paisesEstados = await rootBundle.loadString(('assets/paises_db_simple.json'));
    final String municipios = await rootBundle.loadString('assets/paises_db.json');
    final String munMex = await rootBundle.loadString('assets/municipios_mx.json');

    final paisesEstadosArr = await jsonDecode(paisesEstados);
    final paises = paisesEstadosArr['paises'];
    final estados = paisesEstadosArr['estados'];

    paises.forEach((pais){
      _paisContinente[pais['CountryCode']] = pais['ContinentCode'];
      _paises.add("${pais['CountryName']} (${pais['CountryCode']})");
    });

    estados.forEach((estado){
      final pais = _estados[estado['SUCountry']];
      if(pais == null){
        _estados[estado['SUCountry']] = ["${estado['SUName'].trim()} (${estado['SUCode']})"];
      }else{
        pais.add("${estado['SUName'].trim()} (${estado['SUCode']})");
        _estados[estado['SUCountry']] = pais;
      }
    });

    final munMexDec = await jsonDecode(munMex);
    final munIntDec = await jsonDecode(municipios);

    munIntDec[0]["data"].forEach((item){
      final pais = _municipios[item["Country"]];
      if(pais == null){
        _municipios[item["Country"]] = {};
      }

      if(item["Subdivision"] != null) {
        final tmpEsta = _municipios[item["Country"]]![item["Subdivision"]];

        if(tmpEsta == null){
          _municipios[item["Country"]]![item["Subdivision"]] = [item["Name"]];
        }else{
          tmpEsta.add(item["Name"]);
          _municipios[item["Country"]]![item["Subdivision"]] = tmpEsta;
        }
      }
    });

    final municipiosMx = munMexDec["c_Municipio"];
    Map<String, List<String>> tmpMunMx = {};

    municipiosMx.forEach((municipioMx){
      final tmpEdoMx = tmpMunMx[municipioMx["c_Estado"]];

      if(tmpEdoMx == null){
        tmpMunMx[municipioMx["c_Estado"]] = [municipioMx["Descripción"]];
      }else{
        tmpEdoMx.add(municipioMx["Descripción"]);
        tmpMunMx[municipioMx["c_Estado"]] = tmpEdoMx;
      }
    });

    _municipios["MX"]!["MOR"] = tmpMunMx["MOR"]!;
  }

  Future<bool> registrarInfo({
    required String nombre,
    required String pais,
    required String estado,
    required String ciudad,
    required String movil,
    required String correo,
    required String contra,
    required String apepat,
    required String contConf,
    required String apemat,
    required String distribuidor,
    String? razonSoc,
    String? numCli,
  }) async{
    final registro = await _nuevaCuentaProvider.registrarNuevaCuenta(
      nombre: nombre,
      pais: pais,
      estado: estado,
      ciudad: ciudad,
      movil: movil,
      correo: correo,
      contra: contra,
      apepat: apepat,
      contConf: contConf,
      apemat: apemat,
      distribuidor: distribuidor,
      razonSoc: razonSoc,
      numCli: numCli,
    );

    Fluttertoast.showToast(
      msg: registro.message,
      toastLength: Toast.LENGTH_SHORT,
      timeInSecForIosWeb: 4,
      gravity: ToastGravity.CENTER,
      webBgColor: registro.response ? "linear-gradient(to right, #266B1F, #98F58F)" : "linear-gradient(to right, #b40404, #ff0000)",
    );

    _idUsuario = registro.result.idUsuario;
    _accessToken = registro.result.token;

    return registro.response;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _isLoading ? Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: const [
            CircularProgressIndicator(),
            SizedBox(height: 8.0),
            Cargando(text: "Cargando datos del sistema.")
          ],
        ),
      ) : SafeArea(
        child: LayoutBuilder(builder: (context, constraints) {
          final parentHeight = constraints.maxHeight;
          final parentWidth = constraints.maxWidth;

          List<String> paisesDrop = [];
          _paises.forEach((pais) {
            final codeArr = pais.split(" ");
            String code = codeArr.last;
            code = code.replaceAll("(", "");
            code = code.replaceAll(")", "");

            String flag = code.toUpperCase();
            flag = flag.replaceAllMapped(RegExp(r'[A-Z]'), (match) => String.fromCharCode(match.group(0)!.codeUnitAt(0) + 127397));

            final continente = _paisContinente[code];
            if(continente == _continenteAct && code != "MX"){
              paisesDrop.add("$flag - $pais");
            }
          });

          if(_continenteAct == "AMN"){
            const codeMx = "MX";
            final flag = codeMx.replaceAllMapped(RegExp(r'[A-Z]'), (match) => String.fromCharCode(match.group(0)!.codeUnitAt(0) + 127397));
            paisesDrop.insert(0, "$flag - México (MX)");
          }

          return SizedBox(
            width: parentWidth,
            height: parentHeight,
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  const SizedBox(
                    height: 32.0,
                  ),
                  Row(
                    children: [
                      const SizedBox(width: 32.0),
                      Image.asset(
                        "assets/logo.png",
                        width: 64.0,
                      ),
                      const SizedBox(width: 16.0),
                      Expanded(
                        child: Image.asset("assets/logo_completo.png",),
                      ),
                      const SizedBox(width: 32.0),
                    ],
                  ),
                  const SizedBox(
                    height: 32.0,
                  ),
                  Image.asset(
                    "assets/matriz.png",
                    width: 88.0,
                    fit: BoxFit.cover,
                  ),
                  const SizedBox(
                    height: 16.0,
                  ),
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 32.0,
                    ),
                    child: const Text(
                      "PORTAL DE MEMORIAS DE CÁLCULO",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontFamily: "Helvetica Neue Black Cond",
                        fontSize: 28.0,
                      ),
                    ),
                  ),
                  const SizedBox(
                    height: 8.0,
                  ),
                  AnimatedContainer(
                    duration: const Duration(
                      milliseconds: 250,
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 32.0),
                    width: double.infinity,
                    child: Text(
                      _tieneCuenta
                          ? "Para usar este módulo es necesario tener una cuenta, por favor proporciona tus datos para continuar:"
                          : "Completa el siguiente formulario para crear tu cuenta:",
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        fontFamily: "Helvetica Neue Light",
                        fontSize: 22.0,
                        fontWeight: FontWeight.w600,
                        color: Color.fromRGBO(104, 104, 104, 1),
                      ),
                    ),
                  ),
                  const SizedBox(
                    height: 32.0,
                  ),
                  AnimatedContainer(
                    duration: const Duration(
                      milliseconds: 250,
                    ),
                    width: double.infinity,
                    margin: const EdgeInsets.symmetric(horizontal: 32.0),
                    child: Column(
                      children: [
                        if(!_tieneCuenta)
                          Column(
                            children: [
                              SizedBox(
                                width: parentWidth,
                                child: Text(
                                  "Nombre(s):",
                                  style: GoogleFonts.roboto(
                                    color: const Color.fromRGBO(102, 102, 102, 1),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                              Container(
                                margin: const EdgeInsets.only(bottom: 8.0),
                                child: TextField(
                                  controller: _nombreController,
                                  decoration: InputDecoration(
                                    hintText: "Juan",
                                    hintStyle: GoogleFonts.roboto(
                                      color: Colors.grey,
                                      fontStyle: FontStyle.italic,
                                    ),
                                    errorText: _errores["nombre"]! ? "*Campo obligatorio." : null,
                                    errorStyle: GoogleFonts.roboto(
                                      color: const Color(0xFFFF0000),
                                      fontSize: 12.0,
                                    ),
                                  ),
                                  style: GoogleFonts.roboto(),
                                  onChanged: (value) => setState(() => _errores["nombre"] = false),
                                ),
                              )
                            ],
                          ),
                        if(!_tieneCuenta)
                          const SizedBox(height: 8.0),
                        if(!_tieneCuenta)
                          Column(
                            children: [
                              SizedBox(
                                width: parentWidth,
                                child: Text(
                                  "Apellido paterno:",
                                  style: GoogleFonts.roboto(
                                    color: const Color.fromRGBO(102, 102, 102, 1),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                              Container(
                                margin: const EdgeInsets.only(bottom: 8.0),
                                child: TextField(
                                  controller: _apepatController,
                                  decoration: InputDecoration(
                                    hintText: "Pérez",
                                    hintStyle: GoogleFonts.roboto(
                                      color: Colors.grey,
                                      fontStyle: FontStyle.italic,
                                    ),
                                    errorText: _errores["nombre"]! ? "*Campo obligatorio." : null,
                                    errorStyle: GoogleFonts.roboto(
                                      color: const Color(0xFFFF0000),
                                      fontSize: 12.0,
                                    ),
                                  ),
                                  style: GoogleFonts.roboto(),
                                  onChanged: (value) => setState(() => _errores["nombre"] = false),
                                ),
                              )
                            ],
                          ),
                        if(!_tieneCuenta)
                          const SizedBox(height: 8.0),
                        if(!_tieneCuenta)
                          Column(
                            children: [
                              SizedBox(
                                width: parentWidth,
                                child: Text(
                                  "Apellido materno:",
                                  style: GoogleFonts.roboto(
                                    color: const Color.fromRGBO(102, 102, 102, 1),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                              Container(
                                margin: const EdgeInsets.only(bottom: 8.0),
                                child: TextField(
                                  controller: _apematController,
                                  decoration: InputDecoration(
                                    hintText: "González",
                                    hintStyle: GoogleFonts.roboto(
                                      color: Colors.grey,
                                      fontStyle: FontStyle.italic,
                                    ),
                                    errorText: _errores["nombre"]! ? "*Campo obligatorio." : null,
                                    errorStyle: GoogleFonts.roboto(
                                      color: const Color(0xFFFF0000),
                                      fontSize: 12.0,
                                    ),
                                  ),
                                  style: GoogleFonts.roboto(),
                                  onChanged: (value) => setState(() => _errores["nombre"] = false),
                                ),
                              )
                            ],
                          ),
                        if(!_tieneCuenta)
                          const SizedBox(height: 8.0),
                        if(!_tieneCuenta)
                          Column(
                            children: [
                              Row(
                                children: [
                                  Text(
                                    "Es distribuidor:",
                                    style: GoogleFonts.roboto(
                                      color: const Color.fromRGBO(102, 102, 102, 1),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16.0,
                                    ),
                                  ),
                                  Expanded(
                                    child: Container(
                                      padding: const EdgeInsets.only(left: 16.0),
                                      child: DropdownButton<String>(
                                        value: _esDistribuidor,
                                        isExpanded: true,
                                        onChanged: (val) => setState((){
                                          _esDistribuidor = val!;
                                          _raSocController.text = "";
                                          if(_esDistribuidor == "Si"){
                                            _numCliente = true;
                                          }else{
                                            _numCliente = false;
                                          }
                                        }),
                                        items: ["Si", "No"].map((e) => DropdownMenuItem<String>(
                                          value: e,
                                          child: Text(
                                            e,
                                            style: GoogleFonts.roboto(),
                                          ),
                                        )).toList(),
                                      ),
                                    ),
                                  ),
                                  AnimatedCrossFade(
                                    firstChild: Container(),
                                    secondChild: SizedBox(
                                      width: 164.0,
                                      child: SwitchListTile(
                                        title: Text(
                                          "No. cli.",
                                          style: GoogleFonts.roboto(
                                              color: const Color.fromRGBO(102, 102, 102, 1),
                                              fontWeight: FontWeight.bold,
                                              fontSize: 16.0
                                          ),
                                        ),
                                        value: _numCliente,
                                        activeColor: const Color.fromRGBO(180, 4, 4, 1),
                                        activeTrackColor: const Color.fromRGBO(180, 4, 4, 0.75),
                                        onChanged: (val) => setState(() {
                                          _numCliente = val;
                                          _raSocController.clear();
                                        }),
                                      ),
                                    ),
                                    duration: const Duration(milliseconds: 250),
                                    crossFadeState: _esDistribuidor == 'Si' ? CrossFadeState.showSecond : CrossFadeState.showFirst,
                                  ),
                                ],
                              ),
                              Container(
                                width: parentWidth,
                                margin: const EdgeInsets.only(bottom: 8.0),
                                child: TextField(
                                  controller: _raSocController,
                                  decoration: InputDecoration(
                                    hintText: _numCliente && _esDistribuidor == "Si" ? "Introduzca su número de cliente (Ej. 12345)." : "Introduzca la razón social de su empresa.",
                                    hintStyle: GoogleFonts.roboto(
                                      color: Colors.grey,
                                      fontStyle: FontStyle.italic,
                                    ),
                                    errorText: _errores["raSoc"]! ? "*Campo obligatorio." : null,
                                    errorStyle: GoogleFonts.roboto(
                                      color: const Color(0xFFFF0000),
                                      fontSize: 12.0,
                                    ),
                                  ),
                                  style: GoogleFonts.roboto(),
                                  inputFormatters: [if(_numCliente) DecimalTextInputFormatter()],
                                  onChanged: (value) => setState(() => _errores["raSoc"] = false),
                                ),
                              )
                            ],
                          ),
                        if(!_tieneCuenta)
                          const SizedBox(height: 8.0),
                        if(!_tieneCuenta)
                          Column(
                            children: [
                              Row(
                                children: [
                                  Text(
                                    "Región:",
                                    textAlign: TextAlign.right,
                                    style: GoogleFonts.roboto(
                                      color: const Color.fromRGBO(102, 102, 102, 1),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16.0,
                                    ),
                                  ),
                                  const SizedBox(width: 8.0),
                                  Expanded(
                                    child: DropdownButton<String>(
                                      items: _continentes.keys.toList().map((e) => DropdownMenuItem<String>(
                                        child: Text(
                                          _continentes[e]!,
                                          style: GoogleFonts.roboto(),
                                        ),
                                        value: e,
                                      )).toList(),
                                      value: _continenteAct,
                                      isExpanded: true,
                                      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
                                      onChanged: (val) => setState((){
                                        _pais = "";
                                        _municipio = "";
                                        _estado = "";
                                        _paisCode = "";
                                        _estadoCode = "";
                                        _continenteAct = val!;
                                      }),
                                    ),
                                  )
                                ],
                              ),
                              const SizedBox(height: 8.0),
                              Row(
                                children: [
                                  Text(
                                    "País:",
                                    style: GoogleFonts.roboto(
                                      color: const Color.fromRGBO(102, 102, 102, 1),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16.0,
                                    ),
                                  ),
                                  const SizedBox(width: 8.0),
                                  Expanded(
                                    child: DropdownButton<String>(
                                      value: _pais.isEmpty ? null : _pais,
                                      hint: Text(
                                        "Selecciona una opción",
                                        style: GoogleFonts.roboto(
                                            color: Colors.grey,
                                            fontStyle: FontStyle.italic
                                        ),
                                      ),
                                      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
                                      onChanged: (nuevoPais) => setState((){
                                        _estado = "";
                                        _municipio = "";
                                        _estadoCode = "";
                                        _pais = nuevoPais!;
                                        _paisCode = nuevoPais.split(" ").last.replaceAll("(", "").replaceAll(")", "");

                                        _tieneEstados = _estados[_paisCode] != null;
                                      }),
                                      items: paisesDrop.map((e) => DropdownMenuItem<String>(
                                        child: Text(
                                          e,
                                          style: GoogleFonts.roboto(),
                                        ),
                                        value: e,
                                      )).toList(),
                                      isExpanded: true,

                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 8.0),
                              Row(
                                children: [
                                  Text(
                                  "Estado:",
                                  style: GoogleFonts.roboto(
                                    color: const Color.fromRGBO(102, 102, 102, 1),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16.0,
                                  ),
                                ),
                                  Expanded(
                                    child: Container(
                                      padding: const EdgeInsets.only(left: 16.0),
                                      child: _tieneEstados ? DropdownButton<String>(
                                        value: _estado.isEmpty ? null : _estado,
                                        onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
                                        hint: Text(
                                          "Selecciona una opción",
                                          style: GoogleFonts.roboto(
                                            color: Colors.grey,
                                            fontStyle: FontStyle.italic,
                                          ),
                                        ),
                                        disabledHint: Text(
                                          "Seleccion un país primero",
                                          style: GoogleFonts.roboto(
                                            color: Colors.grey,
                                            fontStyle: FontStyle.italic,
                                          ),
                                        ),
                                        onChanged: _paisCode.isEmpty ? null : (nuevoEstado) => setState((){
                                          _municipio = "";
                                          _ciudadController.clear();
                                          _estado = nuevoEstado!;
                                          _estadoController.text = _estado;
                                          final code = nuevoEstado.split(" ").last.replaceAll("(", "").replaceAll(")", "");
                                          _estadoCode = code;

                                          _tieneCiudades = _municipios[_paisCode]![_estadoCode] != null;
                                        }),
                                        items: _paisCode.isEmpty ? null : _estados[_paisCode]!.map((e) => DropdownMenuItem<String>(
                                          child: Text(
                                            e,
                                            style: GoogleFonts.roboto(),
                                          ),
                                          value: e,
                                        )).toList(),
                                        isExpanded: true,
                                      ) : TextField(
                                        controller: _estadoController,
                                        decoration: InputDecoration(
                                          hintText: "Introduce el nombre de tu provincia",
                                          hintStyle: GoogleFonts.roboto(
                                            color: Colors.grey,
                                            fontStyle: FontStyle.italic,
                                          ),
                                          errorText: _errores["estado"]! ? "*Campo obligatorio." : null,
                                          errorStyle: GoogleFonts.roboto(
                                            color: const Color(0xFFFF0000),
                                            fontSize: 12.0,
                                          ),
                                        ),
                                        style: GoogleFonts.roboto(),
                                        onChanged: (value) => setState(() => _errores["estado"] = false),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 8.0),
                              Row(
                                children: [
                                  Text(
                                    "Ciudad:",
                                    style: GoogleFonts.roboto(
                                      color: const Color.fromRGBO(102, 102, 102, 1),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16.0,
                                    ),
                                  ),
                                  Expanded(
                                    child: Container(
                                      padding: const EdgeInsets.only(left: 16.0),
                                      child: !_tieneEstados || !_tieneCiudades ? TextField(
                                        controller: _ciudadController,
                                        decoration: InputDecoration(
                                          hintText: "Introduce el nombre de tu ciudad",
                                          hintStyle: GoogleFonts.roboto(
                                            color: Colors.grey,
                                            fontStyle: FontStyle.italic,
                                          ),
                                          errorText: _errores["ciudad"]! ? "*Campo obligatorio." : null,
                                          errorStyle: GoogleFonts.roboto(
                                            color: const Color(0xFFFF0000),
                                            fontSize: 12.0,
                                          ),
                                        ),
                                        style: GoogleFonts.roboto(),
                                        onChanged: (value) => setState(() => _errores["ciudad"] = false),
                                      ) : DropdownButton<String>(
                                        value: _municipio.isEmpty ? null : _municipio,
                                        onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
                                        hint: Text(
                                          "Selecciona una opción",
                                          style: GoogleFonts.roboto(
                                            color: Colors.grey,
                                            fontStyle: FontStyle.italic,
                                          ),
                                        ),
                                        disabledHint: _paisCode.isEmpty ? Text(
                                          "Seleccion un país primero",
                                          style: GoogleFonts.roboto(
                                            color: Colors.grey,
                                            fontStyle: FontStyle.italic,
                                          ),
                                        ) : Text(
                                          "Seleccion un estado primero",
                                          style: GoogleFonts.roboto(
                                            color: Colors.grey,
                                            fontStyle: FontStyle.italic,
                                          ),
                                        ),
                                        onChanged: _estadoCode.isEmpty ? null : (nuevoMun) => setState((){
                                          _municipio = nuevoMun!;
                                          _ciudadController.text = _municipio;
                                        }),
                                        items: _estadoCode.isEmpty ? null : _municipios[_paisCode]![_estadoCode]!.map((e) => DropdownMenuItem<String>(
                                          child: Text(
                                            e,
                                            style: GoogleFonts.roboto(),
                                          ),
                                          value: e,
                                        )).toList(),
                                        isExpanded: true,
                                      ),
                                    ),
                                  )
                                ],
                              ),
                              const SizedBox(height: 8.0),
                            ],
                          ),
                        if(!_tieneCuenta)
                          const SizedBox(height: 8.0),
                        if(!_tieneCuenta)
                          Column(
                            children: [
                              SizedBox(
                                width: parentWidth,
                                child: Text(
                                  "Teléfono Móvil:",
                                  style: GoogleFonts.roboto(
                                    color: const Color.fromRGBO(102, 102, 102, 1),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                              Container(
                                margin: const EdgeInsets.only(bottom: 8.0),
                                child: TextField(
                                  controller: _numTelController,
                                  maxLength: _paisCode == "MX" ? 10 : null,
                                  keyboardType: TextInputType.number,
                                  decoration: InputDecoration(
                                    hintText: "7771234567",
                                    hintStyle: GoogleFonts.roboto(
                                      color: Colors.grey,
                                      fontStyle: FontStyle.italic,
                                    ),
                                    errorText: _errores["numTel"]! ? "*Campo obligatorio." : !_numeroValido ? "El número telefónico no tiene un formato válido." : null,
                                    errorStyle: GoogleFonts.roboto(
                                      fontSize: 12.0,
                                    ),
                                  ),
                                  style: GoogleFonts.roboto(),
                                  onChanged: (value) => setState((){
                                    _errores["numTel"] = false;

                                    const pattern = r'(^(?:[+0]9)?[0-9]{10,12}$)';
                                    final regExp = RegExp(pattern);

                                    _numeroValido = _paisCode == "MX" ? regExp.hasMatch(value) : true;
                                  }),
                                ),
                              ),
                            ],
                          ),
                        if(!_tieneCuenta)
                          const SizedBox(height: 8.0),
                        Column(
                          children: [
                            SizedBox(
                              width: parentWidth,
                              child: Text(
                                "Correo electrónico:",
                                style: GoogleFonts.roboto(
                                  color: const Color.fromRGBO(102, 102, 102, 1),
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16.0,
                                ),
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.only(bottom: 8.0),
                              child: TextField(
                                controller: _correoController,
                                keyboardType: TextInputType.emailAddress,
                                decoration: InputDecoration(
                                  hintText: "ejemplo@ejemplo.com",
                                  hintStyle: GoogleFonts.roboto(
                                    color: Colors.grey,
                                    fontStyle: FontStyle.italic,
                                  ),
                                  errorText: _errores["correo"]! ? "*Campo obligatorio." : !_correoValido ? "El correo tiene un formato inválido." : null,
                                  errorStyle: GoogleFonts.roboto(
                                    fontSize: 12.0,
                                  ),
                                ),
                                style: GoogleFonts.roboto(),
                                onChanged: (value) => setState((){
                                  _errores["correo"] = false;

                                  const pattern = r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$';
                                  final regExp = RegExp(pattern);

                                  _correoValido = regExp.hasMatch(value);
                                }),
                              ),
                            )
                          ],
                        ),
                        const SizedBox(height: 8.0),
                        Column(
                          children: [
                            SizedBox(
                              width: parentWidth,
                              child: Text(
                                "Contraseña:",
                                style: GoogleFonts.roboto(
                                  color: const Color.fromRGBO(102, 102, 102, 1),
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16.0,
                                ),
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.only(bottom: 8.0),
                              child: TextField(
                                controller: _contraController,
                                obscureText: _obscurePass,
                                decoration: InputDecoration(
                                  hintText: "Ingrese una contraseña nueva (min. 8 caracteres)",
                                  hintStyle: GoogleFonts.roboto(
                                    color: Colors.grey,
                                    fontStyle: FontStyle.italic,
                                  ),
                                  errorText: _errores["contra"]! ? "*Campo obligatorio." : !_contraValida ? "La contraseña debe tener más de 8 caracteres." : null,
                                  errorStyle: GoogleFonts.roboto(
                                    fontSize: 12.0,
                                  ),
                                  suffixIcon: IconButton(
                                    icon: Icon(_obscurePass ? Icons.visibility : Icons.visibility_off),
                                    onPressed: () => setState(() => _obscurePass = !_obscurePass),
                                  ),
                                ),
                                style: GoogleFonts.roboto(),
                                enableInteractiveSelection: false,
                                onChanged: (value) => setState((){
                                  _errores["contra"] = false;

                                  _contraValida = value.length >= 8;
                                }),
                              ),
                            )
                          ],
                        ),
                        const SizedBox(height: 8.0),
                        if(!_tieneCuenta)
                          Column(
                            children: [
                              SizedBox(
                                width: parentWidth,
                                child: Text(
                                  "Confirmar contraseña:",
                                  style: GoogleFonts.roboto(
                                    color: const Color.fromRGBO(102, 102, 102, 1),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                              Container(
                                margin: const EdgeInsets.only(bottom: 8.0),
                                child: TextField(
                                  controller: _confContraController,
                                  obscureText: _obscureConfirmPass,
                                  keyboardType: TextInputType.emailAddress,
                                  decoration: InputDecoration(
                                    hintText: "Confirme su contraseña",
                                    hintStyle: GoogleFonts.roboto(
                                      color: Colors.grey,
                                      fontStyle: FontStyle.italic,
                                    ),
                                    errorText: _errores["confContra"]! ? "*Campo obligatorio." : !_contrasIguales ? "Las contraseñas no coinciden." : null,
                                    errorStyle: GoogleFonts.roboto(
                                      fontSize: 12.0,
                                    ),
                                    suffixIcon: IconButton(
                                      icon: Icon(_obscureConfirmPass ? Icons.visibility : Icons.visibility_off),
                                      onPressed: () => setState(() => _obscureConfirmPass = !_obscureConfirmPass),
                                    )
                                  ),
                                  style: GoogleFonts.roboto(),
                                  enableInteractiveSelection: false,
                                  onChanged: (value) => setState((){
                                    _errores["confContra"] = false;
                                    _contrasIguales = true;
                                  }),
                                ),
                              ),
                            ],
                          ),
                      ],
                    ),
                  ),
                  const SizedBox(
                    height: 32.0,
                  ),
                  Container(
                    width: double.infinity,
                    margin: const EdgeInsets.symmetric(horizontal: 32.0),
                    child: Column(
                      children: [
                        MaterialButton(
                            elevation: 4.0,
                            padding: const EdgeInsets.symmetric(vertical: 8.0),
                            minWidth: parentWidth-32,
                            color: const Color(0xFFFF0000),
                            child: _tieneCuenta ? Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset(
                                  "assets/iniciar-sesion.png",
                                  width: 32.0,
                                ),
                                const SizedBox(width: 8.0),
                                const Text(
                                  "Iniciar sesión",
                                  style: TextStyle(
                                    fontFamily: "Helvetica Neue Black Cond",
                                    fontSize: 28.0,
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ) : Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset(
                                  "assets/registrarse.png",
                                  width: 32.0,
                                ),
                                const SizedBox(width: 8.0),
                                Text(
                                  _esperando ? "Registrando..." : "Registrarse",
                                  style: const TextStyle(
                                    fontFamily: "Helvetica Neue Black Cond",
                                    fontSize: 28.0,
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ),
                            disabledColor: Colors.grey,
                            onPressed: _esperando ? null : !_tieneCuenta ? () async {
                              FocusScope.of(context).requestFocus(FocusNode());
                              _errores["nombre"] = _nombreController.text.isEmpty;
                              _errores["ciudad"] = _ciudadController.text.isEmpty;
                              _errores["estado"] = _estadoController.text.isEmpty;
                              _errores["numTel"] = _numTelController.text.isEmpty;
                              _errores["correo"] = _correoController.text.isEmpty;
                              _errores["contra"] = _contraController.text.isEmpty;
                              _errores["confContra"] = _confContraController.text.isEmpty;
                              _errores["raSoc"] = _raSocController.text.isEmpty;

                              bool hasError = false;
                              bool paisEstadoEmpty = false;

                              _errores.forEach((key, value) {
                                hasError = value;
                              });

                              if(!_tieneEstados){
                                _estado = _estadoController.text;
                              }

                              if(!_tieneCiudades){
                                _municipio = _ciudadController.text;
                              }

                              if(hasError){
                                setState(() {});
                                return;
                              }

                              if(_pais.isEmpty){
                                Fluttertoast.showToast(
                                  msg: "Antes de avanzar debes seleccionar un país.",
                                  toastLength: Toast.LENGTH_SHORT,
                                  timeInSecForIosWeb: 4,
                                  gravity: ToastGravity.CENTER,
                                  webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                );
                                paisEstadoEmpty = true;
                              }

                              if(_estado.isEmpty){
                                Fluttertoast.showToast(
                                  msg: "Antes de avanzar debes seleccionar un estado.",
                                  toastLength: Toast.LENGTH_SHORT,
                                  timeInSecForIosWeb: 4,
                                  gravity: ToastGravity.CENTER,
                                  webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                );
                                paisEstadoEmpty = true;
                              }

                              if(_municipio.isEmpty){
                                Fluttertoast.showToast(
                                  msg: "Antes de avanzar debes seleccionar un municipio.",
                                  toastLength: Toast.LENGTH_SHORT,
                                  timeInSecForIosWeb: 4,
                                  gravity: ToastGravity.CENTER,
                                  webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                );
                                paisEstadoEmpty = true;
                              }

                              if(paisEstadoEmpty){
                                setState(() {});
                                return;
                              }

                              final contra = _contraController.text;
                              final contraComp = _confContraController.text;

                              _confContraController.clear();

                              _contrasIguales = contra == contraComp;

                              if(!_contrasIguales){
                                Fluttertoast.showToast(
                                  msg: "Las contraseñas no coinciden.",
                                  toastLength: Toast.LENGTH_SHORT,
                                  timeInSecForIosWeb: 4,
                                  gravity: ToastGravity.CENTER,
                                  webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                );
                                setState(() {});
                                return;
                              }

                              _esperando = true;
                              setState(() {});

                              final paisArr = _pais.split(" - ");
                              final paisStr = paisArr.last;
                              final dist = _esDistribuidor.substring(0, 1);

                              final registrado = await registrarInfo(
                                nombre: _nombreController.text,
                                pais: paisStr,
                                estado: _estado,
                                ciudad: _municipio,
                                movil: _numTelController.text,
                                correo: _correoController.text,
                                contra: contra,
                                apepat: _apepatController.text,
                                contConf: contraComp,
                                apemat: _apematController.text,
                                distribuidor: dist,
                                razonSoc: _esDistribuidor == 'Si' && _numCliente? null : _raSocController.text,
                                numCli: _esDistribuidor == 'Si' && _numCliente ? _raSocController.text : null,
                              );

                              _esperando = false;
                              setState(() {});
                              if(registrado){
                                final id = db.collection('login').doc().id;
                                db.collection('login').doc(id).set({
                                  'nombre': _nombreController.text,
                                  'pais': _pais,
                                  'estado': _estado,
                                  'municipio': _municipio,
                                  'movil': _numTelController.text,
                                  'correo': _correoController.text,
                                  'idUsuario': _idUsuario,
                                  'verificacion': '1',
                                  'token': _accessToken
                                });

                                final paisArr = _pais.split('-');
                                final paisStr = paisArr.last.trim();

                                Navigator.push(context, MaterialPageRoute(
                                  builder: (context) => VerificacionPage(
                                    correo: _correoController.text,
                                    numTel: _numTelController.text,
                                    pais: paisStr,
                                    verificacion: "1",
                                    idUsuario: _idUsuario,
                                  ),
                                ));
                              }else{
                                Fluttertoast.showToast(
                                  msg: "Hubo un error al registrar su información. Por favor contacte al departamento de TI de S&P México.",
                                  toastLength: Toast.LENGTH_SHORT,
                                  timeInSecForIosWeb: 4,
                                  gravity: ToastGravity.CENTER,
                                  webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                );
                              }
                            } : () async{
                              bool emailValid = RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(_correoController.text);
                              if(_correoController.text.isEmpty){
                                Fluttertoast.showToast(
                                  msg: "Por favor ingrese un correo electrónico",
                                  toastLength: Toast.LENGTH_SHORT,
                                  timeInSecForIosWeb: 4,
                                  gravity: ToastGravity.CENTER,
                                  webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                );
                              }else if(_contraController.text.isEmpty){
                                Fluttertoast.showToast(
                                  msg: "Por favor ingrese su contraseña",
                                  toastLength: Toast.LENGTH_SHORT,
                                  timeInSecForIosWeb: 4,
                                  gravity: ToastGravity.CENTER,
                                  webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                );
                              }else if(!emailValid){
                                Fluttertoast.showToast(
                                  msg: "El correo ingresado no tiene un formato válido",
                                  toastLength: Toast.LENGTH_SHORT,
                                  timeInSecForIosWeb: 4,
                                  gravity: ToastGravity.CENTER,
                                  webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                );
                              }else if(_contraController.text.length < 8){
                                Fluttertoast.showToast(
                                  msg: "La contraseña debe tener al menos 8 caracteres",
                                  toastLength: Toast.LENGTH_SHORT,
                                  timeInSecForIosWeb: 4,
                                  gravity: ToastGravity.CENTER,
                                  webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                );
                              }else{
                                setState(() => _esperando = true);
                                final loginModel = await _loginProvider.fetchLogin(_correoController.text, _contraController.text);
                                if(!loginModel.response){
                                  Fluttertoast.showToast(
                                    msg: loginModel.message,
                                    toastLength: Toast.LENGTH_SHORT,
                                    timeInSecForIosWeb: 4,
                                    gravity: ToastGravity.CENTER,
                                    webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                  );
                                  setState(() => _esperando = false);
                                }else{
                                  final correo = _correoController.text;

                                  _correoController.clear();
                                  _contraController.clear();
                                  setState(() => _esperando = false);

                                  final id = db.collection('login').doc().id;
                                  db.collection('login').doc(id).set({
                                    'nombre': loginModel.result.nombre,
                                    'pais': loginModel.result.pais,
                                    'estado': loginModel.result.estado,
                                    'municipio': loginModel.result.ciudad,
                                    'movil': loginModel.result.movil,
                                    'correo': correo,
                                    'idUsuario': loginModel.result.idUsuario,
                                    'verificacion': loginModel.result.verificacion,
                                    'token': loginModel.result.accessToken
                                  });

                                  if(loginModel.result.verificacion == "1" || loginModel.result.verificacion == "2" || loginModel.result.verificacion == "3"){
                                    Navigator.push(context, MaterialPageRoute(
                                      builder: (context) => VerificacionPage(
                                        correo: correo,
                                        numTel: loginModel.result.movil,
                                        pais: loginModel.result.pais,
                                        verificacion: loginModel.result.verificacion,
                                        idUsuario: loginModel.result.idUsuario,
                                      ),
                                    ));
                                  }else{
                                    final action = await Navigator.pushNamed(context, "indexMC");
                                    if(action == "logout"){
                                      final items = await db.collection('login').get();
                                      items!.forEach((key, value) {
                                        db.collection('login').doc(key).delete();
                                      });
                                    }
                                  }
                                }
                              }
                            }
                        ),
                        const SizedBox(height: 16.0),
                        MaterialButton(
                          elevation: 4.0,
                          padding: const EdgeInsets.symmetric(vertical: 8.0),
                          minWidth: parentWidth-32,
                          color: const Color(0xFFFF0000),
                          child: _tieneCuenta ? Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                "assets/quiero-una-cuenta.png",
                                width: 32.0,
                              ),
                              const SizedBox(width: 8.0),
                              const Text(
                                "¡Quiero una cuenta!",
                                style: TextStyle(
                                  fontFamily: "Helvetica Neue Black Cond",
                                  fontSize: 28.0,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ) : Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                "assets/ya-tengo-una-cuenta.png",
                                width: 32.0,
                              ),
                              const SizedBox(width: 8.0),
                              const Text(
                                "Ya tengo una cuenta",
                                style: TextStyle(
                                  fontFamily: "Helvetica Neue Black Cond",
                                  fontSize: 28.0,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                          onPressed: () => setState(() {
                            _tieneCuenta = !_tieneCuenta;

                            _nombreController.clear();
                            _paisCode = "";
                            _estadoCode = "";
                            _pais = "";
                            _estado = "";
                            _municipio = "";
                            _numTelController.clear();
                            _confContraController.clear();

                            FocusScope.of(context).requestFocus(FocusNode());
                          }),
                        ),
                        const SizedBox(height: 16.0),
                        MaterialButton(
                          elevation: 4.0,
                          padding: const EdgeInsets.symmetric(vertical: 8.0),
                          minWidth: parentWidth-32,
                          color: const Color.fromRGBO(255, 0, 0, 1),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: const [
                              Icon(
                                Icons.keyboard_return,
                                color: Colors.white,
                                size: 32.0,
                              ),
                              SizedBox(width: 8.0),
                              Text(
                                'Regresar',
                                style: TextStyle(
                                  fontFamily: 'Helvetica Neue Black Cond',
                                  fontSize: 28.0,
                                  color: Colors.white,
                                ),
                              )
                            ],
                          ),
                          onPressed: () => Navigator.pop(context),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(
                    height: 32.0,
                  ),
                ],
              ),
            ),
          );
        }),
      ),
    );
  }
}
