import 'dart:io';
import 'dart:convert';

import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:plataforma_educativa/src/bloc/provider.dart';
import 'package:plataforma_educativa/src/models/local_user_model.dart';
import 'package:plataforma_educativa/src/models/scan_model.dart';
import 'package:plataforma_educativa/src/pages/session_page.dart';
import 'package:plataforma_educativa/src/providers/db_provider.dart';
import 'package:plataforma_educativa/src/providers/login_provider.dart';
import 'package:plataforma_educativa/src/providers/logout_provider.dart';
import 'package:dart_ipify/dart_ipify.dart';
import 'package:plataforma_educativa/src/widgets/line_path_class.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:flutter_sodium/flutter_sodium.dart';

import 'home_page.dart';
import 'menu_page.dart';

class LoginPage extends StatefulWidget {
  final String fcmToken;
  final bool rememberSession;

  const LoginPage({
    Key? key,
    required this.fcmToken,
    required this.rememberSession
  }) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>();
  final _loginProvider = LoginProvider();
  final _logoutProvider = LogoutProvider();
  bool _isLoading = true;
  bool _scanning = false;
  TextEditingController _inputUserController = TextEditingController();
  TextEditingController _inputPwdController = TextEditingController();
  LocalUserModel? _userModel;
  ScanModel? _scanModel;
  late bool _rememberSession;
  late String _so;
  late String _version;
  late String _ip;
  late String _model;

  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  Barcode? result;
  QRViewController? controller;
  bool _flash = false;
  String _futureString = "";

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

    _rememberSession = widget.rememberSession;

    _so = Platform.isAndroid ? "Android" : Platform.isIOS ? "IOS" : "Unknown";

    DBProvider.db.getAllUsers().then((users){
      DBProvider.db.getAllScans().then((scans){
        if(users.isNotEmpty){

        }

        if(scans.isNotEmpty){
          _scanModel = scans.first;
          _inputUserController.text = _scanModel!.idUsuario;
        }
        _init();
      });
    });
  }

  void _init() async{
    final ipv4 = await Ipify.ipv4();
    _ip = ipv4;
    Sodium.init();

    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    if(Platform.isAndroid){
      AndroidDeviceInfo androidDeviceInfo = await deviceInfoPlugin.androidInfo;
      _version = androidDeviceInfo.version.release;
      _model = androidDeviceInfo.model;
    }else if(Platform.isIOS){
      IosDeviceInfo iosDeviceInfo = await deviceInfoPlugin.iosInfo;
      _version = iosDeviceInfo.systemVersion;
      _model = iosDeviceInfo.utsname.machine;
    }else{
      _version = "Unknown";
      _model = "Unknown";
    }

    setState(() => _isLoading = false);
  }

  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller!.pauseCamera();
    } else if (Platform.isIOS) {
      controller!.resumeCamera();
    }
  }

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    final _bloc = Provider.of(context);
    return Scaffold(
      key: _scaffoldkey,
      body: Container(
        height: _screenSize.height,
        width: _screenSize.width,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: _isLoading ? Center(
            child: Image.asset(
              "assets/loading.gif",
              width: 64.0,
            ),
          ) : Stack(
            children: [
              Container(
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const SizedBox(
                        height: 16.0,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Image.asset(
                            "assets/logo.png",
                            width: _scanModel == null ? 256.0 : (_screenSize.width / 2) - 32.0,
                          ),
                          if(_scanModel != null)
                            const SizedBox(
                              width: 32.0,
                            ),
                          if(_scanModel != null)
                            FadeInImage(
                              image: NetworkImage(
                                _scanModel!.logoEscuela,
                              ),
                              placeholder: const AssetImage("assets/loading.gif"),
                              fadeInDuration: const Duration(
                                  milliseconds: 200
                              ),
                              width: (_screenSize.width / 2) - 32.0,
                            )
                        ],
                      ),
                      const SizedBox(
                        height: 16.0,
                      ),
                      Image.asset(
                        "assets/persona.png",
                        fit: BoxFit.cover,
                        width: _screenSize.width - 64.0,
                      ),
                      const SizedBox(
                        height: 32.0,
                      ),
                      Container(
                        width: _screenSize.width - 64.0,
                        child: Text(
                          "Plataforma Educativa Móvil",
                          textAlign: TextAlign.center,
                          style: GoogleFonts.montserrat(
                            color: const Color.fromRGBO(22, 23, 112, 1),
                            fontSize: 20.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 32.0,
                          vertical: 16.0,
                        ),
                        child: _scanModel == null ? Column(
                          children: [
                            Text(
                              "Para comenzar, accede a la Plataforma Educativa y en la parte superior selecciona la opción \"Mostrar QR\".",
                              textAlign: TextAlign.center,
                              style: GoogleFonts.montserrat(
                                color: Colors.black54,
                                fontSize: 16.0,
                                fontWeight: FontWeight.w300,
                              ),
                            ),
                            const SizedBox(
                              height: 32.0,
                            ),
                            FloatingActionButton(
                              child: const Icon(Icons.qr_code_scanner),
                              onPressed: _scanQR,
                              backgroundColor: Colors.deepPurpleAccent,
                            ),
                            const SizedBox(
                              height: 16.0,
                            ),
                            Text(
                              "Escanear código QR",
                              textAlign: TextAlign.center,
                              style: GoogleFonts.montserrat(
                                color: Colors.deepPurpleAccent,
                                fontSize: 16.0,
                              ),
                            )
                          ],
                        ) : Column(
                          children: [
                            Text(
                              "Inicie sesión con el usuario y contraseña que les proporcionamos",
                              textAlign: TextAlign.center,
                              style: GoogleFonts.montserrat(
                                color: Colors.black54,
                                fontSize: 16.0,
                                fontWeight: FontWeight.normal,
                              ),
                            ),
                            const SizedBox(height: 16.0),
                            TextField(
                              controller: _inputUserController,
                              readOnly: true,
                              textCapitalization: TextCapitalization.sentences,
                              decoration: InputDecoration(
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(8.0),
                                ),
                                hintText: "Ingresa tu usuario",
                                labelText: 'Usuario',
                                suffixIcon: const Icon(Icons.account_circle)
                              ),
                            ),
                            const SizedBox(height: 16.0),
                            StreamBuilder(
                              stream: _bloc.passwordStream,
                              builder: (context, snapshot) => TextField(
                                obscureText: true,
                                controller: _inputPwdController,
                                decoration: InputDecoration(
                                  border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(8.0),
                                  ),
                                  hintText: "Escribe tu contraseña...",
                                  labelText: "Contraseña",
                                  errorText: snapshot.error == null ? null : snapshot.error.toString(),
                                  suffixIcon: const Icon(Icons.lock)
                                ),
                                onChanged: _bloc.changePassword,
                              ),
                            ),
                            const SizedBox(height: 16.0),
                            Container(
                              width: _screenSize.width,
                              child: Row(
                                children: [
                                  ClipRRect(
                                    borderRadius: BorderRadius.circular(64.0),
                                    child: Container(
                                      decoration: const BoxDecoration(
                                        gradient: LinearGradient(
                                          begin: Alignment.centerLeft,
                                          end: Alignment.centerRight,
                                          colors: [Color.fromRGBO(246, 137, 121, 1), Colors.redAccent]
                                        ),
                                      ),
                                      child: TextButton(
                                        style: TextButton.styleFrom(
                                          padding: const EdgeInsets.symmetric(
                                            horizontal: 16.0,
                                            vertical: 15.0,
                                          ),
                                          minimumSize: const Size(0.0, 0.0),
                                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                        ),
                                        child: Image.asset(
                                          "assets/Restaurar0.png",
                                          width: 16.0,
                                        ),
                                        onPressed: () => showDialog(
                                          context: context,
                                          barrierDismissible: true,
                                          builder: (context) => AlertDialog(
                                            shape: RoundedRectangleBorder(
                                              borderRadius: BorderRadius.circular(8.0),
                                            ),
                                            titlePadding: EdgeInsets.zero,
                                            title: ClipRRect(
                                              borderRadius: BorderRadius.circular(5.0),
                                              child: Container(
                                                width: double.infinity,
                                                height: 151.0,
                                                child: Stack(
                                                  children: <Widget>[
                                                    Container(
                                                      width: double.infinity,
                                                      height: 124.0,
                                                      decoration: BoxDecoration(
                                                          color: Color.fromRGBO(255, 177, 0, 1),
                                                          borderRadius: BorderRadius.circular(5.0)
                                                      ),
                                                    ),
                                                    ClipPath(
                                                      clipper: LinePathClass(
                                                          height: 120.0,
                                                          width: _screenSize.width*0.78,
                                                          orientation: 'TL'
                                                      ),
                                                      child: Container(
                                                        color: Color.fromRGBO(255, 198, 0, 1),
                                                        width: double.infinity,
                                                        height: 120.0,
                                                      ),
                                                    ),
                                                    Positioned(
                                                      child: Image(
                                                        image: AssetImage('assets/precaucion.png'),
                                                        width: 64.0,
                                                      ),
                                                      top: 8.0,
                                                      right: ((_screenSize.width*0.75)/2)-32.0,
                                                    ),
                                                    Container(
                                                      height: 120.0,
                                                      width: double.infinity,
                                                      padding: EdgeInsets.only(
                                                          top: 70.0
                                                      ),
                                                      child: Text(
                                                        '¿Estás seguro?',
                                                        textAlign: TextAlign.center,
                                                        style: GoogleFonts.montserrat(
                                                            color: Colors.white,
                                                            fontWeight: FontWeight.bold,
                                                            fontSize: 32.0
                                                        ),
                                                      ),
                                                    ),
                                                    Positioned(
                                                      child: ClipPath(
                                                        clipper: LinePathClass(
                                                            height: 28.0,
                                                            width: 28,
                                                            orientation: 'C'
                                                        ),
                                                        child: Container(
                                                          height: 28.0,
                                                          width: 28.0,
                                                          color: Color.fromRGBO(255, 177, 0, 1),
                                                        ),
                                                      ),
                                                      bottom: 0.0,
                                                      left: ((_screenSize.width*0.75)/2)-14.0,
                                                    )
                                                  ],
                                                ),
                                              ),
                                            ),
                                            content: Column(
                                              mainAxisSize: MainAxisSize.min,
                                              children: <Widget>[
                                                Container(
                                                  width: double.infinity,
                                                  margin: EdgeInsets.only(left: 4.0, right: 4.0, bottom: 8.0),
                                                  child: Text(
                                                    'Restaurar la aplicación hará que pierdas los datos de tu institución educativa, \n¿deseas continuar?',
                                                    textAlign: TextAlign.center,
                                                    style: GoogleFonts.montserrat(
                                                        fontWeight: FontWeight.w300,
                                                        color: Colors.black54
                                                    ),
                                                  ),
                                                )
                                              ],
                                            ),
                                            contentPadding: EdgeInsets.zero,
                                            actions: <Widget>[
                                              Container(
                                                width: _screenSize.width,
                                                child: Row(
                                                  mainAxisAlignment: MainAxisAlignment.center,
                                                  crossAxisAlignment: CrossAxisAlignment.center,
                                                  mainAxisSize: MainAxisSize.max,
                                                  children: [
                                                    Expanded(
                                                      child: Container(),
                                                      flex: 1,
                                                    ),
                                                    ElevatedButton(
                                                      style: ElevatedButton.styleFrom(
                                                          minimumSize: const Size(0.0, 0.0),
                                                          padding: EdgeInsets.zero,
                                                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                                          shape: RoundedRectangleBorder(
                                                            borderRadius: BorderRadius.circular(5.0),
                                                          ),
                                                          primary: const Color.fromRGBO(100, 100, 100, 1)
                                                      ),
                                                      child: Container(
                                                        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                                                        decoration: BoxDecoration(
                                                          border: Border.all(
                                                              color: const Color.fromRGBO(25, 25, 25, 1),
                                                              width: 4.0
                                                          ),
                                                          borderRadius: BorderRadius.circular(5.0),
                                                        ),
                                                        child: Text(
                                                          'Cancelar',
                                                          textAlign: TextAlign.center,
                                                          style: GoogleFonts.montserrat(
                                                              color: Colors.white
                                                          ),
                                                        ),
                                                      ),
                                                      onPressed: (){
                                                        Navigator.of(context).pop();
                                                      },
                                                    ),
                                                    Expanded(
                                                      child: Container(),
                                                      flex: 2,
                                                    ),
                                                    ElevatedButton(
                                                      style: ElevatedButton.styleFrom(
                                                          minimumSize: const Size(0.0, 0.0),
                                                          padding: EdgeInsets.zero,
                                                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                                          shape: RoundedRectangleBorder(
                                                            borderRadius: BorderRadius.circular(5.0),
                                                          ),
                                                          primary: const Color.fromRGBO(100, 100, 100, 1)
                                                      ),
                                                      child: Container(
                                                        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                                                        decoration: BoxDecoration(
                                                            border: Border.all(
                                                                color: const Color.fromRGBO(25, 25, 25, 1),
                                                                width: 4.0
                                                            ),
                                                            borderRadius: BorderRadius.circular(5.0)
                                                        ),
                                                        child: Text(
                                                          'Aceptar',
                                                          textAlign: TextAlign.center,
                                                          style: GoogleFonts.montserrat(
                                                              color: Colors.white
                                                          ),
                                                        ),
                                                      ),
                                                      onPressed: () async{
                                                        await DBProvider.db.deleteAllUsers();
                                                        await DBProvider.db.deleteAll();
                                                        Navigator.pushReplacement(context, MaterialPageRoute(
                                                            builder: (context) => LoginPage(
                                                              fcmToken: widget.fcmToken,
                                                              rememberSession: widget.rememberSession,
                                                            )
                                                        ));
                                                      },
                                                    ),
                                                    Expanded(
                                                      child: Container(),
                                                      flex: 1,
                                                    ),
                                                  ],
                                                ),
                                              )
                                            ],
                                            actionsPadding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 8.0),
                                          )
                                        ),
                                      ),
                                    ),
                                  ),
                                  const SizedBox(width: 16.0),
                                  Expanded(
                                    child: StreamBuilder(
                                      stream: _bloc.formValidStream,
                                      builder: (context, snapshot) => ClipRRect(
                                        borderRadius: BorderRadius.circular(64.0),
                                        child: Container(
                                          decoration: BoxDecoration(
                                            gradient: LinearGradient(
                                              begin: Alignment.centerLeft,
                                              end: Alignment.centerRight,
                                              colors: [snapshot.hasData ? const Color.fromRGBO(56, 109, 160, 1) : Colors.grey,
                                                snapshot.hasData ? const Color.fromRGBO(22, 23, 112, 1) : Colors.grey],
                                            ),
                                          ),
                                          width: double.infinity,
                                          child: TextButton(
                                            style: TextButton.styleFrom(
                                              padding: const EdgeInsets.symmetric(
                                                horizontal: 16.0,
                                                vertical: 15.0,
                                              ),
                                              minimumSize: const Size(0.0, 0.0),
                                              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                            ),
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.center,
                                              children: <Widget>[
                                                const Image(
                                                  image: AssetImage('assets/Entrar0.png'),
                                                  width: 16.0,
                                                ),
                                                const SizedBox(width: 8.0),
                                                Text('Acceder', style: GoogleFonts.montserrat(color: Colors.white, fontWeight: FontWeight.bold), textAlign: TextAlign.center)
                                              ],
                                            ),
                                            onPressed: snapshot.hasData ? () => _login(_bloc, context) : null,
                                          ),
                                        ),
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ),
                            const SizedBox(height: 16.0),
                            CheckboxListTile(
                              title: Text(
                                "Recordar esta sesión 30 días",
                                style: GoogleFonts.montserrat(
                                  fontSize: 14.0,
                                  color: Colors.black54,
                                ),
                              ),
                              onChanged: (value) => setState(() => _rememberSession = value!),
                              value: _rememberSession,
                              checkColor: Colors.white,
                              activeColor: const Color.fromRGBO(56, 109, 160, 1),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ),
              if(_scanning)
                AlertDialog(
                  title: Text(
                    "Escanear QR",
                    style: GoogleFonts.montserrat(),
                  ),
                  content: Column(
                    children: [
                      Expanded(
                        child: QRView(
                          key: qrKey,
                          onQRViewCreated: _onQRViewCreated,
                          overlay: QrScannerOverlayShape(
                              borderColor: Colors.deepPurpleAccent,
                              borderRadius: 8.0,
                              borderLength: 32.0,
                              borderWidth: 8.0,
                              cutOutSize: MediaQuery.of(context).size.width < 400 ? 150.0 : 250.0
                          ),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 16.0,
                          vertical: 16.0,
                        ),
                        width: MediaQuery.of(context).size.width,
                        child: Column(
                          children: [
                            ElevatedButton(
                              child: SizedBox(
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text(
                                      _flash ? "Apagar flash" : "Encender flash",
                                      style: GoogleFonts.montserrat(
                                        color: Colors.deepPurpleAccent,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 14.0,
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 4.0,
                                    ),
                                    Icon(
                                      _flash ? Icons.flash_off : Icons.flash_on,
                                      color: Colors.deepPurpleAccent,
                                    )
                                  ],
                                ),
                              ),
                              onPressed: () async{
                                await controller!.toggleFlash();
                                setState(() => _flash = !_flash);
                              },
                              style: ElevatedButton.styleFrom(
                                primary: Colors.white54,
                              ),
                            ),
                            const SizedBox(
                              width: 16.0,
                            ),
                            ElevatedButton(
                              child: SizedBox(
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text(
                                      "Cambiar cámara",
                                      style: GoogleFonts.montserrat(
                                        color: Colors.deepPurpleAccent,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 14.0,
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 4.0,
                                    ),
                                    const Icon(
                                      Icons.switch_camera,
                                      color: Colors.deepPurpleAccent,
                                    )
                                  ],
                                ),
                              ),
                              onPressed: () async => await controller!.flipCamera(),
                              style: ElevatedButton.styleFrom(
                                primary: Colors.white54,
                              ),
                            ),
                            const SizedBox(
                              width: 16.0,
                            ),
                            ElevatedButton(
                              child: SizedBox(
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text(
                                      "Cancelar",
                                      style: GoogleFonts.montserrat(
                                        color: Colors.deepPurpleAccent,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 14.0,
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 4.0,
                                    ),
                                    const Icon(
                                      Icons.cancel,
                                      color: Colors.deepPurpleAccent,
                                    )
                                  ],
                                ),
                              ),
                              onPressed: () => setState(() => _scanning = false),
                              style: ElevatedButton.styleFrom(
                                primary: Colors.white54,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                )
            ],
          ),
        ),
      ),
    );
  }

  _scanQR(){
    // String futureString = 'er4AH1g3HXoegajP4BJR7TggZG1TrHfK1m4prRT1GInKPer4qwT1DHnmaTbtVyiIoHf0cfg9hX9g6PnZ/p4Qj8I+DbU=';
    // /public_html/services/QA/images
    // /idEscuela.png
    setState(() => _scanning = true);
  }

  _login(LoginBloc bloc, BuildContext context) async{
    FocusScope.of(context).requestFocus(FocusNode());
    final loginDate = todayDate();
    final escuelas = await DBProvider.db.getAllScans();
    final escuela = escuelas.first;
    
    await DBProvider.db.deleteAllUsers();
    
    final userKeys = CryptoBox.randomKeys();
    final login = await _loginProvider.fetchLogin(escuela.idUsuario, bloc.password, widget.fcmToken, base64.encode(userKeys.sk), base64.encode(userKeys.pk),
        _ip, _so, _version, _rememberSession ? "Si" : "No", loginDate, _model);

    if(login.error){
      Fluttertoast.showToast(
        msg: "Error: ${login.message}"
      );

      _inputPwdController.clear();
      return null;
    }else{
      List<String> gradoNivel;
      if(login.result.grado == "NA"){
        gradoNivel = [login.result.grado, ""];
      }else{
        gradoNivel = login.result.grado.split("");
      }

      final setUser = LocalUserModel(
        idUsuario: login.result.idUsuario,
        primerNombre: login.result.primerNombre,
        segundoNombre: login.result.segundoNombre,
        tipoUsuario: login.result.tipoUsuario,
        apellidoPaterno: login.result.apellidoPaterno,
        apellidoMaterno: login.result.apellidoMaterno,
        active: _rememberSession,
        until: loginDate,
        secretKey: login.result.secretKey,
        publicKey: login.result.publicKey,
        grado: gradoNivel[0],
        nivel: gradoNivel[1] == 'P' ? 'Primaria'
            : gradoNivel[1] == 'S' ? 'Secundaria'
            : gradoNivel[1] == 'K' ? 'Preescolar'
            : gradoNivel[1] == 'M' ? 'Maternal'
            : '',
        token: login.result.token,
      );
      await DBProvider.db.newUserRaw(setUser);

      if(login.result.tipoUsuario != "PF"){
        Navigator.pushReplacement(context, MaterialPageRoute(
          builder: (context) => MenuPage(
            esPadre: false,
            revisaHijo: false,
            fcmToken: widget.fcmToken,
          ),
        ));
      }else{
        Navigator.pushReplacement(context, MaterialPageRoute(
          builder: (context) => HomePage(
            fcmToken: widget.fcmToken,
          ),
        ));
      }
    }
  }

  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) async{
      setState(() {
        _scanning = false;
        _futureString = scanData.code!;
      });

      if(_futureString.isEmpty){
        Fluttertoast.showToast(
          msg: "No se encontró información.",
        );
      }else{
        String cadenaDesencriptada = "";
        bool error = false;

        try{
          cadenaDesencriptada = CryptoBox.decryptString(
            base64.decode(_futureString),
            base64.decode('rOOHqbrNxRamYCqqkwyxeYUcb7M+32NY'),
            base64.decode('xGGg6eMXd/ugXqFJfB5wQ9k5Yq/VQRaQeFh4zXmMHSo='),
            base64.decode('7tPoKAbUleTq2C/eiQ03oQ5zynj5eWQAR5h+BM0NDeY='),
          );
        }catch(e){
          error = true;
        }

        if(error){
          Fluttertoast.showToast(
            msg: "El formato de la cadena es inválido.",
          );
        }else{
          final String cadenaFinal = utf8.decode(base64.decode(cadenaDesencriptada));
          final List<String> scan = cadenaFinal.split("|");

          final String urlLogo = 'https://www.plataforma-educativa.com.mx/services/${scan[3]}/images/${scan[0]}.png';
          final setScan = ScanModel(idEscuela: scan[0], nombreEscuela: scan[1], idUsuario: scan[2], logoEscuela: urlLogo);

          try{
            await DBProvider.db.newScan(setScan);
          }catch(e){
            print(e);
          }

          Navigator.pushReplacement(_scaffoldkey.currentContext!, MaterialPageRoute(
            builder: (context) => SessionPage(
              fcmToken: widget.fcmToken,
            )
          ));
        }
      }
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  DateTime todayDate(){
    final today = DateTime.now();

    final year = today.year;
    final month = today.month < 10 ? '0${today.month}' : today.month;
    final day = today.day < 10 ? '0${today.day}' : today.day;
    final hour = today.hour < 10 ? '0${today.hour}' : today.hour;
    final minute = today.minute < 10 ? '0${today.minute}' : today.minute;
    final second = today.second < 10 ? '0${today.second}' : today.second;
    const t = 'T';

    final formattedString = '$year-$month-$day$t$hour:$minute:$second';

    return DateTime.parse(formattedString);
  }
}
