import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.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/table_calendar_page.dart';
import 'package:plataforma_educativa/src/providers/db_provider.dart';
import 'package:plataforma_educativa/src/widgets/fade_route_builder.dart';
import 'package:plataforma_educativa/src/widgets/lateral_menu.dart';
import 'package:rect_getter/rect_getter.dart';

import 'mensajes_page.dart';

class MenuPage extends StatefulWidget {
  final bool esPadre;
  final bool revisaHijo;
  final String fcmToken;

  const MenuPage({Key? key, required this.esPadre, required this.revisaHijo, required this.fcmToken}) : super(key: key);

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

class _MenuPageState extends State<MenuPage> {
  final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>();
  final _rectCalendarGetter = RectGetter.createGlobalKey();
  final _rectChatsGetter = RectGetter.createGlobalKey();
  final _rectBitacoraGetter = RectGetter.createGlobalKey();
  final _rectCircularesGetter = RectGetter.createGlobalKey();
  Rect? _chatsRect;
  Rect? _calendarRect;
  LocalUserModel? _hijoInfo;
  late LocalUserModel _userInfo;
  late ScanModel _escuela;
  late bool _puedeChatear;
  late String _grado;
  bool _isLoading = true;

  final Duration _animationDuration = const Duration(milliseconds: 750);
  final Duration _delay = const Duration(milliseconds: 50);

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

    _init();
  }

  void _init() async{
    final users = await DBProvider.db.getAllUsers();
    _userInfo = users.first;

    final escuelas = await DBProvider.db.getAllScans();
    _escuela = escuelas.first;
    print("ESCUELAS: $_escuela");

    if(widget.revisaHijo && users.length > 1){
      _hijoInfo = users.last;
      _puedeChatear = _hijoInfo!.publicKey != "no-data";

      if(_hijoInfo!.grado == "NA"){
        _grado = _hijoInfo!.tipoUsuario == 'AD' ? 'Administrador'
            : _hijoInfo!.tipoUsuario == 'SU' ? 'Super Usuario'
            : _hijoInfo!.tipoUsuario == 'PR' ? 'Profesor'
            : _hijoInfo!.tipoUsuario == 'PF' ? 'Padre de Familia'
            : _hijoInfo!.tipoUsuario == 'AL' ? 'Alumno'
            : 'Ningún tipo';
      }else{
        _grado = '${_hijoInfo!.grado}° de ${_hijoInfo!.nivel}';
      }
    }else{
      _puedeChatear = true;

      if(_userInfo.grado == 'NA'){
        _grado = _userInfo.tipoUsuario == 'AD' ? 'Administrador'
            : _userInfo.tipoUsuario == 'SU' ? 'Super Usuario'
            : _userInfo.tipoUsuario == 'PR' ? 'Profesor'
            : _userInfo.tipoUsuario == 'PF' ? 'Padre de Familia'
            : _userInfo.tipoUsuario == 'AL' ? 'Alumno'
            : 'Ningún tipo';
      }else{
        _grado = '${_userInfo.grado}° de ${_userInfo.nivel}';
      }
    }

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

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    return Stack(
      children: [
        Scaffold(
          key: _scaffoldkey,
          endDrawer: LateralMenu(
            context: context,
            token: widget.fcmToken,
          ),
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage("assets/sesion.png"),
                fit: BoxFit.cover,
              )
            ),
            width: _screenSize.width,
            height: _screenSize.height,
            child: SafeArea(
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      TextButton(
                        child: Icon(
                          Icons.arrow_back_ios,
                          color: widget.esPadre ? const Color.fromRGBO(22, 23, 112, 1) : Colors.transparent,
                          size: 32.0,
                        ),
                        onPressed: !widget.esPadre ? null : () async{
                          if(widget.revisaHijo){
                            await DBProvider.db.deleteAllUsers();
                            await DBProvider.db.newUserRaw(_userInfo);
                          }
                          Navigator.pop(context);
                        },
                        style: TextButton.styleFrom(
                          padding: const EdgeInsets.all(8.0),
                          minimumSize: const Size(0.0, 0.0),
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap
                        ),
                      ),
                      Expanded(
                        child: Text(
                          "Menú",
                          style: GoogleFonts.montserrat(
                            fontSize: 20.0,
                            color: Colors.black38,
                            fontWeight: FontWeight.w500,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      TextButton(
                        child: const Icon(
                          Icons.menu,
                          color: Color.fromRGBO(22, 23, 112, 1),
                          size: 32.0,
                        ),
                        onPressed: () => _scaffoldkey.currentState!.openEndDrawer(),
                        style: TextButton.styleFrom(
                            padding: const EdgeInsets.all(8.0),
                            minimumSize: const Size(0.0, 0.0),
                            tapTargetSize: MaterialTapTargetSize.shrinkWrap
                        ),
                      ),
                    ],
                  ),
                  Expanded(
                    child: _isLoading ? Center(
                      child: Image.asset(
                        "assets/loading.gif",
                        width: 64.0,
                      ),
                    ) : SizedBox(
                      width: _screenSize.width,
                      child: SingleChildScrollView(
                        child: Column(
                          children: [
                            FadeInImage(
                              image: NetworkImage(_escuela.logoEscuela),
                              fit: BoxFit.fill,
                              placeholder: const AssetImage("assets/loading.gif"),
                              fadeInDuration: const Duration(milliseconds: 200),
                              height: 96.0,
                            ),
                            const SizedBox(height: 4.0),
                            FadeInImage(
                              image: const NetworkImage('https://www.plataforma-educativa.com.mx/api/QA/movil/img/ninop0.png'),
                              placeholder: const AssetImage('assets/loading.gif'),
                              fadeInDuration: const Duration(milliseconds: 200),
                              width: _screenSize.width*0.5,
                            ),
                            const SizedBox(height: 12.0),
                            Container(
                              alignment: Alignment.center,
                              child: Column(
                                children: [
                                  Text(
                                    "ID ${widget.revisaHijo ? _hijoInfo!.idUsuario : _userInfo.idUsuario}",
                                    style: GoogleFonts.montserrat(
                                      color: Colors.grey,
                                    ),
                                  ),
                                  const SizedBox(height: 6.0),
                                  SizedBox(
                                    width: _screenSize.width * 0.8,
                                    child: Text(
                                      _completeName(
                                        widget.revisaHijo ? _hijoInfo!.primerNombre : _userInfo.primerNombre,
                                        widget.revisaHijo ? _hijoInfo!.segundoNombre : _userInfo.segundoNombre,
                                        widget.revisaHijo ? _hijoInfo!.apellidoPaterno : _userInfo.apellidoPaterno,
                                        widget.revisaHijo ? _hijoInfo!.apellidoMaterno : _userInfo.apellidoMaterno
                                      ),
                                      style: GoogleFonts.montserrat(
                                        color: const Color.fromRGBO(22, 23, 112, 1),
                                        fontSize: 18.0, fontWeight: FontWeight.bold,
                                        letterSpacing: 0.17,
                                      ),
                                      textAlign: TextAlign.center,
                                    ),
                                  ),
                                  const SizedBox(height: 6.0),
                                  Text(
                                    _grado,
                                    style: GoogleFonts.montserrat(
                                      color: Colors.grey,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(height: 16.0),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 32.0,
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Expanded(
                                    child: ElevatedButton(
                                      child: RectGetter(
                                        key: _rectCalendarGetter,
                                        child: SizedBox(
                                          width: ((_screenSize.width - 64) / 2) - 16,
                                          height: ((_screenSize.width - 64) / 2) - 32,
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.circular(24.0),
                                            child: Stack(
                                              alignment: Alignment.center,
                                              children: [
                                                SizedBox(height: ((_screenSize.width - 64) / 2) - 32),
                                                Positioned(
                                                  child: Image.asset(
                                                    "assets/fn10.png",
                                                    height: (((_screenSize.width - 64) / 2) - 32) / 2,
                                                    width: ((_screenSize.width - 64) / 2) - 16,
                                                    fit: BoxFit.cover,
                                                  ),
                                                  bottom: 0.0,
                                                ),
                                                Image.asset(
                                                  "assets/ic40.png",
                                                  width: (((_screenSize.width - 64) / 2) - 16) - 32,
                                                ),
                                                Positioned(
                                                  bottom: 8.0,
                                                  child: SizedBox(
                                                    width: ((_screenSize.width - 64) / 2) - 16,
                                                    child: Text(
                                                      "Calendario",
                                                      textAlign: TextAlign.center,
                                                      style: GoogleFonts.montserrat(
                                                        fontWeight: FontWeight.w200,
                                                        fontSize: 16.0,
                                                        color: Colors.white,
                                                      ),
                                                    ),
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                      onPressed: _onTapCalendar,
                                      style: ElevatedButton.styleFrom(
                                        padding: EdgeInsets.zero,
                                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                        minimumSize: const Size(0.0, 0.0),
                                        elevation: 4.0,
                                        primary: Colors.white,
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(24.0),
                                        ),
                                      ),
                                    ),
                                  ),
                                  const SizedBox(width: 32.0),
                                  Expanded(
                                    child: ElevatedButton(
                                      child: RectGetter(
                                        key: _rectChatsGetter,
                                        child: SizedBox(
                                          width: ((_screenSize.width - 64) / 2) - 16,
                                          height: ((_screenSize.width - 64) / 2) - 32,
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.circular(24.0),
                                            child: Stack(
                                              alignment: Alignment.center,
                                              children: [
                                                SizedBox(height: ((_screenSize.width - 64) / 2) - 32),
                                                Positioned(
                                                  child: Image.asset(
                                                    "assets/fn20.png",
                                                    height: (((_screenSize.width - 64) / 2) - 32) / 2,
                                                    width: ((_screenSize.width - 64) / 2) - 16,
                                                    fit: BoxFit.cover,
                                                  ),
                                                  bottom: 0.0,
                                                ),
                                                Image.asset(
                                                  "assets/ic20.png",
                                                  width: (((_screenSize.width - 64) / 2) - 16) - 48,
                                                ),
                                                Positioned(
                                                  bottom: 8.0,
                                                  child: SizedBox(
                                                    width: ((_screenSize.width - 64) / 2) - 16,
                                                    child: Text(
                                                      "Chats",
                                                      textAlign: TextAlign.center,
                                                      style: GoogleFonts.montserrat(
                                                        fontWeight: FontWeight.w200,
                                                        fontSize: 16.0,
                                                        color: Colors.white,
                                                      ),
                                                    ),
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                      onPressed: _puedeChatear ? _onTapChat : () => Fluttertoast.showToast(
                                        msg: 'Este usuario aún no ha generado las claves necesarias para conversar.',
                                        toastLength: Toast.LENGTH_LONG,
                                        timeInSecForIosWeb: 2,
                                        fontSize: 14.0,
                                        gravity: ToastGravity.CENTER,
                                        backgroundColor: Colors.grey,
                                        textColor: Colors.white,
                                      ),
                                      style: ElevatedButton.styleFrom(
                                        padding: EdgeInsets.zero,
                                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                        minimumSize: const Size(0.0, 0.0),
                                        elevation: 4.0,
                                        primary: Colors.white,
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(24.0),
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(height: 16.0),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 32.0,
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Expanded(
                                    child: ElevatedButton(
                                      child: RectGetter(
                                        key: _rectBitacoraGetter,
                                        child: SizedBox(
                                          width: ((_screenSize.width - 64) / 2) - 16,
                                          height: ((_screenSize.width - 64) / 2) - 32,
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.circular(24.0),
                                            child: Stack(
                                              alignment: Alignment.center,
                                              children: [
                                                SizedBox(height: ((_screenSize.width - 64) / 2) - 32),
                                                Positioned(
                                                  child: Image.asset(
                                                    "assets/fn40.png",
                                                    height: (((_screenSize.width - 64) / 2) - 32) / 2,
                                                    width: ((_screenSize.width - 64) / 2) - 16,
                                                    fit: BoxFit.cover,
                                                  ),
                                                  bottom: 0.0,
                                                ),
                                                Image.asset(
                                                  "assets/ic0.png",
                                                  width: (((_screenSize.width - 64) / 2) - 16) - 48,
                                                ),
                                                Positioned(
                                                  bottom: 8.0,
                                                  child: SizedBox(
                                                    width: ((_screenSize.width - 64) / 2) - 16,
                                                    child: Text(
                                                      "Bitácora",
                                                      textAlign: TextAlign.center,
                                                      style: GoogleFonts.montserrat(
                                                        fontWeight: FontWeight.w200,
                                                        fontSize: 16.0,
                                                        color: Colors.white,
                                                      ),
                                                    ),
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                      onPressed: () => print("HOLA 2"),
                                      style: ElevatedButton.styleFrom(
                                        padding: EdgeInsets.zero,
                                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                        minimumSize: const Size(0.0, 0.0),
                                        elevation: 4.0,
                                        primary: Colors.white,
                                        shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(24.0)
                                        ),
                                      ),
                                    ),
                                  ),
                                  const SizedBox(width: 32.0),
                                  Expanded(
                                    child: ElevatedButton(
                                      child: RectGetter(
                                        key: _rectCircularesGetter,
                                        child: SizedBox(
                                          width: ((_screenSize.width - 64) / 2) - 16,
                                          height: ((_screenSize.width - 64) / 2) - 32,
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.circular(24.0),
                                            child: Stack(
                                              alignment: Alignment.center,
                                              children: [
                                                SizedBox(height: ((_screenSize.width - 64) / 2) - 32),
                                                Positioned(
                                                  child: Image.asset(
                                                    "assets/fn30.png",
                                                    height: (((_screenSize.width - 64) / 2) - 32) / 2,
                                                    width: ((_screenSize.width - 64) / 2) - 16,
                                                    fit: BoxFit.cover,
                                                  ),
                                                  bottom: 0.0,
                                                ),
                                                Image.asset(
                                                  "assets/ic30.png",
                                                  width: (((_screenSize.width - 64) / 2) - 16) - 48,
                                                ),
                                                Positioned(
                                                  bottom: 8.0,
                                                  child: SizedBox(
                                                    width: ((_screenSize.width - 64) / 2) - 16,
                                                    child: Text(
                                                      "Circulares",
                                                      textAlign: TextAlign.center,
                                                      style: GoogleFonts.montserrat(
                                                        fontWeight: FontWeight.w200,
                                                        fontSize: 16.0,
                                                        color: Colors.white,
                                                      ),
                                                    ),
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                      onPressed: () => print("HOLA 2"),
                                      style: ElevatedButton.styleFrom(
                                        padding: EdgeInsets.zero,
                                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                        minimumSize: const Size(0.0, 0.0),
                                        elevation: 4.0,
                                        primary: Colors.white,
                                        shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(24.0)
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(height: 16.0),
                          ],
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
        _rippleCalendar(context),
        _rippleChats(context),
      ],
    );
  }

  String _completeName(String pNom, String sNom, String aPat, String aMat){
    String nom = '$pNom $sNom $aPat $aMat';
    nom = nom.replaceAll("null", "");
    nom = nom.replaceAll("  ", " ");

    return nom;
  }

  _onTapChat() async{
    setState(() => _chatsRect = RectGetter.getRectFromKey(_rectChatsGetter));
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      setState(() {
        _chatsRect = _chatsRect!.inflate(1.3 * MediaQuery.of(context).size.longestSide);
      });
      Future.delayed(_animationDuration + _delay, _goToChats);
    });
  }

  void _goToChats(){
    Navigator.of(context).push(FadeRouteBuilder(page: MensajesPage(revisaHijo: widget.revisaHijo, fcmToken: widget.fcmToken))).then((value) => setState(() => _chatsRect = null));
  }

  Widget _rippleChats(BuildContext context){
    final _screenSize = MediaQuery.of(context).size;
    if(_chatsRect == null){
      return Container();
    }
    return AnimatedPositioned(
      duration: _animationDuration,
      left: _chatsRect!.left,
      right: MediaQuery.of(context).size.width - _chatsRect!.right,
      top: _chatsRect!.top,
      bottom: MediaQuery.of(context).size.height - _chatsRect!.bottom,
      child: Container(
        width: _screenSize.width*0.325,
        height: _screenSize.width*0.275,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.0),
            gradient: const LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [Color.fromRGBO(56, 109, 160, 1), Color.fromRGBO(22, 23, 112, 1)]
            )
        ),
      ),
    );
  }

  _onTapCalendar() async{
    setState(() => _calendarRect = RectGetter.getRectFromKey(_rectCalendarGetter));
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      setState(() {
        _calendarRect = _calendarRect!.inflate(1.3 * MediaQuery.of(context).size.longestSide);
      });
      Future.delayed(_animationDuration + _delay, _goToCalendar);
    });
  }

  void _goToCalendar(){
    Navigator.of(context).push(FadeRouteBuilder(page: TableCalendarPage(revisaHijo: widget.revisaHijo))).then((value) => setState(() => _calendarRect = null));
  }

  Widget _rippleCalendar(BuildContext context){
    final _screenSize = MediaQuery.of(context).size;
    if(_calendarRect == null){
      return Container();
    }
    return AnimatedPositioned(
      duration: _animationDuration,
      left: _calendarRect!.left,
      right: MediaQuery.of(context).size.width - _calendarRect!.right,
      top: _calendarRect!.top,
      bottom: MediaQuery.of(context).size.height - _calendarRect!.bottom,
      child: Container(
        width: _screenSize.width*0.325,
        height: _screenSize.width*0.275,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.0),
            gradient: const LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [Colors.yellow, Colors.orange]
            )
        ),
      ),
    );
  }
}
