import 'dart:convert';

import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/models/customer-app-settings-model.dart';
import 'package:echo_app/screens/item-informations-page/item-informations.page.dart';
import 'package:echo_app/services/items.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/widgets/General_item_list/widgets/add_remove_item_box.dart';
import 'package:echo_app/widgets/no_data.widget.dart';
import 'package:echo_app/widgets/view_image.widget.dart';
import 'package:favorite_button/favorite_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get_utils/src/extensions/internacionalization.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../models/constant-storage.dart';
import '../../screens/tap_page/tap.page.dart';
import '../../theme/variables.dart';

// ignore: must_be_immutable
class GeneralItemListWidget extends StatefulWidget {
  var itemList = [];
  bool showRequiredQty = false;
  bool showDeliveredQty = false;
  bool showQtyInCenter = false;
  bool showAddRemoveItemBox = false;
  bool showDeleteBtn = false;
  bool showOfferBtn = false;
  bool isTextEdit = false;
  Function? onQtyChanged;
  Function? onClickOffer;
  bool IsPreviewList = false;
  double netTotal = 0;

  GeneralItemListWidget(
      this.itemList,
      this.showRequiredQty,
      this.showDeliveredQty,
      this.showQtyInCenter,
      this.showAddRemoveItemBox,
      this.onQtyChanged,
      this.showDeleteBtn,
      this.showOfferBtn,
      this.onClickOffer,
      this.IsPreviewList,
      this.netTotal) {
    print("object");
  }

  @override
  State<GeneralItemListWidget> createState() => _GeneralItemListWidgetState();
}

class _GeneralItemListWidgetState extends State<GeneralItemListWidget> {
  ItemService _itemService = new ItemService();
  CoreSession coreSession = new CoreSession();
  var filterItemList = [];

  addItemToFav(pack) 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))!;
    this.widget.onClickOffer!();
  }

  void reload(){
    setState(() {

    });
  }
  onPresentItemInfo(int itemID) async {
    var respose = await _itemService.getItemDocuments(itemID);
    if (respose['status'] == GlobalErrors.Success.index) {
      var itemDocuments = respose['data'];
      print(itemDocuments);
      if (itemDocuments.length > 0) {
        // Navigator.push(
        //   context,
        //   MaterialPageRoute(
        //     builder: (context) => ItemInformationsPage(itemID, itemDocuments),
        //   ),
        // );
      } else {
        EasyLoading.showInfo('item-no-attachments-msg'.tr);
      }
    }
  }

  Widget itemCardWidget(index) {
    return Column(
      children: [
        InkWell(
          onTap: () {
            if (this.widget.IsPreviewList)
              Navigator.of(context)
                  .push(MaterialPageRoute(
                      builder: (context) =>
                          ItemInformationsPage(this.widget.itemList[index])))
                  .then((value) => this.widget.onClickOffer!());
          },
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: GestureDetector(
                  child: Container(
                    padding: EdgeInsets.all(5),
                    //height: 90,
                    child: Image.network(
                      CoreSession.imagePath +
                          "item/" +
                          this.widget.itemList[index]['itemId'].toString() +
                          ".png",
                      width: 85,
                      height: 85,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Image.network(
                            CoreSession.imagePath + '/no-image.png');
                      },
                    ),
                  ),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => ViewImageWidget(
                            CoreSession.imagePath +
                                "item/" +
                                this
                                    .widget
                                    .itemList[index]['itemId']
                                    .toString() +
                                ".png",
                            this.widget.itemList[index]['itemName'] +
                                " (" +
                                this.widget.itemList[index]['uom'] +
                                ")"),
                      ),
                    );
                  },
                ),
              ),
              Expanded(
                flex: 4,
                child: ListTile(
                    title: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(this.widget.itemList[index]['itemName'],
                                      style: Theme.of(context)
                                          .textTheme
                                          .bodyLarge),
                                  Text(this.widget.itemList[index]['uom'],
                                      style:
                                          Theme.of(context).textTheme.bodySmall)
                                ],
                              ),
                            ),
                            if (this.widget.itemList[index]['hasOffer'] !=
                                    null &&
                                this.widget.showOfferBtn &&
                                this.widget.itemList[index]['hasOffer'])
                              GestureDetector(
                                child: Container(
                                  width: 80,
                                  child: Image.asset(
                                    'OfferGIF'.tr,
                                    fit: BoxFit.cover,
                                  ),
                                ),
                                onTap: () {
                                  this.widget.onClickOffer!(
                                      this.widget.itemList[index]['itemId']);
                                },
                              ),
                            if (this.widget.showDeleteBtn &&
                                !this.widget.IsPreviewList)
                              Container(
                                width: 25,
                                child: IconButton(
                                  onPressed: () {
                                    this.widget.onQtyChanged != null
                                        ? this.widget.onQtyChanged!(
                                            this.widget.itemList[index],
                                            index,
                                            '0.0',
                                            false)
                                        : print('object');
                                    TapPage.ReloadHome();
                                  },
                                  icon: Icon(
                                    Icons.close,
                                    color: Colors.grey,
                                  ),
                                ),
                              ),
                            if (this.widget.IsPreviewList)
                              Container(
                                width: 25,
                                child: IconButton(
                                  onPressed: () {
                                    addItemToFav(this.widget.itemList[index]);
                                  },
                                  icon: Icon(
                                    Icons.close,
                                    color: Colors.grey,
                                  ),
                                ),
                              )
                          ],
                        ),
                      ],
                    ),
                    subtitle: Row(
                      children: [
                        Expanded(
                          flex: 5,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              if (this.widget.showRequiredQty)
                                Row(
                                  children: [
                                    Text(
                                      "requested".tr + ": ",
                                      style:
                                          Theme.of(context).textTheme.bodySmall,
                                    ),
                                    Text(
                                      this
                                          .widget
                                          .itemList[index]['requestedQuantity']
                                          .toStringAsFixed(
                                              CoreSession.numberOfStockDigits)
                                          .toString(),
                                      style:
                                          Theme.of(context).textTheme.bodyText1,
                                    )
                                  ],
                                ),
                              if (this.widget.showDeliveredQty)
                                Row(
                                  children: [
                                    Text(
                                      "delivered".tr + ": ",
                                      style:
                                          Theme.of(context).textTheme.bodyText1,
                                    ),
                                    Text(
                                      this.widget.itemList[index]
                                                  ['requestedQuantity'] ==
                                              null
                                          ? this
                                              .widget
                                              .itemList[index]
                                                  ['requestedQuantity']
                                              .toString()
                                          : this
                                              .widget
                                              .itemList[index]['requiredQty']
                                              .toStringAsFixed(CoreSession
                                                  .numberOfStockDigits)
                                              .toString(),
                                    )
                                  ],
                                ),
                              if (this.widget.showQtyInCenter)
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Text(
                                      this.widget.itemList[index]
                                                  ['requestedQuantity'] !=
                                              0
                                          ? this
                                              .widget
                                              .itemList[index]
                                                  ['requestedQuantity']
                                              .toString()
                                          : this
                                              .widget
                                              .itemList[index]['requiredQty']
                                              .toStringAsFixed(CoreSession
                                                  .numberOfStockDigits)
                                              .toString(),
                                    )
                                  ],
                                ),
                              if (this.widget.showAddRemoveItemBox &&
                                  this.widget.onQtyChanged != null &&
                                  !this.widget.IsPreviewList)
                                AddRemoveItemBox(this.widget.onQtyChanged!,
                                    this.widget.itemList[index], index),
                            ],
                          ),
                        ),
                        Spacer(),
                        Expanded(
                          flex: 3,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  if (!this.widget.IsPreviewList)
                                    Text(
                                      (this
                                                          .widget
                                                          .itemList[index][
                                                              'netAmountString']
                                                          .toString() ==
                                                      'null' ||
                                                  this
                                                          .widget
                                                          .itemList[index][
                                                              'netAmountString']
                                                          .toString() ==
                                                      ''
                                              ? 0
                                                  .toStringAsFixed(CoreSession
                                                      .numberOfDigits)
                                                  .toString()
                                              : double.parse(this
                                                          .widget
                                                          .itemList[index]
                                                      ['netAmountString'])
                                                  .toStringAsFixed(CoreSession
                                                      .numberOfDigits)) +
                                          ' ' +
                                          CoreSession
                                              .currentOperator['currencyCode'],
                                      style:
                                          Theme.of(context).textTheme.bodyText1,
                                    ),
                                ],
                              ),
                            ],
                          ),
                        ),

                      ],
                    )),
              ),
            ],
          ),
        ),
        if (!this.widget.IsPreviewList)
        ExpansionTile(
          title: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text("net-total".tr,style:
              TextStyle(color: Colors.black, fontSize: Variables.headline2FontSize),),
              Spacer(),
              Text(
                this.widget.itemList[index]['netAmountString']?? '0.00',
                style: TextStyle(
                    fontSize: Variables.headline2FontSize,
                    fontWeight: FontWeight.bold,
                    color: Colors.black),
              ),
            ],
          ),
          children: <Widget>[
            ListTile(
                title: Column(
                  children: [
                    Row(
                      children: [
                        Text("gross".tr,style:
                        TextStyle(color: Colors.black, fontSize: Variables.headline2FontSize),),
                        Spacer(),
                        Text(
                          this.widget.itemList[index]['netAmountString'] ?? '0.00',
                          style: TextStyle(
                              fontSize: Variables.headline2FontSize,
                              color: Colors.black),
                        ),
                      ],
                    ),
                    SizedBox(height: 5,),
                    Row(
                      children: [
                        Text("taxTotal".tr,style:
                        TextStyle(color: Colors.black, fontSize: Variables.headline2FontSize),),
                        Spacer(),
                        Text(
                          this.widget.itemList[index]['calculatedTax'].toStringAsFixed(CoreSession.numberOfDigits),
                          style: TextStyle(
                              fontSize: Variables.headline2FontSize,
                              color: Colors.black),
                        ),
                      ],
                    ),
                    SizedBox(height: 5,),
                    Row(
                      children: [
                        Text("total_discount".tr,style:
                        TextStyle(color: Colors.black, fontSize: Variables.headline2FontSize),),
                        Spacer(),
                        Text(
                          this.widget.itemList[index]['discount'].toStringAsFixed(CoreSession.numberOfDigits),
                          style: TextStyle(
                              fontSize: Variables.headline2FontSize,
                              color: Colors.black),
                        ),
                      ],
                    ),
                    SizedBox(height: 5,),

                    Row(
                      children: [
                        Text("net-total".tr,style:
                        TextStyle(color: Colors.black, fontSize: Variables.headline2FontSize),),
                        Spacer(),
                        Text(
                          this.widget.itemList[index]['netAmountString'] ?? '0.00',
                          style: TextStyle(
                              fontSize: Variables.headline2FontSize,
                              color: Colors.black),
                        ),
                      ],
                    ),
                  ],
                )),
          ],
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 14.0),
          child: Divider(
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomSheet: widget.netTotal > 0
          ? Directionality(
              textDirection: CoreSession.selectedLanguageId == 2 ? TextDirection.rtl : TextDirection.ltr,
              child: Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SizedBox(width: 30,),
                    Expanded(
                      child: Container(
                        height: 50,
                        child: Column(
                          children: [
                            Row(
                              children: [
                                Text('order-summary'.tr, style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.bold)),
                              ],
                            ),
                            SizedBox(height: 10,),
                            Row(
                              children: [
                                Text('total'.tr, style: TextStyle(fontSize: 16.0)),
                                Text(" : "),
                                Spacer(),
                                Text(
                                    widget.netTotal
                                        .toStringAsFixed(CoreSession.numberOfDigits),
                                    style: TextStyle(fontSize: 16.0)),
                                SizedBox(width: 30,)
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),

                  ],
                ),
              ),
            )
          : null,
      body: this.widget.itemList.length > 0
          ? Container(
              child: Column(
                children: [
                  Expanded(
                    child: ListView.builder(
                      itemBuilder: (ctx, index) {
                        return CustomerAppSettingsModel.showItemsDocument
                            ? Slidable(
                                child: itemCardWidget(index),
                                endActionPane: ActionPane(
                                  motion: DrawerMotion(),
                                  children: [
                                    SlidableAction(
                                      backgroundColor:
                                          Color.fromARGB(255, 255, 255, 255),
                                      foregroundColor: Variables.color_primary,
                                      icon: Icons.info,
                                      onPressed: (BuildContext context) {
                                        onPresentItemInfo(this
                                            .widget
                                            .itemList[index]["itemId"]);
                                      },
                                    ),
                                  ],
                                ),
                              )
                            : itemCardWidget(index);
                      },
                      itemCount: this.widget.itemList.length,
                    ),
                  ),
                ],
              ),
            )
          : NoDataWidget(),
    );
  }
}
