import 'dart:convert';
import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/global/global.dart';
import 'package:echo_app/models/constant-storage.dart';
import 'package:echo_app/screens/login_page/login.page.dart';
import 'package:echo_app/screens/my_order/my_order.page.dart';
import 'package:echo_app/screens/notifications/notification.page.dart';
import 'package:echo_app/screens/offers/offers.page.dart';
import 'package:echo_app/screens/order_summery/correctOrder.dart';
import 'package:echo_app/screens/order_summery/order_summery.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/services/order.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/widgets/checkout_save_box.dart';
import 'package:echo_app/widgets/general_item_list/general_item_list.widget.dart';
import 'package:echo_app/widgets/no_items_cart.widget.dart';
import 'package:echo_app/widgets/order_summery_and_edit_dialog/order_summery_and_edit_dialog.dart';
import 'package:echo_app/widgets/search_bar.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../theme/variables.dart';

// ignore: must_be_immutable
class MyFavouritePage extends StatefulWidget {
  @override
  _MyFavouritePageState createState() => _MyFavouritePageState();
  DateTime deliveryDate = new DateTime(
      DateTime.now().year, DateTime.now().month, DateTime.now().day + 1);
  MyOrderPage() {
    if (DateFormat('EEEE').format(deliveryDate).toString() == 'Friday') {
      deliveryDate = new DateTime(
          deliveryDate.year, deliveryDate.month, deliveryDate.day + 1);
    }
  }
}

class _MyFavouritePageState extends State<MyFavouritePage> {
  double netTotal = 0;
  var orderItems = [];
  var achivements = [];
  var appearedList = [];
  var summaryDataList = [];
  var soldItems = [];
  var promotedItems;
  String cancelbtn = '';
  String removebtn = '';
  bool showbackButton = false;
  String checkoutImagePath = '';
  String submitImagePath = '';
  bool showSummary = false;
  bool addNewItem = false;
  String addByString = '';
  ItemService itemsService = new ItemService();
  CoreSession coreSession = new CoreSession();
  bool showNote = false;
  String orderNote = '';
  OrderService _orderService = new OrderService();
  double summaryNetTotal = 0;
  double summaryTotalBeforFirstUserDiscount = 0;
  bool loading = false;

  TextEditingController _searchCtrl = TextEditingController();
  var closeToPromotionIds;
  var data;
  var searchByString = '';



  onEnterSearch() {
    if (_searchCtrl.text == '') {
      setState(() {
        this.appearedList = this.orderItems;
      });
     
    } else {
      this.filterItems();
    }
  }

  filterItems() {
    setState(() {
      this.appearedList = [];

      var filterList = [];

      filterList = this._searchCtrl.text.split(' ');
      if (filterList.length > 0) {
        this.appearedList = this.orderItems;
        for (var word in filterList) {
          this.appearedList = this
              .appearedList
              .where(
                (item) => item['itemName']
                    .toString()
                    .toLowerCase()
                    .contains(word.toLowerCase()),
              )
              .toList();
        }
      }
    });
  }

  initState() {
    this.loadData();
    super.initState();
  }

  loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      // ignore: unused_local_variable
      var val = CoreSession.favBasket;
      var tempList = [];
      ItemService.items.forEach((i) {
        if (CoreSession.favBasket.contains(i['packId']))
          tempList.add(i);
      });
      this.appearedList = tempList;

    });
  }

  onClickOffer(){
      this.loadData();
  }


  updateCart() {
    setState(() {
      this.netTotal = 0;
      this.orderItems.forEach((p) {
        this.netTotal = this.netTotal + p['netAmount'];
      });
      this.itemsService.updateBasket(this.orderItems, this.netTotal);
      ItemService.netTotal = this.netTotal;
    });
  }



  presentAlertMultipleButtons() {
    Alert(
      context: context,
      type: AlertType.none,
      title: "",
      desc: "msg-achivement".tr,
      useRootNavigator: true,
      style: AlertStyle(
        isCloseButton: false,
        alertBorder: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5),
        ),
      ),
      buttons: [
        DialogButton(
          color: Colors.white,
          child: Text(
            "ok".tr,
            style: TextStyle(color: Colors.greenAccent, fontSize: 20),
          ),
          onPressed: () => Navigator.of(context, rootNavigator: true).pop(),
          width: 120,
        )
      ],
    ).show();
  }





  getData(DateTime deliveryDate, String orderNote) {
    this.orderNote = orderNote;
    // ignore: unnecessary_null_comparison
    if (deliveryDate != null) {
      this.widget.deliveryDate = deliveryDate;
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Row(
          children: [
            Text("favourite".tr,style: TextStyle(color: Colors.black),),
            Spacer(),
            CoreSession.newNotificationCount > 0 ?
            IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => NotificationPage()),
                  );
                },
                icon: Image.asset(
                    'assets/imgs/more_icons/notification.png',
                    color: Variables.color_primary,
                    height: 33,
                    width: 30))
                :     IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => NotificationPage()),
                  );
                },
                icon: Image.asset(
                    'assets/imgs/more_icons/notification.png',
                    color: Variables.color_primary,
                    height: 33,
                    width: 30)),
            IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => MyOrderPage()),
                  );
                },
                icon: Image.asset(
                    'assets/imgs/default/cart.png',
                    color: Variables.color_primary,
                    height: 33,
                    width: 30)),
          ],
        ),
        automaticallyImplyLeading: false,),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(height: 10,),
            //   Padding(
            //     padding: const EdgeInsets.all(8.0),
            //     child: Text(
            //     'favourite'.tr,
            //     style: TextStyle(color: Colors.black, fontSize: 18),
            // ),
            //   ),
            // Divider(
            //   color: Colors.grey,
            // ),
            appearedList.length > 0
                ? Expanded(
                    child: Column(
                      children: [
                        Expanded(
                          flex: 10,
                          child: Container(
                              child: GeneralItemListWidget(
                                  this.appearedList,
                                  false,
                                  false,
                                  false,
                                  true,
                                  (){},
                                  true,
                                  false,
                                  this.onClickOffer,
                                  true, 0.0)),
                        ),
                        // Expanded(
                        //   flex: 1,
                        //   child: CheckOutSaveBox(
                        //       this.netTotal, onCheckOut, 'checkout'.tr),
                        // )
                      ],
                    ),
                  )
                : Expanded(child: NoItemCartWidget(2)),
          ],
        ),
      ),
    );
  }
}
