import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:localstore/localstore.dart';
import 'package:quiosco_soler_2/clientes/pages/inicio_clientes.dart';
import 'package:quiosco_soler_2/clientes/providers/cli_provider.dart';
import 'package:quiosco_soler_2/clientes/providers/info_empleado_provider.dart';

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

  @override
  State<InicioEmpleados> createState() => _InicioEmpleadosState();
}

class _InicioEmpleadosState extends State<InicioEmpleados> {
  final _cliProvider = CliProvider();
  final _infoEmpleadoProvider = InfoEmpleadoProvider();
  final _nCliController = TextEditingController();
  final List<String> _listaNombres = [];
  final List<String> _listaID = [];
  final db = Localstore.instance;

  String _perfilParaClientes = '';
  String _usuarioActual = '';
  String _dinum = '';
  String _token = '';
  String _dbKey = '';
  bool _isLoading = true;
  bool _hasError = false;

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

  void _init() async{
    final items = await db.collection('clientes').get();
    final key = items!.keys.last;

    final item = items[key];
    _dinum = item['dinum'];
    _token = item['accesToken'];
    _dbKey = key.replaceAll('/clientes/', '');

    final info = await _infoEmpleadoProvider.fetchInfoEmpleado(item['accesToken'], item['dinum']);
    info.result.gblPerfiles.forEach((element) {
      if(element['IDPORTAL'] == 'CLI'){
        _perfilParaClientes = element['IDPERFIL']!;
      }
    });

    if(_perfilParaClientes != ''){
      final lista = await _cliProvider.fetchSListaClientes(item['accesToken'], _perfilParaClientes, item['dinum'],
      info.result.gblProZon, info.result.gblProDel);

      lista.result.forEach((element) {
        if(!_listaNombres.contains(element.nombre)){
          _listaNombres.add(element.nombre);
          _listaID.add(element.dinum);
        }
      });

      setState(() => _isLoading = false);
    }else{
      setState(() {
        _isLoading = false;
        _hasError = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Row(
          children: <Widget>[
            Image.asset(
              'assets/logo.png',
              width: 32.0,
            ),
            const SizedBox(width: 8.0),
            TextButton(
              style: TextButton.styleFrom(
                minimumSize: const Size(0.0, 0.0),
                padding: EdgeInsets.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
              child: const Icon(
                Icons.menu,
                color: Colors.white,
              ),
              onPressed: null,
            ),
            const Expanded(
              child: Text(
                'EMPLEADOS',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.red,
                  fontFamily: 'Helvetica Neue Black Cond',
                ),
              ),
            ),
            TextButton(
              style: TextButton.styleFrom(
                minimumSize: const Size(0.0, 0.0),
                padding: EdgeInsets.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
              child: const Icon(
                Icons.menu,
                color: Colors.white,
              ),
              onPressed: null,
            ),
            const SizedBox(width: 16.0),
            TextButton(
              style: TextButton.styleFrom(
                minimumSize: const Size(0.0, 0.0),
                padding: EdgeInsets.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
              child: const Icon(
                Icons.logout,
                color: Color(0xFFFF0000),
              ),
              onPressed: () => Navigator.pop(context),
            ),
          ],
        ),
      ),
      body: SafeArea(
        child: _isLoading ? const Center(
          child: CircularProgressIndicator(),
        ) : SingleChildScrollView(
          child: _hasError ? Center(
            child: AlertDialog(
              title: Text(
                '¡Error!',
                textAlign: TextAlign.center,
                style: GoogleFonts.roboto(
                  color: const Color.fromRGBO(255, 0, 0, 1),
                  fontWeight: FontWeight.bold,
                  fontSize: 24.0,
                ),
              ),
              content: Column(
                children: [
                  Image.asset(
                    'assets/error.png',
                    width: 58.0,
                  ),
                  const SizedBox(height: 16.0),
                  Text(
                    'No hemos podido encontrar nungún perfil relacionado a su número de usuario. Por favor contacte al departamento de TI de S&P.',
                    textAlign: TextAlign.center,
                    style: GoogleFonts.roboto(
                      color: Colors.black54,
                      fontWeight: FontWeight.w300,
                    ),
                  ),
                  const SizedBox(height: 8.0),
                ],
              ),
            ),
          ) : Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: _screenSize.width-64.0,
                margin: const EdgeInsets.only(top: 16.0),
                child: Text(
                  'Acceder como cliente',
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(
                    fontSize: 28.0,
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 32.0, vertical: 16.0),
                decoration: BoxDecoration(
                  border: Border.all(
                    width: 2.0,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.5),
                      spreadRadius: 3,
                      blurRadius: 7,
                      offset: const Offset(0,3),
                    ),
                  ],
                  color: Colors.white,
                ),
                width: _screenSize.width-64.0,
                child: Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          width: 98.0,
                          padding: const EdgeInsets.all(8.0),
                          decoration: const BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                width: 2.0,
                              ),
                            ),
                          ),
                          child: Text(
                            'Perfil:',
                            style: GoogleFonts.roboto(
                              fontSize: 16.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            decoration: const BoxDecoration(
                              border: Border(
                                bottom: BorderSide(
                                  width: 2.0,
                                ),
                              ),
                            ),
                            child: Text(
                              _perfilParaClientes,
                              style: GoogleFonts.roboto(
                                fontSize: 16.0,
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                    Row(
                      children: [
                        Container(
                          width: 98.0,
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                            'Usuario:',
                            style: GoogleFonts.roboto(
                              fontSize: 16.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              _dinum,
                              style: GoogleFonts.roboto(
                                fontSize: 16.0,
                              ),
                            ),
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
              Container(
                child: Text(
                  'Nombre de Cliente',
                  style: GoogleFonts.roboto(
                    fontSize: 16.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                margin: const EdgeInsets.fromLTRB(32.0, 8.0, 32.0, 4.0),
                width: double.infinity,
              ),
              Container(
                child: DropdownButton<String>(
                  value: _usuarioActual.isEmpty ? null : _usuarioActual,
                  hint: Text(
                    'Seleccione un usuario',
                    style: GoogleFonts.roboto(
                      color: Colors.grey,
                    ),
                  ),
                  items: _listaNombres.map((e) => DropdownMenuItem<String>(
                    value: e,
                    child: SizedBox(
                      width: _screenSize.width - 96.0,
                      child: Text(
                        e,
                        style: GoogleFonts.roboto(
                          color: Colors.black,
                        ),
                      ),
                    ),
                  )).toList(),
                  onChanged: (val) => setState(() {
                    _usuarioActual = val!;
                    _nCliController.clear();
                  }),
                ),
                margin: const EdgeInsets.fromLTRB(32.0, 0.0, 32.0, 8.0),
              ),
              Container(
                child: Text(
                  'Número de Cliente',
                  style: GoogleFonts.roboto(
                    fontSize: 16.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                margin: const EdgeInsets.fromLTRB(32.0, 0.0, 32.0, 8.0),
                width: double.infinity,
              ),
              Container(
                margin: const EdgeInsets.fromLTRB(32.0, 0.0, 32.0, 8.0),
                child: TextField(
                  decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    contentPadding: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 0.0),
                    hintText: 'Requerido',
                    hintStyle: GoogleFonts.roboto(
                      fontStyle: FontStyle.italic,
                    ),
                  ),
                  style: GoogleFonts.roboto(),
                  controller: _nCliController,
                  keyboardType: TextInputType.number,
                  onChanged: (val) => setState(() {
                    _usuarioActual = '';
                  }),
                ),
              ),
              Container(
                width: _screenSize.width-64.0,
                margin: const EdgeInsets.symmetric(horizontal: 32.0),
                padding: const EdgeInsets.all(8.0),
                color: const Color(0xFFCCCCCC),
                child: Text(
                  'Debe indicar únicamente el Nombre del Cliente o el Número del Cliente para continuar.',
                  style: GoogleFonts.roboto(
                    color: Colors.white,
                    fontSize: 18.0,
                  ),
                ),
              ),
              ElevatedButton(
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      'Acceder',
                      style: GoogleFonts.roboto(
                        fontSize: 16.0,
                      ),
                    ),
                    const SizedBox(width: 8.0),
                    const Icon(Icons.login)
                  ],
                ),
                onPressed: _nCliController.text.isEmpty && _usuarioActual.isEmpty ? null : () async{
                  FocusScope.of(context).requestFocus(FocusNode());
                  Fluttertoast.showToast(
                    msg: 'Validando datos...',
                    toastLength: Toast.LENGTH_SHORT,
                    gravity: ToastGravity.CENTER,
                    timeInSecForIosWeb: 3,
                  );

                  String id = '';
                  if(_nCliController.text.isEmpty && _usuarioActual.isNotEmpty){
                    id = _listaID[_listaNombres.indexOf(_usuarioActual)];
                  }else if(_nCliController.text.isNotEmpty && _usuarioActual.isEmpty){
                    id = _nCliController.text;
                  }

                  if(!_listaID.contains(id)){
                    Fluttertoast.showToast(
                      msg: 'El número de cliente ingresado es inválido',
                      toastLength: Toast.LENGTH_LONG,
                      gravity: ToastGravity.CENTER,
                      timeInSecForIosWeb: 3,
                    );
                  }else{
                    final cliente = await _cliProvider.fetchLoginComoCliente(_token, _dinum, id);
                    final data = await db.collection('clientes').doc(_dbKey).get();

                    data!['accesToken'] = cliente.result.accessToken;
                    data['dinumAfter'] = data['dinum'];
                    data['userAfter'] = data['user'];
                    data['dinum'] = cliente.result.dinum;
                    data['user'] = cliente.result.user;

                    await db.collection('clientes').doc(_dbKey).set(data);

                    await Navigator.push(context, MaterialPageRoute(
                      builder: (context) => const InicioClientes(),
                    ));
                  }
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}
