import 'package:community_material_icon/community_material_icon.dart';
import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/screens/my_order/my_order.page.dart';
import 'package:echo_app/screens/order_history/widgets/order-history-list-item.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/order.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/widgets/no_data.widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:rflutter_alert/rflutter_alert.dart';

import '../../theme/variables.dart';
class OrderHistoryPage extends StatefulWidget {
  @override
  _OrderHistoryPageState createState() => _OrderHistoryPageState();
}

class _OrderHistoryPageState extends State<OrderHistoryPage> {
  OrderService _orderService = new OrderService();
  // ignore: unused_field
  bool _isLoading = true;
  bool _sortDesc = true;
  ItemService _itemsService = new ItemService();
  var textStyle = TextStyle(fontSize: 16);
  var textStyleToDate = TextStyle(fontSize: 16, color: Colors.grey);
  var _ordersHistoryList = [];
  IconData _sortIcon = CommunityMaterialIcons.sort_calendar_ascending;
  DateTime deliveryDate = new DateTime(
      DateTime.now().year, DateTime.now().month, DateTime.now().day);

  initState() {
    populateOrderHistoryAsync(false);
    super.initState();
  }

  reSort() {
    _sortDesc = !_sortDesc;
    populateOrderHistoryAsync(true);
  }

  cancelOrderrAsync(order) async {
    EasyLoading.show(status: 'loading'.tr);
    var response = await _orderService.cancelOrder(order);
    EasyLoading.dismiss();
    if (response['status'] == GlobalErrors.Success.index) {
      populateOrderHistoryAsync(false);
    } else {
      EasyLoading.showError('error'.tr);
    }
  }

  populateOrderHistoryAsync(isResort) async {
    await populateOrderHistoryAPI(isResort);
  }

  Future<dynamic> populateOrderHistoryAPI(isResort) async {
    EasyLoading.show(status: 'loading'.tr);
    var response = await _orderService.getOrderHistory(_sortDesc);
    EasyLoading.dismiss();
    if (response['status'] == GlobalErrors.Success.index) {
      setState(() {
        _ordersHistoryList = response['data'];
        if (isResort) {
          if (_sortDesc) {
            _sortIcon = CommunityMaterialIcons.sort_calendar_ascending;
          } else {
            _sortIcon = CommunityMaterialIcons.sort_calendar_descending;
          }
        }
        this._isLoading = false;
      });
    } else {
      EasyLoading.showError('error'.tr);
    }
  }

  reOrder(order) {
    var confirmationMsg = TapPage.cartValue.value == 0 ? "reorder-confirmation" : "clear-cart-confirm";
      Alert(
        useRootNavigator: true,
        context: context,
        type: AlertType.success,
        title: "confirm".tr,
        desc: confirmationMsg.tr,
        buttons: [
          DialogButton(
            color: Colors.white,
            child: Text(
              "yes".tr,
              style: TextStyle(color: Colors.green, fontSize: 20),
            ),
            onPressed: () => {
              Navigator.of(context, rootNavigator: true).pop(),
              getOrderDetailsForReOrderAPI(order)
            },
            width: 120,
          ),
          DialogButton(
            color: Colors.white,
            child: Text(
              "no".tr,
              style: TextStyle(color: Colors.red, fontSize: 20),
            ),
            onPressed: () => {Navigator.of(context, rootNavigator: true).pop()},
            width: 120,
          )
        ],
      ).show();

  }

  Future<dynamic> getOrderDetailsForReOrderAPI(order) async {
    EasyLoading.show(status: 'loading'.tr);
    var response =
        await _orderService.getOrderDetailsForReorder(order['orderId']);
    EasyLoading.dismiss();
    if (response['status'] == GlobalErrors.Success.index) {
      var soldItems = response['data'];
      if(soldItems.length == 0){
        CoreSession.showToast("reorder-no-Stock");
        return;
      }
      setState(() {
        double netTotal = 0;
        double gross = 0;
        for (var i = 0; i < soldItems.length; i++) {
          gross = (soldItems[i]['price'] * soldItems[i]['requiredQty']);
          soldItems[i]['netTotal'] = gross +  (gross * (soldItems[i]['tax'] / 100));

          netTotal += soldItems[i]['netTotal'];
          soldItems[i]['netAmount'] = soldItems[i]['netTotal'];
        }
        this._itemsService.updateBasket(soldItems, netTotal);
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => MyOrderPage()),
        );
      });
    } else {
      EasyLoading.showError('error'.tr);
    }
  }

  void getOrderDetailsForView(index) async {
    await getOrderDetailsForViewAPI(index);
  }

  Future<dynamic> getOrderDetailsForViewAPI(index) async {
    EasyLoading.show(status: 'loading'.tr);
    var response = await _orderService
        .getOrderDetailsForView(_ordersHistoryList[index]['orderId']);
    EasyLoading.dismiss();
    if (response['status'] == GlobalErrors.Success.index) {
      setState(() {
        var soldItems = response['data']['soldItems'];
        var promotedItems = response['data']['promotedItems'];
        var orderNote = response['data']['notes'];
        var summaryDataList = [
          {
            'netTotal': response['data']['netTotal'],
            'grossTotal': response['data']['grossTotal'],
            'calculatedTotalTax': response['data']['taxTotal'],
            'calculatedTotalDiscount': response['data']['discountTotal'],
            'calculatedDiscountTotalBeforFirstUserDiscount': response['data']
                ['discountTotal']
          }
        ];

        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => OrderSummeryPage(
              true,
              _ordersHistoryList[index]['statusId'] == 9 ? true : false,
              summaryDataList,
              soldItems,
			  [], //this.achivements
              promotedItems,
              () {},
              this.deliveryDate, orderNote, 0),
          ),
        );
      });
    } else {
      EasyLoading.showError('error'.tr);
    }
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
         backgroundColor: Variables.color_primary,
          title: Text("orders-history".tr),
          automaticallyImplyLeading: false,
          actions: <Widget>[
            IconButton(icon: Icon(_sortIcon), onPressed: reSort),
            IconButton(
                icon: Icon(Icons.close),
                onPressed: () {
                  Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(builder: (context) => TapPage()),
                  );
                }),
          ]),
      body: SafeArea(
        child: Container(
          height: size.height,
          child: _ordersHistoryList.length > 0
              ? ListView.builder(
                  itemBuilder: (ctx, index) {
                    return Container(
                        child: GestureDetector(
                            onTap: () {
                              getOrderDetailsForViewAPI(index);
                            },
                            child: OrderHistoryListItem(_ordersHistoryList[index],
                                reOrder, cancelOrderrAsync)));
                  },
                  itemCount: _ordersHistoryList.length)
              : NoDataWidget(),
        ),
      ),
    );
  }
}
