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/orderService.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 FormOrder extends StatefulWidget {
  const FormOrder(
      {this.id_person_customer,
      this.id_event,
      this.id_person_artist,
      this.id_event_artist,
      this.artist_name,
      this.music_name,
      this.value,
      this.note,
      this.idOrder,
      this.status});
  final int id_person_customer;
  final int id_event;
  final int id_person_artist;
  final int id_event_artist;
  final String artist_name;
  final String music_name;
  final double value;
  final String note;
  final int idOrder;
  final String status;

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

class _FormOrderState extends State<FormOrder> {
  TextEditingController _passwordController = new TextEditingController();
  GlobalKey<FormState> _key = new GlobalKey();
  AutovalidateMode _validate = AutovalidateMode.disabled;
  String artist_name, music_name, note, status;
  double value = 05.00;
  bool loading = false;
  bool sucess = false;
  int idOrder, id_person_customer, id_event, id_person_artist, id_event_artist;

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

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

    await Future.delayed(Duration(seconds: 1));
    setState(() {
      try {
        artist_name = widget.artist_name;
        music_name = widget.music_name;
        value = widget.value;
        note = widget.note;
        idOrder = widget.idOrder;
        id_person_customer = widget.id_person_customer;
        id_event = widget.id_event;
        id_person_artist = widget.id_person_artist;
        id_event_artist = widget.id_event_artist;
        status = widget.status;
      } catch (e) {
        idOrder = null;
        artist_name = "";
        music_name = "";
        value = 05.00;
        note = "";
        id_person_customer = widget.id_person_customer;
        id_event = widget.id_event;
        id_person_artist = widget.id_person_artist;
        id_event_artist = widget.id_event_artist;
        status = widget.status;
      }

      if (value == 5.00) {
        _selectedValueOrder[0] = true;
      } else if (value == 10.00) {
        _selectedValueOrder[1] = true;
      } else if (value == 20.00) {
        _selectedValueOrder[2] = true;
      } else if (value == 50.00) {
        _selectedValueOrder[3] = true;
      }

      loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : sucess
            ? Sucess()
            : Scaffold(
                appBar: AppBar(
                  elevation: 5.0,
                  backgroundColor: COLOR_PRIMARY,
                  title: Text("Pedido"),
                  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(
                    initialValue: this.artist_name,
                    validator: validateText,
                    onSaved: (String val) {
                      this.artist_name = val;
                    },
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        hintText: 'Artista',
                        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(
                    initialValue: music_name,
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    validator: validateText,
                    onSaved: (String val) {
                      music_name = val;
                    },
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        hintText: 'Música',
                        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(
                    validator: validateText,
                    initialValue: NumberFormat.currency(
                            locale: 'pt_BR',
                            decimalDigits: 2,
                            customPattern: '#,###.#')
                        .format(loading ? 0.00 : value),
                    keyboardType: TextInputType.number,
                    onSaved: (String val) {
                      try {
                        val = val.replaceAll(",", ".");
                      } catch (e) {}
                      value = double.tryParse(val) + 0.00;
                    },
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        hintText: 'Valor',
                        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: ToggleButtons(
                  children: [
                    Container(
                        alignment: Alignment.center,
                        width: (MediaQuery.of(context).size.width - 54) / 4,
                        child: Text(
                          "R\$ 05",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        )),
                    Container(
                        alignment: Alignment.center,
                        width: (MediaQuery.of(context).size.width - 54) / 4,
                        child: Text(
                          "R\$ 10",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        )),
                    Container(
                        alignment: Alignment.center,
                        width: (MediaQuery.of(context).size.width - 54) / 4,
                        child: Text(
                          "R\$ 20",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        )),
                    Container(
                        alignment: Alignment.center,
                        width: (MediaQuery.of(context).size.width - 54) / 4,
                        child: Text(
                          "R\$ 50",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        )),
                  ],
                  onPressed: (int index) {
                    setState(() {
                      for (int buttonIndex = 0;
                          buttonIndex < _selectedValueOrder.length;
                          buttonIndex++) {
                        if (buttonIndex == index) {
                          _selectedValueOrder[buttonIndex] = true;
                        } else {
                          _selectedValueOrder[buttonIndex] = false;
                        }
                      }
                      value = index == 0
                          ? 5.00
                          : index == 1
                              ? 10.00
                              : index == 2
                                  ? 20.00
                                  : index == 3
                                      ? 50.00
                                      : 0.00;
                    });
                  },
                  color: COLOR_FONT_2,
                  selectedColor: COLOR_FONT_2,
                  borderColor: COLOR_FONT_2,
                  selectedBorderColor: COLOR_PRIMARY,
                  fillColor: COLOR_PRIMARY,
                  isSelected: _selectedValueOrder,
                ))),
        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,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  _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;

      OrderService service = new OrderService();

      try {
        //updateProgress('Validando...');

        ModelOrder order = new ModelOrder(
            id: idOrder,
            person_customer_id: id_person_customer,
            id_event: id_event,
            id_person_artist: id_person_artist,
            id_event_artist: id_event_artist,
            text_artist: artist_name,
            text_music: music_name,
            note: note,
            value: value,
            status: status);

        await service.postOrder(order);
        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) {
        setState(() => loading = false);
        //hideProgress();
        showAlertDialog(context, 'JuBo', "Problemas ao criar Pedido!");
      }
    } 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"),
          );
        });
  }
}
