import 'package:community_material_icon/community_material_icon.dart';
import 'package:echo_app/enums/echo-custome-home-page-types.dart';
import 'package:echo_app/enums/echo_special_items_types.dart';
import 'package:echo_app/models/customer-app-settings-model.dart';
import 'package:echo_app/models/shared-filter.dart';
import 'package:echo_app/screens/items_list_page/widgets/top_part_selection.dart';
import 'package:echo_app/screens/offers/offers.page.dart';
import 'package:echo_app/screens/tap_page/tap.page.dart';
import 'package:echo_app/services/items.service.dart';
import 'package:echo_app/services/offers.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/widgets/general_item_list/general_item_list.widget.dart';
import 'package:echo_app/screens/my_order/my_order.page.dart';
import 'package:echo_app/widgets/no_data.widget.dart';
import 'package:echo_app/widgets/search_bar.dart' as search;
import 'package:echo_app/widgets/total_box.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../theme/variables.dart'; 
// ignore: must_be_immutable
class ItemListPage extends StatefulWidget {
  var dataList = [];
  var selectedData;
  int index = 0;
  String searchByString = '';
  bool isExternalSearch = false;
  TextEditingController _searchCtrl = new TextEditingController();

  ItemListPage(this.dataList, this.index, this.searchByString) {
    if (this.dataList.length != 0) {
      selectedData = this.dataList[index];
      this.isExternalSearch = false;
    } else {
      this.isExternalSearch = true;
    }
  }

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

class _ItemListPageState extends State<ItemListPage> {
  var itemList = [];
  var appearedList = [];
  GeneralFilter filter = new GeneralFilter();
  ItemService _itemService = new ItemService();
  CoreSession coreSession = new CoreSession();

  bool isLoading = true;
  var filterItemList = [];

  String title = '';

  initState() {
    if (this.widget.isExternalSearch) {
      this.title = 'items'.tr;
    } else {
      this.title = widget.selectedData != null
          ? widget.selectedData['name']
          : 'items'.tr;
    }

    this.widget._searchCtrl.text = this.widget.searchByString;
    filterItems(this.widget.selectedData, false);
    super.initState();
  }

  onEnterSearch() async {
    setState(() {
      this.widget.searchByString = this.widget._searchCtrl.text;
      this.filterItems(this.widget.selectedData, false);
    });
  }

  filterItems(selectedData, bool fromTopSection) {
    setState(() {
      this.appearedList = [];
      if (this.widget.isExternalSearch) {
        // ignore: unnecessary_null_comparison
        if (this.widget.searchByString != null &&
            this.widget.searchByString != '') {
          var filterList = [];
          filterList = this.widget.searchByString.split(' ');
          if (filterList.length > 0) {
            this.appearedList = ItemService.items;
            for (var word in filterList) {
              this.appearedList = this
                  .appearedList
                  .where(
                    (item) => item['itemName']
                        .toString()
                        .toLowerCase()
                        .contains(word.toLowerCase()),
                  )
                  .toList();
            }
          }
        } else {
          this.appearedList = ItemService.items;
        }
      } else {
        if (selectedData != null) {
          this.widget.selectedData = selectedData;
          this.widget.dataList.forEach((element) {
            element['selected'] = false;
          });
           this.widget.selectedData['selected'] = true;
          this.title = this.widget.selectedData['name'];
          if (this.widget.selectedData['sectionTypeId'] ==
              EchoCustomeHomePageTypes.Brands.index) {
            this.appearedList = ItemService.items
                .where((item) =>
                    item['brandId'] != null &&
                    item['brandId'] == this.widget.selectedData['id'])
                .toList();
          }
          if (this.widget.selectedData['sectionTypeId'] ==
              EchoCustomeHomePageTypes.Categories.index) {
            this.appearedList = ItemService.items
                .where((item) =>
                    item['itemCategoryId'] != null &&
                    item['itemCategoryId'] == this.widget.selectedData['id'])
                .toList();
          }
          if (this.widget.selectedData['sectionTypeId'] ==
              EchoCustomeHomePageTypes.MasterGroupes.index) {
            var ids = this.widget.selectedData['itemsIds'];

            for (var id in ids) {
              var index =
                  ItemService.items.indexWhere((item) => item['itemId'] == id);
              if (index > -1) {
                this.appearedList.add(ItemService.items[index]);
              }
            }
          }
          if (this.widget.selectedData['sectionTypeId'] ==
              EchoCustomeHomePageTypes.Special.index) {
            filterSpicialItems();
          }

          // ignore: unnecessary_null_comparison
          if (this.widget.searchByString != null &&
              this.widget.searchByString != '') {
            var filterList = [];
            filterList = this.widget.searchByString.split(' ');
            if (filterList.length > 0) {
              for (var word in filterList) {
                this.appearedList = this
                    .appearedList
                    .where(
                      (item) => item['itemName']
                          .toString()
                          .toLowerCase()
                          .contains(word.toLowerCase()),
                    )
                    .toList();
              }
            }
          }
        }
      }
    });
  }

  filterSpicialItems() {
    setState(() {
      if (this.widget.selectedData['id'] == EchoSpecialItemsTypes.IsNew.index) {
        this.appearedList = ItemService.items
            .where((item) => item['isNew'] != null && item['isNew'] == true)
            .toList();
      }
      if (this.widget.selectedData['id'] ==
          EchoSpecialItemsTypes.IsInitiative.index) {
        this.appearedList = ItemService.items
            .where((item) =>
                item['isInitiative'] != null && item['isInitiative'] == true)
            .toList();
      }
      if (this.widget.selectedData['id'] ==
          EchoSpecialItemsTypes.IsPowerSKU.index) {
        this.appearedList = ItemService.items
            .where((item) =>
                item['isPowerSKU'] != null && item['isPowerSKU'] == true)
            .toList();
      }
      if (this.widget.selectedData['id'] ==
          EchoSpecialItemsTypes.TopSailing.index) {
        var list = ItemService.items
            .where((item) =>
                item['isCustomerAppMostSelling'] != null &&
                item['isCustomerAppMostSelling'] == true)
            .toList();
        list.sort((a, b) => a['customerAppMostSellingSequence']
            .compareTo(b['customerAppMostSellingSequence']));
        this.appearedList = list;
      }
    });
  }

  addItemToCart(pack) {
      FocusScope.of(context).unfocus();
    setState(() {
      var addedPacks = [];
      addedPacks = CoreSession.currentBasket['items'];
      var index = addedPacks
          .indexWhere((addedPack) => addedPack['packId'] == pack['packId']);
      if (index > -1) {
        if (pack['requiredQty'] == 0 || pack['requiredQty'] == null) {
          addedPacks.remove(addedPacks[index]);
        } else {
          addedPacks[index]['netAmount'] = pack['netAmount'];
          addedPacks[index]['netAmountString'] = pack['netAmountString'];
          addedPacks[index]['requiredQty'] = pack['requiredQty'];
        }
      } else {
        if (pack['requiredQty'] != null && pack['requiredQty'] != 0) {
          addedPacks.add(pack);
        }
      }
      ItemService.netTotal = 0;
      addedPacks.forEach(
        (p) => {
          ItemService.netTotal = ItemService.netTotal + p['netAmount'],
        },
      );
      //this.netTotal = this.netTotal.toFixed(this.coreSession.numberOfDigits);
      this._itemService.updateBasket(addedPacks, ItemService.netTotal);
      TapPage.cartValue.value = addedPacks.length;
    });
  }

  onQtyChanged(var pack, int index, String quantity , bool IsEdit) {
    setState(() {
      int qty = 0;
      if (quantity != '') {
        qty = int.parse(quantity);
      }

      if (qty == -1 && pack['requiredQty'] == 0) {
        return;
      }
      if (qty == -1 || qty == 1) {
        pack['requiredQty'] = pack['requiredQty'] + qty;
      }

      if (qty != 1 && qty != -1) {
        pack['requiredQty'] = qty;
      }

      final gross = pack['price'] * pack['requiredQty'];

      this.appearedList[index]['netAmount'] =
          gross + (gross * pack['tax']) / 100;

      this.appearedList[index]['requiredQty'] = pack['requiredQty'];

      double netAmount = this.appearedList[index]['netAmount'];
      this.appearedList[index]['netAmountString'] =
          netAmount.toStringAsFixed(CoreSession.numberOfDigits);

      //Update Original Items
      var originalIndex =
          this.itemList.indexWhere((i) => i['packId'] == pack['packId']);
      if (originalIndex > -1) {
        this.itemList[originalIndex]['requiredQty'] =
            this.appearedList[index]['requiredQty'];

        this.itemList[originalIndex]['netAmount'] =
            this.appearedList[index]['netAmount'];

        this.itemList[originalIndex]['netAmountString'] =
            this.appearedList[index]['netAmountString'];
      }

      originalIndex =
          ItemService.items.indexWhere((i) => i['packId'] == pack['packId']);
      if (originalIndex > -1) {
        ItemService.items[originalIndex]['requiredQty'] =
            this.appearedList[index]['requiredQty'];

        ItemService.items[originalIndex]['netAmount'] =
            this.appearedList[index]['netAmount'];

        ItemService.items[originalIndex]['netAmountString'] =
            this.appearedList[index]['netAmountString'];
      }

      //Update Filtered Items
      originalIndex =
          this.filterItemList.indexWhere((i) => i['packId'] == pack['packId']);
      if (originalIndex > -1) {
        this.filterItemList[originalIndex]['requiredQty'] =
            this.appearedList[index]['requiredQty'];

        this.filterItemList[originalIndex]['netAmount'] =
            this.appearedList[index]['netAmount'];

        this.filterItemList[originalIndex]['netAmountString'] =
            this.appearedList[index]['netAmountString'];
      }
      this.addItemToCart(this.appearedList[index]);
    });
  }

  onClickOffer(int itemId) {
    var itemsOffer = [];
    var offersList = [];
    itemsOffer = CoreSession.currentOperator['itemOffers'] != null
        ? CoreSession.currentOperator['itemOffers']
        : [];
    var myOffers =
        itemsOffer.where((item) => item['itemId'] == itemId).toList();
    for (var offer in myOffers) {
      var idsList = offer['offerIds'].split(',');
      for (var id in idsList) {
        if (id != "") {
          int index = OffersService.offers
              .indexWhere((e) => e['promotionId'] == int.parse(id));
          if (index > -1) {
            offersList.add(OffersService.offers[index]);
          }
        }
      }
    }
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => new OffersPage(offersList, true, false),
      ),
    );
  
  }

  @override
  Widget build(BuildContext context) {
     
    return SafeArea(
      child: Scaffold( 
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
           backgroundColor: Variables.color_primary,
          title: Text(this.title),
          automaticallyImplyLeading: false,
          actions: <Widget>[
            Container(
              margin: EdgeInsets.only(top: 5),
              child: new Stack(
                children: <Widget>[
                  new IconButton(
                    icon: Icon(CommunityMaterialIcons.cart_outline),
                    onPressed: () {
                      setState(() {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => MyOrderPage(),
                          ),
                        ).then(
                          (value) =>
                              filterItems(this.widget.selectedData, false),
                        );
                      });
                    },
                  ),
                  ValueListenableBuilder(
                    builder: (BuildContext context, int value, Widget? child) {
                      return new Positioned(
                        right: 5,
                        top: 5,
                        child: value > 0
                            ? new Container(
                                padding: EdgeInsets.all(2),
                                decoration: new BoxDecoration(
                                  color: Colors.red,
                                  borderRadius: BorderRadius.circular(5),
                                ),
                                constraints: BoxConstraints(
                                  minWidth: 16,
                                  minHeight: 16,
                                ),
                                child: Text(
                                  value.toString(),
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 9,
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                              )
                            : Container(),
                      );
                    },
                    valueListenable: TapPage.cartValue,
                  )
                ],
              ),
            ),
            IconButton(
                icon: Icon(Icons.close),
                onPressed: () {
                  Navigator.of(context).pop();
                }),
          ],
          bottom: PreferredSize(
            preferredSize: Size(50, 50),
            child: search.Search_Bar.CustomSearchBar(this.widget._searchCtrl, this.onEnterSearch,true),
          ),
        ),
        body: this.widget.dataList.length == 0 && this.appearedList.length == 0
            ? NoDataWidget()
            : Column(
                children: [
                  if (CustomerAppSettingsModel.showGroupInItemScreen &&
                      !this.widget.isExternalSearch)
                    TopPartSelection(
                        widget.dataList, widget.index, filterItems),
                  this.appearedList.length > 0
                      ? GeneralItemListWidget(
                          appearedList,
                          false,
                          false,
                          false,
                          true,
                          this.onQtyChanged,
                          false,
                          true,
                          this.onClickOffer,
                          false, 0
                  )
                      : NoDataWidget(),
                  TotalBox(ItemService.netTotal)
                ],
              ),
      ),
    );
  }
}
