import 'dart:convert';

import 'package:bottom_bar_matu/utils/app_utils.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/services/items.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/theme/variables.dart';
import 'package:echo_app/widgets/General_item_list/widgets/add_remove_item_box.dart';
import 'package:favorite_button/favorite_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/constant-storage.dart';
import '../screens/item-informations-page/item-informations.page.dart';

// ignore: must_be_immutable
class ItemWidget extends StatelessWidget {
  var item = {};
  var sectionTypeId = -1;
  var pathStr = '';
  var name = '';
  var selected = false;
  var ItemList = [];

  Function refreshpage;
  Function onClickCard;
  Function onClickDetailCard;
  ItemService itemsService = new ItemService();
  ItemWidget(this.item, this.onClickCard,this.ItemList, this.onClickDetailCard,this.refreshpage);

  Future<String> fetchData() async {
    return "Data loaded";
  }
  onQtyChanged(var pack, int index, String quantity, bool isEdit) {
    int qty = 0;
    if (quantity == '') {
      quantity = '0';
    }
    if ((quantity == '1' || quantity == '-1') &&
        !isEdit &&
        pack['requiredQty'] != 2)
      quantity =
          (pack['requiredQty'] + double.parse(quantity)).toStringAsFixed(0);

    qty = int.parse(quantity);

    this.ItemList = ItemService.items;
    if (qty <= 0 && pack['requiredQty'] == 0) {
      return;
    }
    if ((qty == -1 || qty == 1)) {
      if (!isEdit)
        pack['requiredQty'] = pack['requiredQty'] + qty;
      else
        pack['requiredQty'] = qty;
    }

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

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

    pack['netAmount'] = gross + (gross * pack['tax']) / 100;

    // pack['requiredQty'] = pack['requiredQty'];

    double netAmount = pack['netAmount'];
    pack['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'] = pack['requiredQty'];

      this.ItemList[originalIndex]['netAmount'] = pack['netAmount'];

      this.ItemList[originalIndex]['netAmountString'] =
      pack['netAmountString'];
    }

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

      ItemService.items[originalIndex]['netAmount'] = pack['netAmount'];

      ItemService.items[originalIndex]['netAmountString'] =
      pack['netAmountString'];
    }
    this.addItemToCart(pack);
    refreshpage();
    Future<String> result = fetchData();
    return result;
  }

  addItemToCart(pack) {

      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 (pack['requiredQty'] == 0 || pack['requiredQty'] == null) {
          addedPacks.remove(addedPacks[index]);
        } else 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 GestureDetector(
      onTap: () {
        this.onClickDetailCard(item);
      },
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5),
        ),
        child: Container(
          height: 250,
          decoration: BoxDecoration(
            border: Border.all(
              width: 0.25,
              color: this.selected ? Colors.redAccent : Color(0xff7C7C7C),
            ),
            borderRadius: BorderRadius.circular(5),
          ),
          child: Row(
            children: [
              Expanded(
                flex: 1,
                child: Stack(children: [
                  PositionedDirectional(
                      start: 1,
                      child: FavoriteButton(
                        iconSize: 30.0,
                        isFavorite:
                        CoreSession.favBasket.contains(item['packId']),
                        valueChanged: (_isFavorite) async {
                          if (!CoreSession.favBasket.contains(item['packId']))
                            CoreSession.favBasket.add(item['packId']);
                          else
                            CoreSession.favBasket.remove(item['packId']);

                          SharedPreferences prefs =
                          await SharedPreferences.getInstance();
                          prefs.setString(ConstantStorage.favBasket,
                              json.encode(CoreSession.favBasket));
                        },
                      )),
                  Container(
                    padding: EdgeInsets.all(2),
                    height: 100,
                    width: double.infinity,
                    child: ClipRRect(
                        borderRadius: BorderRadius.circular(5),
                        child: Image.network(
                          height: 80.0,
                          CoreSession.imagePath +
                              "item/" +
                              item['itemId'].toString() +
                              ".png",
                          errorBuilder: (context, error, stackTrace) {
                            return Image.network(
                                CoreSession.imagePath + '/no-image.png');
                          },
                          fit: BoxFit.fitHeight,
                        )),
                  ),
                  if (item['hasOffer'])
                    PositionedDirectional(
                      end: 1,
                      child: Image.asset(
                        'OfferGIF'.tr,
                        width: 40,
                      ),
                    ),
                  // if (CoreSession.favBasket.contains(item['packId']))

                ]),
              ),
              Expanded(
                flex: 3,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,

                  children: [
                    Padding(
                      padding: EdgeInsets.fromLTRB(4, 1, 4, 1),
                      child: Text(
                        // ignore: unnecessary_null_comparison
                        item['itemName'] != null ? item['itemName'] : '',
                        overflow: TextOverflow.ellipsis,
                        softWrap: false,
                        maxLines: CoreSession.selectedLanguageId == 1 ? 2 : 1,
                        style: TextStyle(
                          fontSize: Variables.headline1FontSize,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.fromLTRB(4, 1, 4, 1),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            // ignore: unnecessary_null_comparison
                            item['uom'] != null ? item['uom'] : '',
                            overflow: TextOverflow.ellipsis,
                            softWrap: false,
                            maxLines: 1,
                            textAlign: TextAlign.start,
                            style: TextStyle(
                              color: Colors.grey,
                              fontSize: Variables.headline5FontSize,
                              fontWeight: FontWeight.normal,
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 20,),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset(
                            'assets/imgs/more_icons/price-tag.png',
                            color:  Color(0xFF2D9596),
                            height: 25,
                            width: 25),
                        Padding(
                          padding: const EdgeInsets.fromLTRB(4, 1, 4, 1),
                          child: Text(
                            // ignore: unnecessary_null_comparison
                            item['basePrice'] != null
                                ? item['basePrice'].toStringAsFixed(2) +
                                ' ' +
                                CoreSession.currentOperator['currencyCode']
                                : '0.00\$',
                            overflow: TextOverflow.ellipsis,
                            softWrap: false,
                            maxLines: 1,
                            textAlign: TextAlign.start,
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: Variables.headline2FontSize,
                              fontWeight: FontWeight.normal,
                            ),
                          ),
                        ),
                        Spacer(),

                        AddRemoveItemBox(
                            this.onQtyChanged!, item, -1)


                      ],
                    ),

                    SizedBox(height: 5,),
                    InkWell(
                      onTap: (){

                      },
                      child: Container(

                        decoration: BoxDecoration(
                          color: Variables.color_primary,
                          borderRadius: BorderRadius.circular(5.0),
                        ),
                        child: Row(
                          children: [
                            Spacer(),
                            Image.asset(
                                'assets/imgs/more_icons/cart_button.png',
                                color: Colors.white,
                                height: 40,
                                width: 40),
                            Text('add-cartoon'.tr,style: TextStyle(color: Colors.white),),
                            Spacer(),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

}
