import 'dart:convert';

import 'package:awesome_card/awesome_card.dart' as myCreditcard;
import 'package:awesome_card/style/card_background.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:labulabu/labulabu/common_widget/BottomNavBarWidget.dart';
import 'package:labulabu/labulabu/models/user.dart';
import 'package:labulabu/labulabu/utils/Utils.dart';
import 'package:labulabu/signin/googleSigin.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:stripe_api/stripe_api.dart';
import 'package:credit_card_type_detector/credit_card_type_detector.dart';

class CreditCardControl extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return CreditCardControlState();
  }
}

class CreditCardControlState extends State<CreditCardControl> {
  String cardNumber = "";
  String cardHolderName = "";
  String cardmonth = "";
  String cardyear = "";
  String cvv = "";
  bool showBack = false;
  DateTime cfirmdatetime = DateTime.now();
  bool iscfirmdatetime = false;
  String paycfirm ="";
  FocusNode _focusNode;

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

    _focusNode = new FocusNode();
    _focusNode.addListener(() {
      setState(() {
        _focusNode.hasFocus ? showBack = true : showBack = false;
      });
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Icon(Icons.arrow_back, color: Colors.black),
            onPressed: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => BottomNavBarWidget(root: "",)),
            )
          ),
          title: Text(Utils.registCard),
        ),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  height: 40,
                ),
                myCreditcard.CreditCard(
                  cardNumber: cardNumber,
                  cardExpiry: cardmonth + "/" + cardyear,
                  cardHolderName: cardHolderName,
                  cvv: cvv,
                  showBackSide: showBack,
                  frontBackground: CardBackgrounds.black,
                  backBackground: CardBackgrounds.white,
                  showShadow: true,
                ),
                SizedBox(
                  height: 40,
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.symmetric(
                        horizontal: 20,
                      ),
                      child: TextFormField(
                        keyboardType: TextInputType.number,
                        inputFormatters: <TextInputFormatter>[
                          FilteringTextInputFormatter.digitsOnly
                        ],
                        decoration: InputDecoration(hintText: Utils.cardnumber),
                        maxLength: 16,
                        onChanged: (value) {
                          setState(() {
                            cardNumber = value;
                          });
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.symmetric(
                        horizontal: 20,
                      ),
                      child: TextFormField(
                        keyboardType: TextInputType.number,
                        inputFormatters: <TextInputFormatter>[
                          FilteringTextInputFormatter.digitsOnly
                        ],
                        decoration: InputDecoration(hintText: Utils.cardmonth),
                        maxLength: 2,
                        onChanged: (value) {
                          setState(() {
                            cardmonth = value;
                          });
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.symmetric(
                        horizontal: 20,
                      ),
                      child: TextFormField(
                        keyboardType: TextInputType.number,
                        inputFormatters: <TextInputFormatter>[
                          FilteringTextInputFormatter.digitsOnly
                        ],
                        decoration: InputDecoration(hintText: Utils.cardyear),
                        maxLength: 2,
                        onChanged: (value) {
                          setState(() {
                            cardyear = value;
                          });
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.symmetric(
                        horizontal: 20,
                      ),
                      child: TextFormField(
                        decoration:
                            InputDecoration(hintText: Utils.cardholder),
                        onChanged: (value) {
                          setState(() {
                            cardHolderName = value;
                          });
                        },
                      ),
                    ),
                    Container(
                      margin:
                          EdgeInsets.symmetric(horizontal: 20, vertical: 25),
                      child: TextFormField(
                        keyboardType: TextInputType.number,
                        inputFormatters: <TextInputFormatter>[
                          FilteringTextInputFormatter.digitsOnly
                        ],
                        decoration: InputDecoration(hintText: "CVV"),
                        maxLength: 3,
                        onChanged: (value) {
                          setState(() {
                            cvv = value;
                          });
                        },
                        focusNode: _focusNode,
                      ),
                    ),

                    TextButton(
                        onPressed: () {

                          DatePicker.showDateTimePicker(context, showTitleActions: true,
                              onChanged: (date) {
                                print('change $date in time zone ' +
                                    date.timeZoneOffset.inHours.toString());
                              }, onConfirm: (date) {
                                print('confirm $date');
                                final Duration difference = DateTime.now().difference(date);
                                setState(() {
                                  cfirmdatetime = date;
                                  iscfirmdatetime = true;
                                  paycfirm = ((difference.inDays.toInt()-1)*Utils.mount).toString().replaceAll('-', '')+Utils.currency;
                                });


                              },
                              minTime:  DateTime.now(),
                              locale:  Utils.localeType);
                        },
                        child: Text(
                          Utils.selectdatepaylabel,
                          style: TextStyle(color: Colors.blue),
                        )),
                    iscfirmdatetime==true?Text(Utils.todate+formatDate(cfirmdatetime,Utils.formatdate)):Text(""),
                    paycfirm!=""?Text(Utils.mountpay+paycfirm):Text(""),
                    Divider(),
                    RaisedButton(
                      child: Text(Utils.pay),
                      color: Colors.blue,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                      onPressed: () {

                        FocusScopeNode currentFocus = FocusScope.of(context);
                        if (!currentFocus.hasPrimaryFocus) {
                          currentFocus.unfocus();
                        }
                        buybyPaypal(context,paycfirm,Timestamp.fromDate(cfirmdatetime));
                      },
                    ),
                  ],
                )
              ],
            ),
          ),
        ));
  }

//  void saveCard(BuildContext context) async {
//    DateTime now = new DateTime.now();
//    if (cardmonth == "" ||
//        cardyear == "" ||
//        cardNumber == "" ||
//        cardHolderName == "" ||
//        cvv == ""||int.parse(cardyear)>=now.year) {
//      Fluttertoast.showToast(
//          msg: Utils.fillAllinfo,
//          toastLength: Toast.LENGTH_SHORT,
//          gravity: ToastGravity.CENTER,
//          timeInSecForIosWeb: 3,
//          backgroundColor: Colors.red,
//          textColor: Colors.white,
//          fontSize: 16.0);
//    } else {
//      CreditCardType type = detectCCType(cardNumber);
//      if(type== CreditCardType.unknown){
//        Fluttertoast.showToast(
//            msg: Utils.badcard,
//            toastLength: Toast.LENGTH_SHORT,
//            gravity: ToastGravity.CENTER,
//            timeInSecForIosWeb: 3,
//            backgroundColor: Colors.red,
//            textColor: Colors.white,
//            fontSize: 16.0);
//      }else{
//
//        Map<String, dynamic> frameworks = {
//          "cardNumber": cardNumber.replaceAll(new RegExp(r"\s+"), ""),
//          "expiryDate": cardmonth + "/" + cardyear,
//          "cardHolderName": cardHolderName,
//          "cvvCode": cvv,
//          "cardType": type.toString().split('.')[1]
//        };
//        if (widget.expressCard == true) {
//          Firestore.instance
//              .collection('labulabu_UserLib')
//              .document(currentUserModel.id)
//              .updateData({"creaditjson": frameworks});
//          Navigator.push(
//            context,
//            MaterialPageRoute(builder: (context) => BottomNavBarWidget()),
//          );
//        } else {
//          Navigator.pop(context, frameworks);
//        }
//      }
//    }
//  }
  void buybyPaypal(BuildContext context,String mount,Timestamp datetime) async {
    DateTime now = new DateTime.now();
    print(datetime);
    if (cardmonth == "" ||
        cardyear == "" ||
        cardNumber == "" ||
        cardHolderName == "" ||
        cvv == ""||int.parse(cardyear)>=now.year||mount =="") {
      Fluttertoast.showToast(
          msg: Utils.fillAllinfo,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 3,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
    } else {
      CreditCardType type = detectCCType(cardNumber);
      if(type== CreditCardType.unknown){
        Fluttertoast.showToast(
            msg: Utils.badcard,
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 3,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0);
      }else{

        Map<String, dynamic> frameworks = {
          "cardNumber": cardNumber.replaceAll(new RegExp(r"\s+"), ""),
          "expiryDate": cardmonth + "/" + cardyear,
          "cardHolderName": cardHolderName,
          "cvvCode": cvv,
          "cardType": type.toString().split('.')[1]
        };
        try {
          mount = mount.replaceAll("USD", "");
//    String url = "http://0.0.0.0/pay/labulabu";
          String url = "https://chonho-670ec.uc.r.appspot.com/pay/labulabu";

          var resp = await http.post(url,
              body: jsonEncode(
                  {"mail": currentUserModel.email, "price": mount,"credit":frameworks,"description":Utils.description,"currency":"usd"}));


          if (resp.statusCode == 202) {

            Firestore.instance
                .collection('labulabu_UserLib')
                .document(currentUserModel.id)
                .updateData({"timestamp": datetime}).then((value) async => {
            currentUserModel = User.fromDocument(await Firestore.instance.collection('labulabu_UserLib').document(currentUserModel.id).get())
            });
            Fluttertoast.showToast(
                msg: Utils.registOk,
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
                timeInSecForIosWeb: 3,
                backgroundColor: Colors.red,
                textColor: Colors.white,
                fontSize: 16.0
            );
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => BottomNavBarWidget()),
            );

          } else {
            Fluttertoast.showToast(
                msg: Utils.badcard,
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
                timeInSecForIosWeb: 3,
                backgroundColor: Colors.red,
                textColor: Colors.white,
                fontSize: 16.0
            );
            return;
          }
        } catch (e) {
          print(e);
          Fluttertoast.showToast(
              msg: Utils.unvalueCard,
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 3,
              backgroundColor: Colors.red,
              textColor: Colors.white,
              fontSize: 16.0
          );
        }

      }
    }
  }
}

class StripepaymentControl {
  String _error;

  void payStripe(
      String url, Map<String, dynamic> record, String Id, String price) async {
    var mycard = record["creaditjson"];
    var mail = record["email"];
    String number = mycard["cardNumber"];
    List<String> expiryDate = mycard["expiryDate"].split("/");
    int expmonth = int.parse(expiryDate[0]);
    int expYear = int.parse(expiryDate[1]);
    String cvc = mycard["cvvCode"];


    StripeCard card = new StripeCard(
        number: number, cvc: cvc, expMonth: expmonth, expYear: expYear);
    card.name = mycard["cardHolderName"];
    Stripe.instance.createCardToken(card).then((token) {

      postmyHttp(url, token.id, Id, price, mail);
    }).then((source) {
      print(source);
    }).catchError((error) {

      Fluttertoast.showToast(
          msg: Utils.unvalueCard,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 3,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);

      pageController.jumpToPage(5);
    });
  }

  void postmyHttp(
      String url, String id, String Id, String price, String mail) async {
    try {
      var resp = await http.post(url,
          body: jsonEncode(
              {"tokenid": id, "userid": Id, "price": price, "mail": mail}));

      if (resp.statusCode == 202) {
        Fluttertoast.showToast(
            msg: Utils.registOk,
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 3,
            backgroundColor: Colors.blue,
            textColor: Colors.white,
            fontSize: 16.0);

        pageController.jumpToPage(2);
      } else {
        Fluttertoast.showToast(
            msg: Utils.badcard,
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 3,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0);

        return;
      }
    } catch (e) {
      Fluttertoast.showToast(
          msg: Utils.unvalueCard,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 3,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);

      pageController.jumpToPage(0);
    }
  }

  void postdeleteHttp(
      String Id, String url, String coursename, String subid) async {
    try {
      var response = await http.post(url,
          body: jsonEncode({"course": coursename, "myid": Id, "subid": subid}));

      String msg = json.decode(response.body);
      Fluttertoast.showToast(
          msg: msg,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 3,
          backgroundColor: Colors.blue,
          textColor: Colors.white,
          fontSize: 16.0);

      pageController.jumpToPage(0);
    } catch (e) {
      print(e);
    }
  }
}
 write test case flutter