

import 'package:badges/badges.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/business.dart';
import '../../models/cart_info.dart';
import '../../models/product.dart';
import '../../pages/attribute_selection.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/utils.dart';

class AddRemoveButton extends StatefulWidget {
  final Product product;
  final Business business;
  final bool addOnly;
  final int cartLineItemIndex;
  final bool addToBasket;
  final bool onHovor;

  AddRemoveButton({
    this.product,
    this.business,
    this.addOnly = false,
    this.cartLineItemIndex = -1,
    this.addToBasket = false,
    this.onHovor = false,
  });

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

class AddRemoveButtonState extends State<AddRemoveButton> {
  int _qty;
  var zeroColor = const Color(0xFFEFEFEF);
  var qtyColor = const Color(0xFFFF6666);
  var zeroFontColor = const Color(0xFF888888);
  var qtyFontColor = const Color(0xFFFFFFFF);

  var d = 1;

  CartInfo cartInfo;

  GlobalKey startKey = GlobalKey();

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

  @override
  Widget build(BuildContext context) {
    if (widget.product.leftNum == null) {
      _qty = 0;
      cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, widget.business);
      if (cartInfo != null) {
        for (var i = 0; i < cartInfo.productList.length; i++) {
          if (cartInfo.productList[i].product.id == widget.product.id
              && cartInfo.productList[i].unitPrice == 0.0) {
            _qty = cartInfo.productList[i].quantity.round();
            break;
          }
        }
      }
      return Container(
        padding: EdgeInsets.only(top: 5.0, bottom: 5.0, left: 32.0, right: 32.0),
        child: Text(
            'x$_qty'
        ),
      );
    }
    if (widget.product.leftNum <= 0) {
      return Container(
        padding: EdgeInsets.only(top: 0.0, bottom: 10.0, left: 8.0, right: 8.0),
        child: Text(
          S.of(context).out_of_stock,
          style: TextStyle(
            fontSize: 8.0,
            color: Colors.white,
          ),
        ),
        decoration: BoxDecoration(
          color: Colors.red,
          shape: BoxShape.rectangle,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(3.0),
            topRight: Radius.circular(3.0),
            bottomLeft: Radius.circular(3.0),
            bottomRight: Radius.circular(3.0),
          ),
        ),
      );
    }
    if (widget.addToBasket) {
      _qty = 0;
      cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, widget.business);
      if (cartInfo != null) {
        for (var i = 0; i < cartInfo.productList.length; i++) {
          if (cartInfo.productList[i].product.id == widget.product.id) {
            _qty = cartInfo.productList[i].quantity.round();
            break;
          }
        }
      }
      if (_qty > 0) {
        return Badge(
          badgeContent: Text(
            '$_qty',
            style: TextStyle(
              color: Colors.white,
              fontSize: 17.0,
            ),
          ),
          padding: EdgeInsets.all(10),
          position: BadgePosition.topEnd(top: -15, end: -10),
          badgeColor: Colors.lightBlueAccent,
          child: ElevatedButton.icon(
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.redAccent,
              onPrimary: Colors.white,
              padding: EdgeInsets.only(left: 32, right: 32, top: 20, bottom: 20),
              elevation: 2.0,
              shape: new RoundedRectangleBorder(
                borderRadius: new BorderRadius.circular(10.0),
              ),
            ),
            icon: Icon(
              Icons.shopping_basket_outlined,
              size: 32.0,
              color: Colors.yellow,
            ),
            label: Text(
              S.of(context).add_to_basket,
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            onPressed: () {
              _addToCart(context);
            },
          ),
        );
      } else {
        return ElevatedButton.icon(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.redAccent,
            padding: EdgeInsets.only(left: 32, right: 32, top: 20, bottom: 20),
            elevation: 2.0,
            shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(10.0),
            ),
          ),
          icon: Icon(
            Icons.shopping_basket_outlined,
            size: 32.0,
            color: Colors.yellow,
          ),
          label: Text(
            S.of(context).add_to_basket,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          onPressed: () {
            _addToCart(context);
          },
        );
      }
    } else if (widget.addOnly) {
      return Container(
        key: startKey,
        padding: EdgeInsets.all(0.0),
        child: GestureDetector(
          child: Icon(
            Icons.add_circle,
            size: 24.0,
          ),
          onTap: () {
            _addToCart(context);
          },
        ),
      );
    } else {
      _qty = 0;
      cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, widget.business);
      if (cartInfo != null) {
        for (var i = 0; i < cartInfo.productList.length; i++) {
          if (cartInfo.productList[i].product.id == widget.product.id) {
            _qty = cartInfo.productList[i].quantity.round();
            break;
          }
        }
      }
      if (widget.product.productAttributes != null &&
          widget.product.productAttributes.length > 0 && widget.cartLineItemIndex == -1) {
        return new Row(
          key: startKey,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            new GestureDetector(
              child: new Container(
                width: 60.0,
                child: new Center(
                  child: new Text(
                    '$_qty',
                    style: new TextStyle(
                        fontSize: 13.0,
                        fontWeight: FontWeight.bold,
                        color: _qty > 0 ? qtyFontColor : zeroFontColor
                    ),
                  ),
                ),
                padding: EdgeInsets.all(5.0).copyWith(left: 10.0, right: 10.0),
                decoration: BoxDecoration(
                  color: _qty > 0 ? qtyColor : zeroColor,
                  shape: BoxShape.rectangle,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(10.0),
                    topRight: Radius.circular(10.0),
                    bottomLeft: Radius.circular(10.0),
                    bottomRight: Radius.circular(10.0),
                  ),
                ),
              ),
              onTap: () {
                _addToCart(context);
              },
            ),
          ],
        );
      } else {
        if (!widget.onHovor && _qty == 0) {
          return SizedBox.shrink();
        }
        return new Row(
          key: startKey,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            new GestureDetector(
              child: new Container(
                width: 30.0,
                child: new Center(
                  child: new Text(
                    '$_qty',
                    style: new TextStyle(
                        fontSize: 13.0,
                        fontWeight: FontWeight.bold,
                        color: _qty > 0 ? qtyFontColor : zeroFontColor
                    ),
                  ),
                ),
                padding: EdgeInsets.all(5.0).copyWith(left: 10.0, right: 10.0),
                decoration: BoxDecoration(
                  color: _qty > 0 ? qtyColor : zeroColor,
                  shape: BoxShape.rectangle,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(10.0),
                    bottomLeft: Radius.circular(10.0),
                  ),
                ),
              ),
              onTap: () {
                _addToCart(context);
              },
            ),
            new GestureDetector(
              child: new Container(
                width: 30.0,
                child: new Center(
                  child: new Text(
                    '-',
                    style: new TextStyle(
                      fontSize: 13.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                padding: EdgeInsets.all(5.0).copyWith(left: 10.0, right: 10.0),
                decoration: BoxDecoration(
                  color: const Color(0xFFABABAB),
                  shape: BoxShape.rectangle,
                  borderRadius: BorderRadius.only(
                    topRight: Radius.circular(10.0),
                    bottomRight: Radius.circular(10.0),
                  ),
                ),
              ),
              onTap: () {
                if (_qty > 0) {
                  _removeFromCart(context);
                }
              },
            ),
          ],
        );
      }
    }
  }

  void _addToCart(BuildContext context) {
    if (widget.cartLineItemIndex != -1) {
      if (cartInfo.productList[widget.cartLineItemIndex].quantity + 1.0 > widget.product.leftNum) {
        Fluttertoast.showToast(
            msg: S.of(context).product_insufficient,
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            backgroundColor: Colors.red,
            textColor: Colors.white
        );
      } else {
        cartInfo.productList[widget.cartLineItemIndex].quantity += 1.0;
        Utils.addSubproductQty(cartInfo, cartInfo.productList[widget.cartLineItemIndex]);
        store.dispatch(UpdateCartInfo(
            Utils.addCartInfoToCartInfoList(store.state.cartInfos, cartInfo)));
        eventBus.fire(new OnCartInfoUpdated());
      }
    } else {
      if (widget.product.productAttributes.length > 0) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) =>
          new AttributeSelection(
            product: widget.product, business: widget.business, startKey: startKey,)),
        );
      } else {
        eventBus.fire(new OnProductWillAddToCart(widget.product, {},
            widget.product.price, widget.product.description,
            widget.business, buttonKey: startKey));
      }
    }
  }

  void _removeFromCart(BuildContext context) {
    if (widget.cartLineItemIndex != -1) {
      if (cartInfo.productList[widget.cartLineItemIndex].quantity <= 1) {
        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_item),
                actions: <Widget>[
                  TextButton(
                    child: Text(S.of(context).cancel),
                    onPressed: () {
                      Navigator.of(context).maybePop();
                    },
                  ),
                  TextButton(
                    child: Text(S.of(context).yes_i_am_sure),
                    onPressed: () {
                      _removeCartLineItem();
                      Navigator.of(context).maybePop();
                    },
                  ),
                ],
              );
            }
        );
      } else {
        _removeCartLineItem();
      }
    } else {
      eventBus.fire(new OnProductWillRemoveFromCart(
          widget.product, -1, widget.business));
    }
  }

  void _removeCartLineItem() {
    if (cartInfo.productList[widget.cartLineItemIndex].quantity <= 1) {
      String uuid = cartInfo.productList[widget.cartLineItemIndex].uuid;
      cartInfo.productList.removeAt(widget.cartLineItemIndex);
      Utils.removeSubproduct(cartInfo, uuid);
    } else {
      cartInfo.productList[widget.cartLineItemIndex].quantity -= 1;
      Utils.addSubproductQty(cartInfo, cartInfo.productList[widget.cartLineItemIndex], remove: true);
    }
    if (cartInfo.productList.length <= 0) {
      store.dispatch(new UpdateCartInfo(Utils.removeCartInfoFromCartInfoList(store.state.cartInfos, cartInfo)));
    } else {
      store.dispatch(new UpdateCartInfo(Utils.addCartInfoToCartInfoList(store.state.cartInfos, cartInfo)));
    }
    eventBus.fire(new OnCartInfoUpdated());
  }

  @override
  void setState(VoidCallback fn) {
    if(mounted) {
      super.setState(fn);
    }
  }
}