

import 'package:flutter/material.dart';

import '../../constants.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/stripe_payment_method.dart';
import '../../models/user.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/utils.dart';
import '../../widgets/general/bottom_nav.dart';
import '../../widgets/general/breadcrumbs.dart';
import '../../widgets/general/navigationbar.dart';

class DesktopMyCards extends StatefulWidget {
  final Key key;
  const DesktopMyCards({this.key});

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

}

class MyCardsState extends State<DesktopMyCards> {
  User _user;

  bool isSubmitting;

  double sideSpace = 0;
  double mainSpace = 1200;

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    if (MediaQuery.of(context).size.width <= 1200) {
      mainSpace = MediaQuery.of(context).size.width;
      sideSpace = 0;
    } else {
      mainSpace = 1200;
      sideSpace = (MediaQuery.of(context).size.width - 1200) / 2;
    }

    return Scaffold(
      appBar: MiniNavigationBar(
        title: S.of(context).blog,
        back: true,
        breadCrumbs: [
          BreadCrumb(S.of(context).my_cards, null),
        ],
        breadCrumbHeight: Constants.BREADCRUMB_HEIGHT,
      ),
      body: Row(
        children: [
          Container(
            width: sideSpace,
          ),
          Expanded(
            child: ListView.builder(
                itemCount: _user.stripePaymentMethods.length,
                itemBuilder: (BuildContext context, int position) {
                  StripePaymentMethod paymentMethod = _user.stripePaymentMethods[position];
                  return cardWidget(paymentMethod);
                }
            ),
          ),
          Container(
            width: sideSpace,
          ),
        ],
      ),
      bottomNavigationBar: BottomNav(),
    );
  }

  Widget cardWidget(StripePaymentMethod paymentMethod) {
    return Container(
      padding: EdgeInsets.only(
          top: 16.0, left: 16.0, right: 16.0, bottom: 16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          paymentMethod.cardBrand == 'visa' ?
          Image.asset(
            'assets/images/visa.png',
            width: 50.0,
            height: 50.0,
            fit: BoxFit.fill,
          ) : (paymentMethod.cardBrand == 'mastercard' ?
          Image.asset(
            'assets/images/master.png',
            width: 50.0,
            height: 50.0,
            fit: BoxFit.fill,
          ) : Icon(
            Icons.credit_card, size: 50.0, color: Colors.black38,)),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(left: 20.0, right: 10.0),
                  child: Text(
                    '**** ${paymentMethod.cardLast4}',
                    style: TextStyle(
                      fontSize: 20.0,
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 20.0, right: 10.0),
                  child: Text(
                    S.of(context).expire_token(paymentMethod.cardExpMonth, paymentMethod.cardExpYear),
                    style: TextStyle(
                      fontSize: 14.0,
                      color: Colors.black26,
                    ),
                  ),
                ),
              ],
            ),
          ),
          IconButton(
            icon: Icon(Icons.clear, color: Colors.black26,),
            onPressed: () {
              showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text(S.of(context).warning),
                    content: Text(
                      S.of(context).are_you_sure_to_remove_the_card,
                    ),
                    actions: <Widget>[
                      FlatButton(
                        child: Text(S.of(context).cancel),
                        color: Theme.of(context).primaryColor,
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                      FlatButton(
                        child: Text(S.of(context).yes_i_am_sure),
                        onPressed: () {
                          Navigator.of(context).pop();
                          _removeCard(paymentMethod);
                        },
                      )
                    ],
                  );
                }
              );
            },
          ),
        ],
      ),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            width: 0.5,
            color: Colors.black12,
          ),
        ),
      ),
    );
  }

  _removeCard(StripePaymentMethod paymentMethod) {
    HttpUtil.httpDelete('v1/stripe-card/${paymentMethod.id}', (response) {
      _user = User.fromJson(response.data);
      store.dispatch(UpdateCurrentUser(_user));
      eventBus.fire(OnCurrentUserUpdated());
      if (mounted) {
        Navigator.of(context).pop();
        setState(() {
          isSubmitting = false;
        });
      }
    }).catchError((error) {
      if (isSubmitting) {
        Navigator.of(context).pop();
        isSubmitting = false;
      }
      Utils.showMessageDialog(context, error, onOk: () {
        Navigator.of(context).pop();
        Navigator.of(context).pop();
      });
    });
    isSubmitting = true;
    Utils.showSubmitDialog(context);
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      isSubmitting = false;
      _user = store.state.user;
    });
  }
}