import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:localstore/localstore.dart';
import 'package:quiosco_soler_2/clientes/pages/inicio_clientes.dart';
import 'package:quiosco_soler_2/clientes/pages/inicio_empleados.dart';
import 'package:quiosco_soler_2/src/providers/login_provider.dart';

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

  @override
  State<LoginClientePage> createState() => _LoginClientePageState();
}

class _LoginClientePageState extends State<LoginClientePage> {
  final _dinumController = TextEditingController();
  final _dipassController = TextEditingController();
  final _loginProvider = LoginProvider();
  final db = Localstore.instance;

  @override
  void dispose() {
    _dinumController.dispose();
    _dipassController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            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),
                ],
              ),
              const SizedBox(height: 48.0),
              const Icon(
                Icons.account_circle,
                color: Color.fromRGBO(255, 0, 0, 1),
                size: 88.0,
              ),
              const SizedBox(height: 16.0),
              const Text(
                'CLIENTES',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontFamily: 'Helvetica Neue Black Cond',
                  fontSize: 28.0,
                ),
              ),
              const SizedBox(height: 32.0),
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 32.0),
                child: Column(
                  children: [
                    TextField(
                      controller: _dinumController,
                      decoration: const InputDecoration(
                        hintText: 'Usuario:',
                        contentPadding: EdgeInsets.zero,
                      ),
                      maxLines: 1,
                      cursorColor: const Color.fromRGBO(180, 4, 4, 1),
                      style: const TextStyle(fontSize: 20.0),
                    ),
                    const SizedBox(height: 16.0),
                    TextField(
                      controller: _dipassController,
                      obscureText: true,
                      decoration: const InputDecoration(
                        hintText: 'Contraseña:',
                        contentPadding: EdgeInsets.zero,
                      ),
                      maxLines: 1,
                      cursorColor: const Color.fromRGBO(180, 4, 4, 1),
                      style: const TextStyle(fontSize: 20.0),
                    ),
                    const SizedBox(height: 32.0),
                    MaterialButton(
                      elevation: 4.0,
                      padding: const EdgeInsets.symmetric(vertical: 8.0),
                      minWidth: _screenSize.width - 64.0,
                      color: const Color.fromRGBO(255, 0, 0, 1),
                      child: const Text(
                        'Entrar',
                        style: TextStyle(
                          fontFamily: 'Helvetica Neue Black Cond',
                          fontSize: 28.0,
                          color: Colors.white,
                        ),
                      ),
                      onPressed: () async{
                        FocusScope.of(context).requestFocus(FocusNode());
                        Fluttertoast.showToast(
                          msg: 'Validando datos...',
                          toastLength: Toast.LENGTH_LONG,
                          gravity: ToastGravity.CENTER,
                          timeInSecForIosWeb: 3,
                        );

                        final dinum = _dinumController.text;
                        final dipass = _dipassController.text;

                        _dinumController.clear();
                        _dipassController.clear();

                        final cliente = await _loginProvider.fetchLoginCliente(dinum, dipass);
                        if(!cliente.response){
                          Fluttertoast.showToast(
                            msg: 'Whoops!, parece que tus credenciales son incorrectas.',
                            toastLength: Toast.LENGTH_LONG,
                            gravity: ToastGravity.CENTER,
                            timeInSecForIosWeb: 3,
                          );
                        }else if(cliente.result.tipo == 'CLIENTE' || cliente.result.tipo == 'EMPLEADO'){
                          final dbItems = await db.collection('clientes').get();

                          if(dbItems != null){
                            dbItems.forEach((key, value) async{
                              await db.collection('clientes').doc(key).delete();
                            });
                          }

                          final logID = db.collection('clientes').doc().id;
                          
                          await db.collection('clientes').doc(logID).set({
                            "accesToken": cliente.result.accessToken,
                            "user": cliente.result.user,
                            "dinum": cliente.result.dinum,
                          });

                          Navigator.push(context, MaterialPageRoute(
                            builder: (context) => cliente.result.tipo == 'CLIENTE'
                              ? const InicioClientes() : const InicioEmpleados(),
                          ));
                        }else{
                          Fluttertoast.showToast(
                            msg: 'Su usuario no tiene acceso al portal de clientes, consulte al departamente de TI de S&P.',
                            toastLength: Toast.LENGTH_LONG,
                            gravity: ToastGravity.CENTER,
                            timeInSecForIosWeb: 3,
                          );
                        }
                      },
                    ),
                    const SizedBox(height: 32.0),
                    MaterialButton(
                      elevation: 4.0,
                      padding: const EdgeInsets.symmetric(vertical: 8.0),
                      minWidth: _screenSize.width - 64.0,
                      color: const Color.fromRGBO(255, 0, 0, 1),
                      child: const Text(
                        'Regresar',
                        style: TextStyle(
                          fontFamily: 'Helvetica Neue Black Cond',
                          fontSize: 28.0,
                          color: Colors.white,
                        ),
                      ),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 32.0),
            ],
          ),
        ),
      ),
    );
  }
}
