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

class FormCreditCard extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return FormCreditCardState();
  }
}

class FormCreditCardState extends State<FormCreditCard> {
  String cardNumber = '';
  String expiryDate = '';
  String cardHolderName = '';
  String cvvCode = '';
  bool isCvvFocused = false;
  bool loading = false;
  bool sucess = false;
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  @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);
          },
        ),
      ),
      resizeToAvoidBottomInset: true,
      body: SafeArea(
        child: Column(
          children: <Widget>[
            CreditCardWidget(
              cardBgColor: Colors.black,
              cardNumber: cardNumber,
              expiryDate: expiryDate,
              cardHolderName: cardHolderName,
              cvvCode: cvvCode,
              showBackView: isCvvFocused,

              obscureCardNumber: true,
              obscureCardCvv: true,
            ),
            Expanded(
              child: SingleChildScrollView(
                /*
                child: Column(
                  children: [

                    CreditCardForm(

                      formKey: formKey,
                      onCreditCardModelChange: onCreditCardModelChange,
                      obscureCvv: true,
                      obscureNumber: true,
                      cardNumberDecoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Número',
                        hintText: 'XXXX XXXX XXXX XXXX',
                      ),
                      expiryDateDecoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Vencimento',
                        hintText: 'XX/XX',

                      ),
                      cvvCodeDecoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'DV',
                        hintText: 'XXX',
                      ),
                      cardHolderDecoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Nome',
                      ),
                    ),
                    SizedBox(height: 20,),
                    RaisedButton(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                      child: Container(
                        margin: const EdgeInsets.all(8),
                        child: const Text(
                          'Validar',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                          ),
                        ),
                      ),
                     // color: COLOR_PRIMARY,
                      onPressed: () {
                        if (formKey.currentState.validate()) {
                          print('valid!');

                        } else {
                          print('invalid!');
                        }
                      },
                    ),
                    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 (formKey.currentState.validate()) {
      setState(() {
        loading = true;
        sucess = false;
      });
      formKey.currentState.save();

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

      var m = null;

      CreditCardService service = new CreditCardService();

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

        ModelCreditCard card = new ModelCreditCard(

            display_number: cardNumber,
            holder_name: cardHolderName,
            month: int.parse(expiryDate.split("/")[0]),
            year: int.parse(expiryDate.split("/")[1]),
        cvv: int.parse(cvvCode) );

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

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



  void onCreditCardModelChange(CreditCardModel creditCardModel) {
    setState(() {
      cardNumber = creditCardModel.cardNumber;
      expiryDate = creditCardModel.expiryDate;
      cardHolderName = creditCardModel.cardHolderName;
      cvvCode = creditCardModel.cvvCode;
      isCvvFocused = creditCardModel.isCvvFocused;
    });
  }
}