import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/models/shared-filter.dart';
import 'package:echo_app/screens/offers/widget/take_promotion.dart';
import 'package:echo_app/services/items.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:rflutter_alert/rflutter_alert.dart';

// ignore: must_be_immutable
class OfferDetailsCardFixed extends StatefulWidget {
  var offer;
  List promotionInputs = [];
  List promotionOutputs = [];

  OfferDetailsCardFixed(this.offer) {
    promotionInputs = this.offer['promotionInputs'];
    promotionOutputs = this.offer['promotionOutputs'];
  }

  @override
  _OfferDetailsCardFixedState createState() => _OfferDetailsCardFixedState();
}

class _OfferDetailsCardFixedState extends State<OfferDetailsCardFixed> {
  ItemService _itemsService = new ItemService();
  GeneralFilter filter = new GeneralFilter();
  onOfferCountChange(int promotionOptionId, String qty) {
    setState(() {
      int index = widget.promotionInputs.indexWhere(
          (element) => element['promotionOptionId'] == promotionOptionId);
      // ignore: unnecessary_null_comparison
      if (qty == null || qty == '') {
        qty = '0';
      }
     int count = int.parse(qty);

      if (!widget.promotionInputs[index].containsKey('takeQty')) {
        widget.promotionInputs[index]['takeQty'] = 0;
      }
      if (widget.promotionInputs[index]['takeQty'] == 0 && count == -1) {
        return;
      }
      if (count == 1) {
        widget.promotionInputs[index]['takeQty'] += 1;
      } else if (count == -1) {
        widget.promotionInputs[index]['takeQty'] -= 1;
      } else {
        widget.promotionInputs[index]['takeQty'] = count;
      }
    });
  }

  onTakeOffer(int promotionOptionId) async {
    if (CoreSession.currentBasket != null &&
        CoreSession.currentBasket.containsKey('items') &&
        CoreSession.currentBasket['items'].length > 0) {
      Alert(
        useRootNavigator: true,
        context: context,
        type: AlertType.info,
        title: "confirm".tr,
        desc: "clear-cart-confirm".tr,
        buttons: [
          DialogButton(
            color: Colors.white,
            child: Text(
              "yes".tr,
              style: TextStyle(color: Colors.green, fontSize: 20),
            ),
            onPressed: () => {
              Navigator.of(context, rootNavigator: true).pop(),
              CoreSession.currentBasket['items'] = [],
              ItemService.items
                  .where((element) => element['requiredQty'] > 0)
                  .forEach(
                    (i) => {
                      i['requiredQty'] = 0,
                    },
                  ),
              takeOfferAfterConfirmation(promotionOptionId),
            },
            width: 120,
          ),
          DialogButton(
            color: Colors.white,
            child: Text(
              "no".tr,
              style: TextStyle(color: Colors.red, fontSize: 20),
            ),
            onPressed: () => {
              Navigator.of(context, rootNavigator: true).pop(),
              // takeOfferAfterConfirmation(promotionOptionId),
            },
            width: 120,
          )
        ],
      ).show();
    } else {
      takeOfferAfterConfirmation(promotionOptionId);
    }
  }

  takeOfferAfterConfirmation(int promotionOptionId) async {
    var items = [];
    var takeQty = 0;
    int index = widget.promotionInputs.indexWhere(
        (element) => element['promotionOptionId'] == promotionOptionId);
    if (index != -1) {
      var selectedInput = widget.promotionInputs[index];
      takeQty = selectedInput['takeQty'];
      if (selectedInput.containsKey('takeQty') &&
          selectedInput['takeQty'] != 0) {
        for (var option in widget.promotionInputs[index]
            ['promotionOptionDetails']) {
          this.filter.packId = option['packId'];
          EasyLoading.show(status: 'loading'.tr);
          var respose = await this._itemsService.getItems(this.filter);

          if (respose['status'] == GlobalErrors.Success.index) {
            if (respose['data'] != null) {
              items = respose['data']['items'];
              if (items.length > 0) {
                var pack = items[0];
                var reqQty = takeQty * option['value'];
                pack['requiredQty'] = reqQty;

                this.addItemToCart(pack);
              }
            }
          }
        }
        EasyLoading.dismiss();
        widget.promotionInputs[index]['takeQty'] = 0;
      }
    }
  }

  addItemToCart(pack) {
    setState(() {
      var requiredQty = pack['requiredQty'] == '' ? 0 : pack['requiredQty'];
      var price = pack['price'];
      var tax = pack['tax'];
      var packId = pack['packId'];
      var addedPacks = [];

      var gross = price * requiredQty;
      pack['netAmount'] = gross + (gross * tax / 100);
      pack['netAmountString'] =
          pack['netAmount'].toStringAsFixed(CoreSession.numberOfDigits);

      if (CoreSession.currentBasket != null &&
          CoreSession.currentBasket.containsKey('items')) {
        addedPacks = CoreSession.currentBasket['items'];
        int index =
            addedPacks.indexWhere((addedPack) => addedPack['packId'] == packId);
        if (index > -1) {
          addedPacks[index]['netAmount'] += pack['netAmount'];
          addedPacks[index]['requiredQty'] += pack['requiredQty'];
          addedPacks[index]['netAmountString'] =
              pack['netAmount'].toStringAsFixed(CoreSession.numberOfDigits);
        } else {
          addedPacks.add(pack);
        }
      } else {
        addedPacks.add(pack);
      }

      double netTotal = 0;
      for (var p in addedPacks) {
        netTotal = netTotal + p['netAmount'];
      }

      this._itemsService.updateBasket(addedPacks, netTotal);
      EasyLoading.showSuccess('added-successfully'.tr);
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Card(
            child: ListView(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              children: widget.promotionInputs
                  .map((e) => ListTile(
                        title: widget.promotionInputs.indexOf(e) != 0 &&
                                widget.promotionInputs[widget.promotionInputs
                                        .indexOf(e)]['promotionOptionTypeId'] ==
                                    widget.promotionInputs[
                                        widget.promotionInputs.indexOf(e) -
                                            1]['promotionOptionTypeId']
                            ? Text('or'.tr,
                                style: Theme.of(context).textTheme.bodyMedium)
                            : Text('should-buy'.tr,
                                style: Theme.of(context).textTheme.bodyMedium),
                        subtitle: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                                toQueryString(
                                  e['promotionOptionDetails'],
                                ),
                                style: Theme.of(context).textTheme.headlineLarge),
                            e['showTakePromotionOption'] == true
                                ? Container(
                                    margin: EdgeInsets.only(top: 10),
                                    child: TakePromotion(
                                        e.containsKey('takeQty')
                                            ? e['takeQty']
                                            : 0,
                                        e['promotionOptionId'],
                                        onOfferCountChange,
                                        onTakeOffer),
                                  )
                                : Container(),
                          ],
                        ),
                      ))
                  .toList(),
            ),
          ),
          Card(
            child: ListView(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              children: widget.promotionOutputs
                  .map(
                    (e) => ListTile(
                      title: widget.promotionOutputs.indexOf(e) != 0 &&
                              widget.promotionOutputs[widget.promotionOutputs
                                      .indexOf(e)]['promotionOptionTypeId'] ==
                                  widget.promotionOutputs[
                                      widget.promotionOutputs.indexOf(e) -
                                          1]['promotionOptionTypeId']
                          ? Text('or'.tr,
                              style: Theme.of(context).textTheme.bodyLarge)
                          : Text('will-get'.tr,
                              style: Theme.of(context).textTheme.bodyLarge),
                      subtitle: Text(
                          toQueryString(
                            e['promotionOptionDetails'],
                          ),
                          style: Theme.of(context).textTheme.bodySmall),
                    ),
                  )
                  .toList(),
            ),
          ),
        ],
      ),
    );
  }

  toQueryString(obj) {
    var parts = [];
    // tslint:disable-next-line:forin
    for (var property in obj) {
      String? value = property['description'];
      if (value != null && value != '') {
        parts.add(value);
      }
    }
    return parts.join(" & ");
  }
}
