import 'dart:convert';

import 'package:badges/badges.dart';
import 'package:echo_app/screens/home_page/home.page.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:favorite_button/favorite_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:get/get.dart';
import 'package:riverpod/riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../models/constant-storage.dart';

import '../../services/items.service.dart';
import '../../services/offers.service.dart';
import '../../shared/NavigationService.dart';
import '../../theme/variables.dart';
import '../../widgets/General_item_list/widgets/add_remove_item_box.dart';
import '../../widgets/checkout_save_box.dart';
import '../home_page/widget/carousel_slider.widget.dart';
import '../my_order/my_order.page.dart';
import 'package:firebase_analytics/firebase_analytics.dart';

import '../tap_page/tap.page.dart';

// ignore: must_be_immutable
class ItemInformationsPage extends StatefulWidget {
  var orderItems = [];
  var itemList = [];
  var item;
  var offerList = [];
  int oldValue = 0;
  double RateValue = 0.0;
  double oldRateValue = 0.0;
  ItemService itemsService = new ItemService();
  bool isFav = false;

  ItemInformationsPage(this.item) {
    oldValue = this.item['requiredQty'] ?? 0;
    if (CoreSession.currentBasket['items']
        .firstWhere((f) => f['packId'] == item['packId'], orElse: () => '')
        .toString()
        .isNotEmpty)
      this.item = CoreSession.currentBasket['items']
          .firstWhere((f) => f['packId'] == item['packId'], orElse: () => '');

    // RateValue = double.parse(item['rateValue'].toStringAsFixed(2));
    // oldRateValue = RateValue;

    if (CoreSession.favBasket.contains(item['packId'])) {
      isFav = true;
    }

    offerList = OffersService.offers;
  }

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

class _ItemInformationPage extends State<ItemInformationsPage> {
  // TODO: implement createState
  FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  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 (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.widget.itemsService.updateBasket(addedPacks, netTotal);
      // EasyLoading.showSuccess('added-successfully'.tr);
    });
  }

  addItemToFav(pack) {
    setState(() async {
      if (!CoreSession.favBasket.contains(pack['packId']))
        CoreSession.favBasket.add(pack['packId']);
      else
        CoreSession.favBasket.remove(pack['packId']);

      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString(
          ConstantStorage.favBasket, json.encode(CoreSession.favBasket))!;
    });
  }

  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.widget.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.widget.itemList.indexWhere((i) => i['packId'] == pack['packId']);
    if (originalIndex > -1) {
      this.widget.itemList[originalIndex]['requiredQty'] = pack['requiredQty'];

      this.widget.itemList[originalIndex]['netAmount'] = pack['netAmount'];

      this.widget.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);
  }

  int defaultSelect = 0;
  var listvar = ['250 ml', '500 ml', '1L'];

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

  updateRateValue() async {
    ItemService service = ItemService();
    if (CoreSession.currentOperator != null &&
        this.widget.oldRateValue != this.widget.RateValue) {
      // await service
      //     .setPackRate(this.widget.item['packId'], this.widget.RateValue,
      //         CoreSession.currentOperator['customerId'])
      //     .then((value) {
      //   this.widget.item['rateValue'] = this.widget.RateValue;
      //   service.fillHomePageSectionsAndItems();
      // });
    }
  }

  @override
  void dispose() {
    updateRateValue();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    this.widget.orderItems = CoreSession.currentBasket['items'];

    return WillPopScope(
      onWillPop: () async {
        analytics.logEvent(name: 'PageTrack', parameters: {
          "PagaName": 'Back from Item :' + this.widget.item['itemName'],
          "ItemID": this.widget.item['itemId']
        });
        bool value = false;
        if (this.widget.oldValue != this.widget.item['requiredQty'])
          await CoreSession.showYesNoDialog(context, () {
            onQtyChanged(
                this.widget.item, -1, this.widget.oldValue.toString(), true);
            value = true;
          }, 'confirm-proceed'.tr);
        else
          value = true;

        return value;
      },
      child: Scaffold(
        appBar: AppBar(
            backgroundColor: Variables.color_primary,
            title: Text(this.widget.item['itemName']),
            actions: <Widget>[
              IconButton(
                  icon: Image.asset('assets/imgs/cart.png',
                          color: Colors.white, height: 33, width: 30),
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => MyOrderPage()),
                    );
                  }),
            ]),
        bottomSheet: Container(
          height: 70,
          child: Padding(
            padding:
                const EdgeInsets.symmetric(horizontal: 15.0, vertical: 8.0),
            child: ElevatedButton(
              onPressed: () {
                print('onPress ');
                if (this.widget.oldValue == 0 &&
                    this.widget.item['requiredQty'] == 0) {
                  Fluttertoast.showToast(
                      msg: "insert-qty".tr,
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      timeInSecForIosWeb: 1,
                      backgroundColor: Colors.red,
                      textColor: Colors.white,
                      fontSize: 16.0);
                  return;
                } else {
                  Navigator.of(context).pop(true);


                    TapPage.ReloadHome();
                }
              },
              child: Row(
                children: [
                  Spacer(),
                  Text(this.widget.oldValue == 0
                      ? 'add-to-cart'.tr
                      : 'edit-cart'.tr),
                  Spacer(),
                ],
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: Variables.color_primary,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ),
          ),
        ),
        body: Container(
          width: size.width,
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  color: Color(0xffF2F3F2),
                  child: Column(
                    children: [
                      Container(
                          width: size.width * 0.9,
                          height: 200,
                          child: Image.network(
                            CoreSession.imagePath +
                                "item/" +
                                this.widget.item['itemId'].toString() +
                                ".png",
                            errorBuilder: (context, error, stackTrace) {
                              return Image.network(
                                  CoreSession.imagePath + '/no-image.png');
                            },
                            fit: BoxFit.fill,
                          )
                          // CarouselSliderWidget([
                          //   CoreSession.imagePath +
                          //       "item/" +
                          //       this.widget.item['itemId'].toString() +
                          //       ".png"
                          // ]),
                          ),
                      SizedBox(
                        height: 10,
                      )
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Row(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            width: 300,
                            child: Text(
                              this.widget.item['itemName'],
                              style: TextStyle(
                                fontSize: Variables.headline1FontSize,
                                color: Colors.black,
                              ),
                            ),
                          ),
                          Text(
                            this.widget.item['uom'] ?? '',
                            style: TextStyle(
                                fontSize: Variables.headline2FontSize,
                                color: Colors.grey),
                          ),
                        ],
                      ),
                      Spacer(),
                      FavoriteButton(
                        isFavorite: this.widget.isFav,
                        valueChanged: (_isFavorite) {
                          addItemToFav(this.widget.item);
                        },
                      )
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Row(
                    children: [
                      AddRemoveItemBox(
                          this.onQtyChanged!, this.widget.item, -1),
                      Spacer(),
                      Text(
                          ((this
                                  .widget
                                  .item['exclusivePrice'] ?? 0.00)
                                  .toStringAsFixed(2) +
                              ' ' +
                              CoreSession.currentOperator['currencyCode']),
                          style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              fontFamily: 'Poppins'))
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(0, 0, 10, 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text('tax'.tr),
                      ),
                      Text(this.widget.item['tax'].toString() + '' + '%',
                          style: TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.bold,
                              fontFamily: 'Poppins')),
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text('net-total'.tr),
                      ),
                      Text(
                        (this.widget.item['netAmountString'] != null
                            ? double.parse(this.widget.item['netAmountString'])
                                .toStringAsFixed(2)
                            : '0' +
                                ' ' +
                                CoreSession.currentOperator['currencyCode']),
                        style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            fontFamily: 'Poppins'),
                      )
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 16.0, vertical: 5.0),
                  child: Row(
                    children: [
                      Text('uom'.tr),
                      Spacer(),
                      Text(this.listvar[this.defaultSelect])
                    ],
                  ),
                ),
                ExpansionTile(
                  title: Text('product-detail'.tr),
                  children: <Widget>[
                    ListTile(
                        title: Text(
                      this.widget.item['itemDefinition'],
                      style: TextStyle(
                          fontSize: Variables.headline2FontSize,
                          color: Colors.black),
                    )),
                  ],
                ),
                // ExpansionTile(
                //   title: Row(
                //     children: [
                //       Text('review'.tr),
                //       Spacer(),
                //       RatingBar.builder(
                //         ignoreGestures: true,
                //         initialRating: this.widget.RateValue,
                //         minRating: 0.5,
                //         direction: Axis.horizontal,
                //         allowHalfRating: false,
                //         itemCount: 5,
                //         itemPadding: EdgeInsets.symmetric(horizontal: 1.0),
                //         itemSize: 20,
                //         itemBuilder: (context, _) => Icon(
                //           Icons.star,
                //           color: Colors.amber,
                //         ),
                //         onRatingUpdate: (rating) {},
                //       )
                //     ],
                //   ),
                //   children: <Widget>[
                //     RatingBar.builder(
                //       initialRating: this.widget.RateValue,
                //       minRating: 0,
                //       direction: Axis.horizontal,
                //       allowHalfRating: false,
                //       itemCount: 5,
                //       itemPadding: EdgeInsets.symmetric(horizontal: 1.0),
                //       itemSize: 40,
                //       itemBuilder: (context, _) => Icon(
                //         Icons.star,
                //         color: Colors.amber,
                //       ),
                //       onRatingUpdate: (rating) {
                //         this.widget.RateValue = rating;
                //       },
                //     ),
                //   ],
                // ),
                SizedBox(
                  height: 70,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
