import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/models/shared-filter.dart';
import 'package:echo_app/screens/my_order/my_order.page.dart';
import 'package:echo_app/screens/offers/offers.page.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 OfferInputOutput extends StatefulWidget {
  var promotionInput;
  var promotionOutput;

  int promotionType;
  int promotionId;

  bool showTakePromotionOption = false;

  OfferInputOutput(this.promotionId, this.promotionInput, this.promotionOutput,
      this.promotionType, this.showTakePromotionOption);

  @override
  State<OfferInputOutput> createState() => _OfferInputOutputState();
}

class _OfferInputOutputState extends State<OfferInputOutput> {
  String _inputStr = '';
  String _outputStr = '';
  // ignore: unused_field
  int _inputLength = -1;
  GeneralFilter filter = new GeneralFilter();
  ItemService _itemsService = new ItemService();

  initState() {
    super.initState();
    fillData();
  }
  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(" & ");
  }

  fillData() {
    setState(() {
      _inputLength = this.widget.promotionInput.length;
      _inputLength = this.widget.promotionOutput.length;
      var promotionOptionDetailsInput =
          this.widget.promotionInput[0]['promotionOptionDetails'];
      var promotionOptionDetailsOutput =
          this.widget.promotionOutput[0]['promotionOptionDetails'];

      _inputStr = toQueryString(promotionOptionDetailsInput);
      _outputStr = toQueryString(promotionOptionDetailsOutput);
    });
  }

  onOfferCountChange(int promotionOptionId, String qty) {
    setState(() {
      // ignore: unnecessary_null_comparison
      if (qty == null || qty == '') {
        qty = '0';
      }

      int count = int.parse(qty);

      if (!widget.promotionInput[0].containsKey('takeQty')) {
        widget.promotionInput[0]['takeQty'] = 0;
      }
      if (widget.promotionInput[0]['takeQty'] == 0 && count == -1) {
        return;
      }
      if (count == 1) {
        widget.promotionInput[0]['takeQty'] += 1;
      } else if (count == -1) {
        widget.promotionInput[0]['takeQty'] -= 1;
      } else {
        widget.promotionInput[0]['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,
        style: AlertStyle(
          isCloseButton: false,
          alertBorder: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5),
          ),
        ),
        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 = 0;
    if (index != -1) {
      var selectedInput = widget.promotionInput[index];
      takeQty = selectedInput['takeQty'];
      if (selectedInput.containsKey('takeQty') &&
          selectedInput['takeQty'] != 0) {
        for (var option in widget.promotionInput[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.promotionInput[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);
      //  Navigator.pushReplacement(
      //                 context,
      //                 MaterialPageRoute(builder: (context) => MyOrderPage()),
      //               );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListTile(
          title: Text('should-buy'.tr,
              style: Theme.of(context).textTheme.bodyLarge),
          subtitle: new Text(this._inputStr,
              style: Theme.of(context).textTheme.bodySmall),
        ),
        ListTile(
          title:
              Text('will-get'.tr, style: Theme.of(context).textTheme.bodyLarge),
          subtitle: new Text(this._outputStr,
              style: Theme.of(context).textTheme.bodySmall),
        ),
        if (this.widget.showTakePromotionOption)
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 5),
            child: TakePromotion(
                this.widget.promotionInput[0] != null &&
                        this.widget.promotionInput[0].containsKey('takeQty')
                    ? this.widget.promotionInput[0]['takeQty']
                    : 0,
                this.widget.promotionInput[0]['promotionOptionId'],
                onOfferCountChange,
                onTakeOffer),
          ),
      ],
    );
  }
}
