import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:jubo/control/eventService.dart';
import 'package:jubo/control/orderService.dart';
import 'package:jubo/model/modelEvent.dart';
import 'package:jubo/model/modelOrder.dart';
import 'package:jubo/ui/loading.dart';
import 'package:jubo/ui/sucess.dart';
import '../util/params.dart';
import '../util/helper.dart';

class FormEvent extends StatefulWidget {
  const FormEvent({this.id_person_spot});
  final int id_person_spot;

  @override
  State createState() => _FormEventState();
}

class _FormEventState extends State<FormEvent> {
  TextEditingController _passwordController = new TextEditingController();
  GlobalKey<FormState> _key = new GlobalKey();
  AutovalidateMode _validate = AutovalidateMode.disabled;
  String note, date_event;
  bool loading = false;
  bool sucess = false;

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

  void loadData() async {
    setState(() => loading = true);

    await Future.delayed(Duration(seconds: 1));
    setState(() {
      try {
        note = "";
      } catch (e) {
        note = "";
      }
      loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : sucess
            ? Sucess()
            : Scaffold(
                appBar: AppBar(
                  elevation: 5.0,
                  backgroundColor: COLOR_PRIMARY,
                  title: Text("Evento"),
                  leading: TextButton(
                    child: Icon(
                      Icons.arrow_back,
                      size: 30.0,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      Navigator.pop(context, false);
                    },
                  ),
                ),
                body: SingleChildScrollView(
                  child: new Container(
                    margin:
                        new EdgeInsets.only(left: 16.0, right: 16, bottom: 16),
                    child: new Form(
                      key: _key,
                      autovalidateMode: _validate,
                      child: formUI(),
                    ),
                  ),
                ),
              );
  }

  List<bool> _selectedValueOrder = List.generate(4, (_) => false);

  Widget formUI() {
    return new Column(
      children: <Widget>[
        SizedBox(
          height: 20,
        ),
        ConstrainedBox(
            constraints: BoxConstraints(minWidth: double.infinity),
            child: Padding(
                padding:
                    const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
                child: TextFormField(
                    validator: validateDate,
                    /*onSaved: (String val) {
                      date_event = val;
                    },*/
                    controller: dateController,
                    onTap: () {
                      _selectDate();
                      FocusScope.of(context).requestFocus(new FocusNode());
                    },
                    readOnly: true,
                    keyboardType: TextInputType.datetime,
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        hintText: 'Data do Evento',
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0),
                            borderSide:
                                BorderSide(color: COLOR_PRIMARY, width: 2.0)),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ))))),
        ConstrainedBox(
            constraints: BoxConstraints(minWidth: double.infinity),
            child: Padding(
                padding:
                    const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
                child: TextFormField(
                    maxLength: 50,
                    keyboardType: TextInputType.multiline,
                    minLines: 1,
                    maxLines: 5,
                    initialValue: note,
                    textInputAction: TextInputAction.newline,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    //validator: validateName,
                    onSaved: (String val) {
                      note = val;
                    },
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        hintText: 'Observação',
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0),
                            borderSide:
                                BorderSide(color: COLOR_PRIMARY, width: 2.0)),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ))))),
        Padding(
          padding: const EdgeInsets.only(right: 8.0, left: 8.0, top: 40.0),
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: double.infinity),
            child: ElevatedButton(
              onPressed: _sendToServer,
              style: ElevatedButton.styleFrom(
                primary: COLOR_PRIMARY,
                padding: EdgeInsets.only(top: 15, bottom: 15),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    side: BorderSide(color: COLOR_PRIMARY)),
              ),
              child: Text(
                'Salvar',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(right: 8.0, left: 8.0, top: 10.0),
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: double.infinity),
            child: ElevatedButton(
              onPressed: () {
                Navigator.pop(context, false);
              },
              style: ElevatedButton.styleFrom(
                primary: Color(0xFF822A41),
                padding: EdgeInsets.only(top: 15, bottom: 15),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    side: BorderSide(color: Color(0xFF822A41))),
              ),
              child: Text(
                'Cancelar',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  TextEditingController dateController = TextEditingController();
  Future _selectDate() async {
    DateTime picked = await showDatePicker(
        context: context,
        locale: Locale("pt", "BR"),
        initialDate: DateTime.now(),
        firstDate: new DateTime(1900),
        lastDate: new DateTime(2030));
    if (picked != null)
      setState(() => {
            date_event = DateFormat('yyyy-MM-dd').format(picked),
            dateController.text = DateFormat('dd/MM/yyyy').format(picked)
          });
  }

  _sendToServer() async {
    if (_key.currentState.validate()) {
      setState(() {
        loading = true;
        sucess = false;
      });
      _key.currentState.save();

      await new Future.delayed(const Duration(seconds: 1));

      var m = null;

      EventService service = new EventService();

      try {
        //updateProgress('Validando...');
        //print(date_event);
       // print(widget.id_person_spot);
        ModelEvent event = new ModelEvent(
          date_event: date_event,
          note: note,
          person_spot_id: widget.id_person_spot,
          person_spot_name: ""

        );
        await service.postEvent(event);
        setState(() {
          loading = false;
          sucess = true;
        });
        await new Future.delayed(const Duration(milliseconds: 1600));
        setState(() {
          loading = false;
          sucess = false;
        });
        //showAlertDialog(context, 'JuBo', "Cadastro Efetuado!");

        Navigator.pop(context, true);
      } catch (Exception) {
        print(Exception);
        setState(() => loading = false);
        //hideProgress();
        showAlertDialog(context, 'JuBo', "Problemas ao criar Evento!");
      }
    } else {
      setState(() {
        _validate = AutovalidateMode.onUserInteraction;
      });
    }
  }

  void clickAlert(context) {
    showDialog(
        context: context,
        builder: (contextGlobal) {
          return AlertDialog(
            title: new Text("Erro"),
            content: new Text("Preencha os Campos"),
          );
        });
  }
}
