import 'package:flutter/material.dart';
import 'package:flutter_credit_card/flutter_credit_card.dart';
import 'package:jubo/control/accountService.dart';
import 'package:jubo/control/creditCardService.dart';
import 'package:jubo/model/modelAccount.dart';
import 'package:jubo/util/params.dart';
import '../util/helper.dart';
import 'package:jubo/ui/sucess.dart';
import 'package:jubo/ui/loading.dart';

class FormAccount extends StatefulWidget {
  const FormAccount({this.person_id});

  final int person_id;
  @override
  State<StatefulWidget> createState() {
    return FormAccountState();
  }
}

class FormAccountState extends State<FormAccount> {
  String cardNumber = '';
  String description = '';
  String expiryDate = '';
  String cardHolderName = '';
  String cvvCode = '';
  bool loading = false;
  bool sucess = false;
  GlobalKey<FormState> _key = new GlobalKey();
  AutovalidateMode _validate = AutovalidateMode.disabled;

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : sucess
            ? Sucess()
            : Scaffold(
                backgroundColor: Colors.white54,
                appBar: AppBar(
                  elevation: 5.0,
                  backgroundColor: COLOR_PRIMARY,
                  title: Text("Cartão"),
                  leading: TextButton(
                    child: Icon(
                      Icons.arrow_back,
                      size: 30.0,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      Navigator.pop(context, false);
                    },
                  ),
                ),
                resizeToAvoidBottomInset: true,
                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(),
                    ),
                  ),
                ),
              );
  }

  Widget formUI() {
    return new Column(
      children: <Widget>[
        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,
                    onSaved: (String val) {
                      this.description = val;
                    },
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        labelText: 'Descrição',
                        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,
                    onSaved: (String val) {
                      this.cardNumber = val;
                    },
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        labelText: 'Número',
                        hintText: 'XXXX XXXX XXXX XXXX',
                        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,
                    onSaved: (String val) {
                      this.expiryDate = val;
                    },
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        labelText: 'Vencimento',
                        hintText: 'XX/XXXX',
                        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,
                    onSaved: (String val) {
                      this.cardHolderName = val;
                    },
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        labelText: 'Nome',
                        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,
                    onSaved: (String val) {
                      this.cvvCode = val;
                    },
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(
                            vertical: 8, horizontal: 16),
                        fillColor: Colors.white,
                        labelText: 'CVV',
                        hintText: 'XXX',
                        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);
              },
              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;

      AccountService service = new AccountService();

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

        ModelAccount card = new ModelAccount(
            name: cardNumber,
            /*holder_name: cardHolderName,
            month: int.parse(expiryDate.split("/")[0]),
            year: int.parse(expiryDate.split("/")[1]),
            cvv: int.parse(cvvCode),
            id_person: widget.person_id,
            description: description*/);

        await service.postAccount(card);
        setState(() {
          loading = false;
          sucess = true;
        });
        await new Future.delayed(const Duration(milliseconds: 500));
        setState(() {
          loading = false;
          sucess = false;
        });

        Navigator.pop(context);
      } catch (Exception) {
        setState(() => loading = false);
        showAlertDialog(context, 'JuBo', "Problemas ao criar cartão!");
      }
    }
  }
}
