import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:quiosco_soler_2/calculadora/pages/calculadora.dart';
import 'package:quiosco_soler_2/catalogo/pages/index_catalogo.dart';
import 'package:quiosco_soler_2/clientes/pages/login_cliente.dart';
import 'package:quiosco_soler_2/memorias_calculo/pages/login_memorias.dart';
import 'package:quiosco_soler_2/quiosco/pages/login_page.dart';
import 'package:quiosco_soler_2/src/pages/about_page.dart';
import 'package:quiosco_soler_2/src/pages/check_page.dart';
import 'package:quiosco_soler_2/src/providers/db_provider.dart';
import 'package:quiosco_soler_2/src/providers/imei_provider.dart';

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

  @override
  State<MenuInicio> createState() => _MenuInicioState();
}

class _MenuInicioState extends State<MenuInicio> {
  final _imeiProvider = ImeiProvider();
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  bool _isLoading = true;
  bool _hasQuiosco = false;
  double _fontSize = 16.0;

  Future<String> initPlatformState() async{
    String udidIOS = '';
    String udidAndroid = '';

    int version = 0;
    final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();

    try{
      if(Platform.isAndroid){
        var build = await deviceInfoPlugin.androidInfo;
        udidAndroid = build.id!;
        version = build.version.sdkInt!;
        print(version);
      }else if(Platform.isIOS){
        var data = await deviceInfoPlugin.iosInfo;
        udidIOS = data.identifierForVendor!;
      }
    } on PlatformException {
      return '';
    }


    if (version < 33 && Platform.isAndroid) {
      final status = await Permission.storage.status;
      if(status.isDenied){
        final response = await Permission.storage.request();
        if(response.isDenied || response.isPermanentlyDenied){
          Navigator.pushReplacement(_scaffoldKey.currentContext!, MaterialPageRoute(
            builder: (context) => const CheckPage(),
          ));
        }
      }
    }

    if(!mounted && Platform.isAndroid) return '';
    if(!mounted && Platform.isIOS) return '';

    if(Platform.isAndroid){
      return udidAndroid;
    }else if(Platform.isIOS){
      return udidIOS;
    }else{
      return '';
    }
  }

  @override
  void initState() {
    super.initState();
    initPlatformState().then((imei){
      _imeiProvider.fetchImei(imei).then((value){
        setState(() {
          _isLoading = false;
          _hasQuiosco = value.response;
          //_hasQuiosco = true;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;

    if(_screenSize.width <= 360){
      _fontSize = 12.0;
    }else if(_screenSize.width > 360 && _screenSize.width <= 400){
      _fontSize = 14.0;
    }else{
      _fontSize = 16.0;
    }

    return Scaffold(
      key: _scaffoldKey,
      body: SafeArea(
        child: _isLoading ? const Center(
          child: CircularProgressIndicator(),
        ) : SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            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),
                ],
              ),
              Container(
                width: _screenSize.width,
                padding: const EdgeInsets.symmetric(horizontal: 32.0),
                child: IconButton(
                  icon: const Icon(
                    Icons.info_outline,
                    color: Color(0xFF333333),
                    size: 32.0,
                  ),
                  onPressed: () => Navigator.push(context, MaterialPageRoute(
                    builder: (context) => const AboutPage(),
                  )),
                ),
                alignment: Alignment.centerRight,
              ),
              Container(
                margin: const EdgeInsets.fromLTRB(32.0, 0.0, 32.0, 32.0),
                width: _screenSize.width,
                child: Text(
                  'Para comenzar, selecciona la función a la que deseas acceder',
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(
                    fontSize: 24.0,
                  ),
                ),
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(width: 32.0),
                  ElevatedButton(
                    onPressed: () => Navigator.push(context, MaterialPageRoute(
                      builder: (context) => const LoginClientePage()
                    )),
                    child: Column(
                      children: [
                        const SizedBox(height: 16.0),
                        const Icon(
                          Icons.account_circle,
                          color: Color(0xFFFF0000),
                          size: 64.0,
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
                          child: Text(
                            'Acceso de Clientes',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.roboto(
                              fontSize: _fontSize,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          height: 8.0,
                          color: const Color(0xFFFF0000),
                        )
                      ],
                    ),
                    style: ElevatedButton.styleFrom(
                      elevation: 8.0,
                      primary: Colors.white,
                      padding: EdgeInsets.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      minimumSize: const Size(0.0, 0.0),
                    ),
                  ),
                  const SizedBox(width: 32.0),
                  ElevatedButton(
                    onPressed: () => Navigator.push(context, MaterialPageRoute(
                      builder: (context) => const IndexCatalogo(),
                    )),
                    child: Column(
                      children: [
                        const SizedBox(height: 16.0),
                        const Icon(
                          Icons.view_carousel,
                          color: Color(0xFFFF0000),
                          size: 64.0,
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
                          child: Text(
                            'Catálogo de Productos',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.roboto(
                              fontSize: _fontSize,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          height: 8.0,
                          color: const Color(0xFFFF0000),
                        )
                      ],
                    ),
                    style: ElevatedButton.styleFrom(
                      elevation: 8.0,
                      primary: Colors.white,
                      padding: EdgeInsets.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      minimumSize: const Size(0.0, 0.0),
                    ),
                  ),
                  const SizedBox(width: 32.0),
                ],
              ),
              const SizedBox(height: 32.0),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(width: 32.0),
                  ElevatedButton(
                    onPressed: () => Navigator.push(context, MaterialPageRoute(
                      builder: (context) => const LoginMemorias(),
                    )),
                    child: Column(
                      children: [
                        const SizedBox(height: 16.0),
                        Image.asset(
                          'assets/matriz.png',
                          width: 64.0,
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
                          child: Text(
                            'Portal de Memorias de Cálculo',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.roboto(
                              fontSize: _fontSize,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          height: 8.0,
                          color: const Color(0xFFFF0000),
                        )
                      ],
                    ),
                    style: ElevatedButton.styleFrom(
                        elevation: 8.0,
                        primary: Colors.white,
                        padding: EdgeInsets.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        minimumSize: const Size(0.0, 0.0)
                    ),
                  ),
                  /*ElevatedButton(
                    onPressed: () => Navigator.push(context, MaterialPageRoute(
                      builder: (context) => const CalculadoraPage(),
                    )),
                    child: Column(
                      children: [
                        const SizedBox(height: 16.0),
                        const Icon(
                          Icons.exposure,
                          color: Color(0xFFFF0000),
                          size: 64.0,
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
                          child: Text(
                            'Calculadora de Atenuadores Acústicos',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.roboto(
                              fontSize: _fontSize,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          height: 8.0,
                          color: const Color(0xFFFF0000),
                        )
                      ],
                    ),
                    style: ElevatedButton.styleFrom(
                        elevation: 8.0,
                        primary: Colors.white,
                        padding: EdgeInsets.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        minimumSize: const Size(0.0, 0.0)
                    ),
                  ),*/
                  const SizedBox(width: 32.0),
                  if(_hasQuiosco)
                    ElevatedButton(
                    onPressed: () async{
                      final response = await DBProvider.db.getLoginInfo();
                      Navigator.push(context, MaterialPageRoute(
                          builder: (context) => LoginPage(
                            response: response['response'],
                            dateTime: response['fecha'],
                            pass: response['pass'],
                          )
                      ));
                    },
                    child: Column(
                      children: [
                        const SizedBox(height: 16.0),
                        Image.asset(
                          'assets/quiosco.png',
                          width: 64.0,
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
                          child: Text(
                            'Quiosco de Documentos',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.roboto(
                              fontSize: _fontSize,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          height: 8.0,
                          color: const Color(0xFFFF0000),
                        )
                      ],
                    ),
                    style: ElevatedButton.styleFrom(
                        elevation: 8.0,
                        primary: Colors.white,
                        padding: EdgeInsets.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        minimumSize: const Size(0.0, 0.0)
                    ),
                  ),
                  if(_hasQuiosco)
                    const SizedBox(width: 32.0),
                ],
              ),
              const SizedBox(height: 32.0),
              /*if(_hasQuiosco)
                Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(width: 32.0),
                  ElevatedButton(
                    onPressed: () async{
                      final response = await DBProvider.db.getLoginInfo();
                      Navigator.push(context, MaterialPageRoute(
                        builder: (context) => LoginPage(
                          response: response['response'],
                          dateTime: response['fecha'],
                          pass: response['pass'],
                        )
                      ));
                    },
                    child: Column(
                      children: [
                        const SizedBox(height: 16.0),
                        Image.asset(
                          'assets/quiosco.png',
                          width: 64.0,
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
                          child: Text(
                            'Quiosco de Documentos',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.roboto(
                              fontSize: _fontSize,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        Container(
                          width: (_screenSize.width - 96.0) / 2,
                          height: 8.0,
                          color: const Color(0xFFFF0000),
                        )
                      ],
                    ),
                    style: ElevatedButton.styleFrom(
                        elevation: 8.0,
                        primary: Colors.white,
                        padding: EdgeInsets.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        minimumSize: const Size(0.0, 0.0)
                    ),
                  ),
                  const SizedBox(width: 32.0),
                ],
              ),
              if(_hasQuiosco)
                const SizedBox(height: 32.0),*/
            ],
          ),
        ),
      ),
    );
  }
}
