import 'package:auto_animated/auto_animated.dart';
import 'package:bottom_bar_matu/utils/app_utils.dart';
import 'package:echo_app/enums/echo-custome-home-page-types.dart';
import 'package:echo_app/screens/all_classification_page/all_classification_page.dart';
import 'package:echo_app/screens/items_list_page/item_list.page.dart';
import 'package:echo_app/theme/variables.dart';
import 'package:echo_app/widgets/classification_card.widget.dart';
import 'package:echo_app/widgets/item_widget.dart';
import 'package:flutter/material.dart';
import 'package:echo_app/services/items.service.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

import '../../../enums/echo_special_items_types.dart';
import '../../../shared/core.session.dart';
import '../../item-informations-page/item-informations.page.dart';

// ignore: must_be_immutable
class GridCardList extends StatefulWidget {
  final data;
  final RangeValues _priceValue;
  final bool SearchPage;
  String pathStr = '';
  String title = '';
  var dataList = [];
  var newItemList = [];
  var FillterdItemList = [];
  final String search;
  ScrollController? controller;

  GridCardList(this.data, this.search, this._priceValue, this.SearchPage,
      this.controller) {
    if (this.controller == null) {
      this.controller = ScrollController();
    }
    this.dataList = this.data['dataList'];
    this.title = this.data['sectionName'];
    if (EchoCustomeHomePageTypes.Brands.index == this.data['sectionTypeId'])
      pathStr = 'brand';
    bool selected = false;
    for (var fillter in CoreSession.homePageData) {
      for (var fillter in fillter['dataList']) {
        switch (fillter['sectionTypeId']) {
          case 1: // brand
            if (fillter['selected']) {
              var valid = ItemService.items
                  .where((item) =>
                      item['brandId'] != null &&
                      item['brandId'] == fillter['id'])
                  .toList();

              if (newItemList.length > 0) {
                valid.forEach((element) {
                  if (!newItemList.contains(element)) newItemList.add(element);
                });
              } else {
                newItemList.addAll(valid);
              }
              selected = true;
            }
            break;
          case 2: //category
            if (fillter['selected']) {
              var valid = ItemService.items
                  .where((item) =>
                      item['itemCategoryId'] != null &&
                      item['itemCategoryId'] == fillter['id'])
                  .toList();
              if (newItemList.length > 0) {
                valid.forEach((element) {
                  if (!newItemList.contains(element)) newItemList.add(element);
                });
              } else {
                newItemList.addAll(valid);
              }
              selected = true;
            }
            break;
          case 3:
            if (fillter['selected']) {
              var ids = fillter['itemsIds'];

              for (var id in ids) {
                var index = ItemService.items
                    .indexWhere((item) => item['itemId'] == id);

                var packid = -1;
                if (index > -1) packid = ItemService.items[index]['packId'];
                var haveindex =
                    newItemList.indexWhere((item) => item['packId'] == packid);

                if (index > -1 && haveindex == -1) {
                  newItemList.add(ItemService.items[index]);
                }
              }
              selected = true;
            }

            break;
          case 4:
            if (fillter['selected']) {
              if (fillter['id'] == EchoSpecialItemsTypes.IsNew.index) {
                newItemList.addAll(ItemService.items
                    .where((item) => item['isNew'] != null && item['isNew'])
                    .toList());
              }
              if (fillter['id'] == EchoSpecialItemsTypes.IsPowerSKU.index) {
                newItemList.addAll(ItemService.items
                    .where((item) =>
                        item["isPowerSKU"] != null && item['isPowerSKU'])
                    .toList());
              }
              if (fillter['id'] == EchoSpecialItemsTypes.IsInitiative.index) {
                newItemList.addAll(ItemService.items
                    .where((item) =>
                        item['isInitiative'] != null && item['isInitiative'])
                    .toList());
              }
              selected = true;
            }
            break;
        }
      }
    }

    if (EchoCustomeHomePageTypes.Categories.index == this.data['sectionTypeId'])
      pathStr = 'category';

    if (EchoCustomeHomePageTypes.MasterGroupes.index ==
        this.data['sectionTypeId']) pathStr = 'itemGroup';

    if (EchoCustomeHomePageTypes.Special.index == this.data['sectionTypeId'])
      pathStr = 'special';

    if (!selected) newItemList = ItemService.items;

    newItemList = newItemList
        .where((i) =>
            (i['itemName']
                    .toString()
                    .toLowerCase()
                    .contains(search.toLowerCase()) ||
                (i['brand']
                    .toString()
                    .toLowerCase()
                    .contains(search.toLowerCase())) ||
                (i['category']
                    .toString()
                    .toLowerCase()
                    .contains(search.toLowerCase()))))
        .toList();
    if (newItemList.length > 20)
      FillterdItemList.addAll(newItemList.take(20));
    else
      FillterdItemList.addAll(newItemList);
  }

  Future<void> fetchData() async {
    if (FillterdItemList.length < newItemList.length) {
      FillterdItemList.addAll(
          newItemList.skip(FillterdItemList.length).take(20));
    }
  }

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

class _GridCardListState extends State<GridCardList> {
  void Relaod() {
    setState(() {});
  }

  final options = LiveOptions(
    // Start animation after (default zero)
    delay: Duration(milliseconds: 50),

    // Show each item through (default 250)
    showItemInterval: Duration(milliseconds: 150),

    // Animation duration (default 250)
    showItemDuration: Duration(milliseconds: 300),

    // Animations starts at 0.05 visible
    // item fraction in sight (default 0.025)
    visibleFraction: 0.05,

    // Repeat the animation of the appearance
    // when scrolling in the opposite direction (default false)
    // To get the effect as in a showcase for ListView, set true
    reAnimateOnVisibility: false,
  );

  OnClickDetails(var pack) {
    Navigator.of(context)
        .push(MaterialPageRoute(
            builder: (context) => ItemInformationsPage(pack)))
        .then((value) {
      setState(() {});
    });
  }

  @override
  void dispose() {
    //this.widget.controller!.dispose();
  }

  Widget GridViewList() {
    Size size = MediaQuery.of(context).size;

    this.widget.controller!.addListener(() {
      if (this.widget.controller!.position.maxScrollExtent ==
          this.widget.controller!.offset) {
        this.widget.fetchData().then((value) => {setState(() {})});
      }
    });
    return Container(
        child: LiveGrid.options(
      physics:  NeverScrollableScrollPhysics(),

      options: options,
      shrinkWrap: true,
      //if file/folder list is grabbed, then show here
      itemCount: this.widget.FillterdItemList.length,
      itemBuilder: buildAnimatedItem,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisSpacing: 1,
          mainAxisSpacing: 1,
          childAspectRatio: 2.5,
          crossAxisCount: MediaQuery.of(context).size.width < 500 ? 1 : 1),
    )

        );
  }

  Widget buildAnimatedItem(
    BuildContext context,
    int index,
    Animation<double> animation,
  ) =>
      // For example wrap with fade transition
      FadeTransition(
        opacity: Tween<double>(
          begin: 0,
          end: 1,
        ).animate(animation),
        // And slide transition
        child: SlideTransition(
          position: Tween<Offset>(
            begin: Offset(0, -0.1),
            end: Offset.zero,
          ).animate(animation),
          // Paste you Widget
          child: ItemWidget(this.widget.newItemList[index], () {
            setState(() {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) =>
                      ItemListPage(this.widget.dataList, index, ''),
                ),
              );
            });
          },this.widget.newItemList, OnClickDetails,(){
            setState(() {

            });
          }),
        ),
      );

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return this.widget.SearchPage
        ? GridViewList()
        : Container(
            child: GridViewList(),
          );
  }
}
