import 'package:dart_ipify/dart_ipify.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:localstore/localstore.dart';

import '../providers/dudas_provider.dart';

class ComentariosPage extends StatefulWidget {
  @override
  _ComentariosPageState createState() => _ComentariosPageState();
}

class _ComentariosPageState extends State<ComentariosPage> {
  final _asuntoController = TextEditingController();
  final _nombreController = TextEditingController();
  final _correoController = TextEditingController();
  final _mensajeController = TextEditingController();
  final _dudasProvider = DudasProvider();
  final List<String> _departamentos = ['CUENTAS POR COBRAR', 'COMERCIAL'];
  final List<bool> _showErrorMsg = [false, false, false, false];
  final String _errorMsg = '*Aún no has completado este campo';
  final String _errorMsg2 = '*Este campo debe contener al menos 35 caracteres';
  final db = Localstore.instance;

  late String _departamenoSeleccionado;
  late String _ipAddress;
  late List<DropdownMenuItem<String>> _dropDownMenuItems;
  late Map<String, dynamic> _info;

  Future<void> _initIpAddress() async{
    //_ipAddress = await GetIp.ipAddress;
    _ipAddress = await Ipify.ipv4();

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

    _info = items[key];
  }

  @override
  void initState() {
    _dropDownMenuItems = getDropDownMenuItems();
    _departamenoSeleccionado = _dropDownMenuItems[0].value!;
    _initIpAddress();
    super.initState();
  }

  @override
  void dispose() {
    _asuntoController.dispose();
    _correoController.dispose();
    _mensajeController.dispose();
    _nombreController.dispose();

    super.dispose();
  }

  List<DropdownMenuItem<String>> getDropDownMenuItems() {
    List<DropdownMenuItem<String>> items = [];
    for (String city in _departamentos) {
      items.add(DropdownMenuItem(
          value: city,
          child: Text(city)
      ));
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Dudas y/o Comentarios',
          style: GoogleFonts.roboto(
              fontWeight: FontWeight.w700,
              color: Color(0xFF67616B)
          ),
        ),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.send),
            onPressed: (){
              FocusScope.of(context).requestFocus(FocusNode());

              setState(() {
                _showErrorMsg[0] = _asuntoController.text.isEmpty;
                _showErrorMsg[1] = _asuntoController.text.isEmpty;
                _showErrorMsg[2] = _asuntoController.text.isEmpty;
                _showErrorMsg[3] = _asuntoController.text.isEmpty;
              });

              if(_asuntoController.text.isEmpty || _nombreController.text.isEmpty || _correoController.text.isEmpty || _mensajeController.text.isEmpty){
                Fluttertoast.showToast(
                  msg: 'Error al enviar el mensaje.',
                  backgroundColor: const Color(0xFFFF0000),
                  textColor: const Color(0xFFFFFFFF),
                  toastLength: Toast.LENGTH_LONG,
                  timeInSecForIosWeb: 3,
                  gravity: ToastGravity.CENTER,
                );
              }else{
                _dudasProvider.enviarDudas(
                  _info['accesToken'],
                  _info['dinum'],
                  _departamenoSeleccionado.toUpperCase(),
                  _nombreController.text,
                  _correoController.text,
                  _asuntoController.text,
                  _ipAddress,
                  _mensajeController.text,
                ).then((res){
                  if(res['error']){
                    Fluttertoast.showToast(
                      msg: res['mensaje'],
                      backgroundColor: const Color(0xFFFF0000),
                      textColor: const Color(0xFFFFFFFF),
                      toastLength: Toast.LENGTH_LONG,
                      timeInSecForIosWeb: 3,
                      gravity: ToastGravity.CENTER,
                    );
                  }else{
                    Fluttertoast.showToast(
                      msg: res['mensaje'],
                      backgroundColor: const Color(0xFF6AEB5E),
                      textColor: Colors.white,
                      toastLength: Toast.LENGTH_LONG,
                      timeInSecForIosWeb: 3,
                      gravity: ToastGravity.CENTER,
                    );
                  }
                  _nombreController.text = '';
                  _correoController.text = '';
                  _mensajeController.text = '';
                  _asuntoController.text = '';
                });
              }
            },
          )
        ],
        backgroundColor: Colors.white,
        iconTheme: const IconThemeData(
          color: Color.fromRGBO(255, 0, 0, 1),
        ),
      ),
      body: SizedBox(
        width: _screenSize.width,
        height: _screenSize.height,
        child: Stack(
          children: [
            Positioned(
              bottom: 0.0,
              right: 0.0,
              child: Image.asset(
                'assets/carteraVencer.png',
                width: _screenSize.width*0.75,
                fit: BoxFit.cover,
              ),
            ),
            SafeArea(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      margin: const EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                      child: Text(
                        'Departamento:',
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(
                            fontWeight: FontWeight.w500,
                            fontSize: 16.0
                        ),
                      ),
                      width: double.infinity,
                    ),
                    DropdownButton(
                      value: _departamenoSeleccionado,
                      items: _dropDownMenuItems,
                      onChanged: changedDropDownItem,
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                      child: Text(
                        'Asunto*:',
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(
                            fontWeight: FontWeight.w500,
                            fontSize: 16.0
                        ),
                      ),
                      width: double.infinity,
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 0.0),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4.0),
                          color: const Color.fromRGBO(255, 255, 255, 0.75)
                      ),
                      child: TextField(
                        decoration: InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(4.0)
                            ),
                            hintText: 'Requerido',
                            errorText: _showErrorMsg[0] ? _errorMsg : null
                        ),
                        controller: _asuntoController,
                        onChanged: (value) => setState(()=> _showErrorMsg[0] = false),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                      child: Text(
                        'Nombre*:',
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(
                            fontWeight: FontWeight.w500,
                            fontSize: 16.0
                        ),
                      ),
                      width: double.infinity,
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 0.0),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4.0),
                          color: const Color.fromRGBO(255, 255, 255, 0.75)
                      ),
                      child: TextField(
                        decoration: InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(4.0)
                            ),
                            hintText: 'Requerido',
                            errorText: _showErrorMsg[1] ? _errorMsg : null
                        ),
                        controller: _nombreController,
                        onChanged: (value) => setState(()=> _showErrorMsg[1] = false),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                      child: Text(
                        'Correo Electrónico*:',
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(
                            fontWeight: FontWeight.w500,
                            fontSize: 16.0
                        ),
                      ),
                      width: double.infinity,
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 0.0),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4.0),
                          color: const Color.fromRGBO(255, 255, 255, 0.75)
                      ),
                      child: TextField(
                        decoration: InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(4.0)
                            ),
                            hintText: 'Requerido',
                            errorText: _showErrorMsg[2] ? _errorMsg : null
                        ),
                        keyboardType: TextInputType.emailAddress,
                        controller: _correoController,
                        onChanged: (value) => setState(()=> _showErrorMsg[2] = false),
                        textCapitalization: TextCapitalization.none,
                        autocorrect: false,
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                      child: Text(
                        'Mensaje*:',
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(
                            fontWeight: FontWeight.w500,
                            fontSize: 16.0
                        ),
                      ),
                      width: double.infinity,
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 0.0),
                      decoration: BoxDecoration(
                          color: const Color.fromRGBO(255, 255, 255, 0.75),
                          borderRadius: BorderRadius.circular(4.0)
                      ),
                      child: TextField(
                        decoration: InputDecoration(
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(4.0),
                            ),
                            errorText: _showErrorMsg[3] ? _errorMsg2 : null
                        ),
                        maxLines: 15,
                        controller: _mensajeController,
                        onChanged: (value) => setState((){
                          if(value.length < 35) _showErrorMsg[3] = true;
                          else _showErrorMsg[3] = false;
                        }),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(16.0, 16.0, 8.0, 8.0),
                      child: Text(
                        '*Campos obligatorios. El mensaje debe tener mínimo 35 caracteres.',
                        textAlign: TextAlign.left,
                        style: GoogleFonts.roboto(
                            fontWeight: FontWeight.w300,
                            fontSize: 12.0
                        ),
                      ),
                      width: double.infinity,
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  void changedDropDownItem(String? departamentoSeleccionado) {
    setState(() {
      _departamenoSeleccionado = departamentoSeleccionado!;
    });
  }
}
