import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:localstore/localstore.dart';
import 'package:memorias_calculo_web/src/pages/index_page.dart';
import 'package:memorias_calculo_web/src/pages/loading.dart';
import 'package:memorias_calculo_web/src/pages/login.dart';
import 'package:memorias_calculo_web/src/pages/not_found.dart';
import 'package:memorias_calculo_web/src/pages/ventilacion_ambiental_page.dart';
import 'package:memorias_calculo_web/src/pages/ventilacion_estacionamientos.dart';
import 'package:memorias_calculo_web/src/pages/ventilacion_localizada_page.dart';
import 'package:memorias_calculo_web/src/pages/verification.dart';
import 'package:memorias_calculo_web/src/providers/validar_token_provider.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final db = Localstore.instance;
  final GlobalKey<NavigatorState> _navKey = GlobalKey<NavigatorState>();
  final ValidarTokenProvider _validarTokenProvider = ValidarTokenProvider();

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: _navKey,
      title: 'Portal de Memorias de Cálculo',
      debugShowCheckedModeBanner: false,
      scrollBehavior: ScrollRules(),
      theme: ThemeData(
        brightness: Brightness.light,
        primaryColor: const Color(0xFFFF0000),
        splashColor: const Color.fromRGBO(180, 4, 4, 1),
        colorScheme: const ColorScheme.light(
          primary: Color.fromRGBO(180, 4, 4, 1),
          secondary: Color.fromRGBO(180, 4, 4, 1),
        ),
      ),
      initialRoute: "cargando",
      routes: {
        "cargando" : (ctx) => const LoadingPage(),
        "404"      : (ctx) => const NotFoundPage(),
        "login"    : (ctx) => const LoginPage(),
        "index"    : (ctx) => const IndexPage(),
        "ventilacionLocalizada": (ctx) => const VentilacionLocalizadaPage(),
        "ventilacionEstacionamientos": (ctx) => const VentilacionEstacionamientosPage(),
        "ventilacionAmbiental": (ctx) => const VentilacionAmbientalPage()
      },
      onGenerateRoute: (RouteSettings settings) {
        _navKey.currentState?.pushReplacementNamed("404");
        return MaterialPageRoute(builder: (ctx) => const NotFoundPage());
      },
    );
  }

  getItems() async{
    final items = await db.collection("login").get();
    if(items == null){
      _navKey.currentState?.pushReplacementNamed("login");
    }else{
      final lastID = items.keys.last;
      final info = items[lastID];

      final bool valido = await _validarTokenProvider.validar(info["token"]);
      if(valido){
        final verificacion = info['verificacion'];

        if(verificacion == "1" || verificacion == "2" || verificacion == "3"){
          _navKey.currentState?.pushReplacement(MaterialPageRoute(
            builder: (context) => VerificacionPage(
              correo: info['correo'],
              numTel: info['movil'],
              pais: info['pais'],
              verificacion: verificacion,
              idUsuario: info['idUsuario'],
            ),
          ));
        }else{
          final action = await _navKey.currentState?.pushReplacementNamed("index");
          if(action == "logout"){
            final items = await db.collection('login').get();
            items!.forEach((key, value) {
              db.collection('login').doc(key).delete();
            });

            _navKey.currentState?.pushNamed("login");
          }
        }
      }else{
        db.collection('login').doc(lastID).delete();
        _navKey.currentState?.pushReplacementNamed("login");
      }
    }
  }
}

class ScrollRules extends MaterialScrollBehavior{
  @override
  Set<PointerDeviceKind> get dragDevices => {
    PointerDeviceKind.touch,
    PointerDeviceKind.mouse
  };
}
