import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/order_detail.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/orders_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/order_model_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/pharmacy/order/Order.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets//pharmacy/product_tile.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/image.dart' as flutterImage;
import 'package:flutter_svg/flutter_svg.dart';

dynamic languageID;

class OrderDetailsPage extends StatefulWidget {
  Orders orderModel;

  OrderDetailsPage({@required this.orderModel});

  //  Orders orderModel;
//  OrderModel orderModelDetails;
//  OrderDetailsPage({@required this.orderModel, this.orderModelDetails});

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

class _OrderDetailsPageState extends State<OrderDetailsPage> {
  getLanguageID() async {
    languageID = await sharedPref.getString(APP_LANGUAGE);
  }

//  AppSharedPreferences sharedPref = AppSharedPreferences();
  String customerId;
  List<OrderDetailModel> ordersList = [];

  List<OrderDetailModel> cancelledOrderList = [];

//  String orderId="3516";
  var model;
  var isCancel = false;
  var isRefund = false;
  var isActiveDelivery = false;
  var dataIsCancel;
  var dataIsRefund;
  BuildContext context;

  MyInAppBrowser browser;

  @override
  void initState() {
    getLanguageID();
    super.initState();
//    print(widget.orderModel.orderItems.length);
    getCancelOrder(widget.orderModel.id);

    print("ID is" + widget.orderModel.id);
//    cancelOrderDetail(order)
  }

  @override
  Widget build(BuildContext context) {
    this.context = context;
    return BaseView<OrderModelViewModel>(
      onModelReady: (model) {
        model.getOrderDetails(widget.orderModel.id).then((value) {
          setState(() {
            isActiveDelivery = (value.orderStatusId == 995 &&
                (value.driverID != null && value.driverID.isNotEmpty));
          });
        });
      },
      builder: (_, model, wi) => AppScaffold(
        appBarTitle: TranslationBase.of(context).orderDetail,
        isShowAppBar: true,
        isPharmacy: true,
        baseViewModel: model,
        body: model.orderListModel.length > 0
            ? Container(
                color: Colors.white,
                child: SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.fromLTRB(10.0, 15.0, 1.0, 5.0),
                            child: Row(
                              children: <Widget>[
                                SvgPicture.asset(
                                  'assets/images/pharmacy/shipping_mark_icon.svg',
                                  width: 28,
                                  height: 28,
                                ),
                                Text(
                                  TranslationBase.of(context).shippingAddress,
                                  style: TextStyle(
                                    fontSize: 13.0,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 15.0, right: 10.0),
                            padding: EdgeInsets.only(left: 11.0, right: 11.0),
                            decoration: BoxDecoration(
                                border: Border.all(
                                  color: getStatusBackgroundColor(),
                                  style: BorderStyle.solid,
                                  width: 5.0,
                                ),
                                color: getStatusBackgroundColor(),
                                borderRadius: BorderRadius.circular(30.0)),
                            child: Text(
                              languageID == "ar"
                                  ? model.orderListModel[0].orderStatusn
                                  : model.orderListModel[0].orderStatus,
//                            TranslationBase.of(context).delivered,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 13.0,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 10.0, top: 13.0),
                        child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                "${model.orderListModel[0].shippingAddress.firstName} ${model.orderListModel[0].shippingAddress.lastName}",
                                style: TextStyle(
                                  fontSize: 15.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ]),
                      ),
                      Container(
                        margin: EdgeInsets.fromLTRB(10.0, 5.0, 1.0, 5.0),
                        child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                model.orderListModel[0].shippingAddress.address1
                                    .toString()
                                    ,
                                style: TextStyle(
                                  fontSize: 10.0,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.grey,
                                ),
                              ),
                            ]),
                      ),
                      Container(
                        margin: EdgeInsets.fromLTRB(10.0, 5.0, 1.0, 5.0),
                        child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                model.orderListModel[0].shippingAddress.address2
                                        .toString()
                                         +
                                    ' ' +
                                    model.orderListModel[0].shippingAddress
                                        .country
                                        .toString() +
                                    ' ' +
                                    model.orderListModel[0].shippingAddress
                                        .zipPostalCode
                                        .toString(),
                                style: TextStyle(
                                  fontSize: 10.0,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.grey,
                                ),
                              ),
                            ]),
                      ),
                      Container(
                        child: Row(
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.fromLTRB(10.0, 5.0, 8.0, 5.0),
                              child: SvgPicture.asset(
                                'assets/images/pharmacy/mobile_number_icon.svg',
                                height: 13,
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 5.0, bottom: 5.0),
                              child: Text(
                                model.orderListModel[0].shippingAddress
                                    .phoneNumber
                                    .toString(),
                                style: TextStyle(
                                  fontSize: 15.0,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Divider(
                        color: Colors.grey[350],
                        height: 20,
                        thickness: 1,
                        indent: 0,
                        endIndent: 0,
                      ),
                      Row(
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.fromLTRB(10.0, 10.0, 5.0, 10.0),
                            child: SvgPicture.asset(
                              'assets/images/pharmacy/shipping_truck_icon.svg',
                              height: 20,
                              width: 20,
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.all(10.0),
                            child: Text(
                              TranslationBase.of(context).shippedMethod,
                              style: TextStyle(
                                fontSize: 13.0,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          Container(
                            child: flutterImage.Image.asset(
                              model.orderListModel[0]
                                          .shippingRateComputationMethodSystemName !=
                                      "Shipping.Aramex"
                                  ? "assets/images/pharmacy_module/payment/LogoParmacyGreen.png"
                                  : "assets/images/pharmacy_module/payment/aramex_shipping_logo.png",
                              fit: BoxFit.contain,
//                        height: 100,
                              width: 100,
                            ),
                          ),
//                    Container(
//                      child: widget.orderModel
//                                  .shippingRateComputationMethodSystemName ==
//                              "Shipping.FixedOrByWeight"
//                          ? Container(
//                              margin: EdgeInsets.only(bottom: 10.0, top: 10.0),
//                              child: SvgPicture.asset(
//                                'assets/images/pharmacy_module/payment/hmg_shipping_logo.png',
//                                height: 25,
//                                width: 25,
//                              ),
//                            )
//                          : Container(
//                              margin: EdgeInsets.only(bottom: 10.0, top: 10.0),
//                              child: SvgPicture.asset(
//                                'assets/images/pharmacy_module/payment/aramex_shipping_logo.png',
//                                height: 25,
//                                width: 25,
//                              ),
//                            ),
//                    ),
                        ],
                      ),
                      Divider(
                        color: Colors.grey[350],
                        height: 20,
                        thickness: 8,
                        indent: 0,
                        endIndent: 0,
                      ),
                      Row(
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.all(10.0),
                            child: SvgPicture.asset(
                              'assets/images/pharmacy/credit_card_icon.svg',
                              height: 20,
                              width: 20,
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(bottom: 10.0, top: 10.0),
                            child: Text(
                              model.orderListModel[0].paymentName
                                  .toString()
                                  .substring(12),
                              style: TextStyle(
                                fontSize: 13.0,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Colors.grey[350],
                        height: 20,
                        thickness: 8,
                        indent: 0,
                        endIndent: 0,
                      ),
                      Container(
                        padding: EdgeInsets.only(bottom: 15.0),
                        margin: EdgeInsets.only(left: 10.0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              TranslationBase.of(context).orderDetail,
                              style: TextStyle(
                                fontSize: 15.0,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                      ListView.builder(
                          scrollDirection: Axis.vertical,
                          shrinkWrap: true,
                          physics: ScrollPhysics(),
                          itemCount: model.orderListModel[0].orderItems.length,
                          itemBuilder: (context, index) {
                            return Container(
                              child: productTile(
                                productName: model.orderListModel[0].orderItems[index].product.name.toString(),
                                productPrice: model.orderListModel[0].orderItems[index].product.price.toString(),
                                productRate: model.orderListModel[0].orderItems[index].product.approvedRatingSum.toDouble(),
                                productReviews: model.orderListModel[0].orderItems[index].product.approvedTotalReviews,
                                totalPrice: "${(model.orderListModel[0].orderItems[index].product.price * model.orderListModel[0].orderItems[index].quantity).toStringAsFixed(2)}",
                                qyt: model.orderListModel[0].orderItems[index].quantity.toString(),
                                isOrderDetails: true,
                                imgs: model.orderListModel[0].orderItems[index].product.images != null &&
                                        model.orderListModel[0].orderItems[index].product.images.length != 0
                                    ? model.orderListModel[0].orderItems[index].product.images[0].src.toString() : null,
                                status: model.orderListModel[0].orderStatusId,
                                product: model.orderListModel[0].orderItems[index].product,
                              ),
                            );
                          }),

                      Container(
                        padding: EdgeInsets.only(bottom: 10.0),
                        margin: EdgeInsets.only(left: 10.0, top: 5.0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              TranslationBase.of(context).orderSummary,
                              style: TextStyle(
                                fontSize: 15.0,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(bottom: 10.0),
                            margin: EdgeInsets.only(top: 5.0, left: 10.0),
                            child: Text(
                              TranslationBase.of(context).subtotal,
                              style: TextStyle(
                                fontSize: 13.0,
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(bottom: 10.0),
                            margin: EdgeInsets.fromLTRB(10.0, 5.0, 5.0, 5.0),
                            child: Row(
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(right: 5.0),
                                  child: Text(
                                    TranslationBase.of(context).sar,
                                    style: TextStyle(
                                      fontSize: 13.0,
                                    ),
                                  ),
                                ),
                                Text(
                                  model.orderListModel[0].orderSubtotalExclTax
                                      .toString(),
                                  style: TextStyle(
                                    fontSize: 13.0,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(bottom: 10.0),
                            margin: EdgeInsets.only(top: 5.0, left: 10.0),
                            child: Text(
                              TranslationBase.of(context).shipping,
                              style: TextStyle(
                                fontSize: 13.0,
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(bottom: 10.0),
                            margin: EdgeInsets.fromLTRB(10.0, 5.0, 5.0, 5.0),
                            child: Row(
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(right: 5.0),
                                  child: Text(
                                    TranslationBase.of(context).sar,
                                    style: TextStyle(
                                      fontSize: 13.0,
                                    ),
                                  ),
                                ),
                                Text(
                                  model.orderListModel[0].orderShippingExclTax
                                      .toString(),
                                  style: TextStyle(
                                    fontSize: 13.0,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(bottom: 10.0),
                            margin: EdgeInsets.only(top: 5.0, left: 10.0),
                            child: Text(
                              TranslationBase.of(context).vat,
                              style: TextStyle(
                                fontSize: 13.0,
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(bottom: 10.0),
                            margin: EdgeInsets.fromLTRB(10.0, 5.0, 5.0, 5.0),
                            child: Row(
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(right: 5.0),
                                  child: Text(
                                    TranslationBase.of(context).sar,
                                    style: TextStyle(
                                      fontSize: 13.0,
                                    ),
                                  ),
                                ),
                                Text(
                                  model.orderListModel[0].orderTax.toString(),
                                  style: TextStyle(
                                    fontSize: 13.0,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.only(top: 5.0, left: 10.0),
                            child: Text(
                              TranslationBase.of(context).total,
                              style: TextStyle(
                                fontSize: 15.0,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.fromLTRB(10.0, 5.0, 5.0, 5.0),
                            child: Row(
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(right: 5.0),
                                  child: Text(
                                    TranslationBase.of(context).sar,
                                    style: TextStyle(
                                      fontSize: 15.0,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                                Text(
                                  model.orderListModel[0].orderTotal.toString(),
                                  style: TextStyle(
                                    fontSize: 15.0,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      model.orderListModel[0].orderStatusId == 10
                          ? InkWell(
                              onTap: () {
                                print(widget.orderModel.toString());
                                print(model.orderListModel.toString());
                                print("calc = ${5.9 * 3}");
                                // TODO MOSA
                                openPayment(
                                    model.orderListModel[0], model.user);
                              },
                              child: Container(
//                          margin: EdgeInsets.only(top: 20.0),
                                height: 50.0,
                                color: Colors.transparent,
                                child: Container(
                                  padding: EdgeInsets.only(
                                      left: 130.0, right: 130.0),
                                  decoration: BoxDecoration(
                                      border: Border.all(
                                          color: Colors.green,
                                          style: BorderStyle.solid,
                                          width: 4.0),
                                      color: Colors.green,
                                      borderRadius: BorderRadius.circular(5.0)),
                                  child: Center(
                                    child: Text(
                                      TranslationBase.of(context).payOnline,
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            )
                          : Container(),
//                getCancelOrder(canCancel, canRefund),
                      isCancel
                          ? InkWell(
                              onTap: () {
                                presentConfirmDialog(
                                    model, widget.orderModel.id);
                                //  model.orderListModel[0].id//(widget.orderModel.id));
//
                              },
                              child: Container(
//                                  padding: EdgeInsets.only(left: 13.0, right: 13.0, top: 5.0),
                                height: 50.0,
                                color: Colors.transparent,
                                child: Center(
                                  child: Text(
                                    TranslationBase.of(context).cancelOrder,
                                    style: TextStyle(
                                        color: Colors.red[900],
                                        fontWeight: FontWeight.bold,
                                        decoration: TextDecoration.underline),
                                  ),
                                ),
                              ),
                            )
                          : Container(),
                      isActiveDelivery
                          ? InkWell(
                              onTap: () {
                                // Navigator.push(
                                //   context,
                                //   MaterialPageRoute(builder: (context) => TrackDriver(order: widget.orderModel),
                                // ));
                              },
                              child: Container(
                                height: 50.0,
                                color: Colors.transparent,
                                child: Center(
                                  child: Text(
                                    TranslationBase.of(context)
                                        .trackDeliveryDriver,
                                    style: TextStyle(
                                        color: Colors.green[900],
                                        fontWeight: FontWeight.normal,
                                        decoration: TextDecoration.none),
                                  ),
                                ),
                              ),
                            )
                          : Container(),
                    ],
                  ),
                ),
              )
            : Container(),
      ),
    );
  }

  Color getStatusBackgroundColor() {
    print(widget.orderModel.orderStatusId);
//    if(orderStatus == 'delivered')
    if (widget.orderModel.orderStatusId == 30 ||
        widget.orderModel.orderStatusId == 997 ||
        widget.orderModel.orderStatusId == 994)
      return Colors.blue[700];
    else if (widget.orderModel.orderStatusId == 20 ||
        widget.orderModel.orderStatusId == 995 ||
        widget.orderModel.orderStatusId == 998 ||
        widget.orderModel.orderStatusId == 999)
      return Colors.green;
    else if (widget.orderModel.orderStatusId == 10)
      return Colors.orange[300];
    else if (widget.orderModel.orderStatusId == 40 ||
        widget.orderModel.orderStatusId == 996 ||
        widget.orderModel.orderStatusId == 200) return Colors.red[900];
  }

  getCancelOrder(dataIsCancel) {
    if (widget.orderModel.canCancel && widget.orderModel.canRefund) {
      setState(() {
        isCancel = true;
        isRefund = false;
      });
    } else if (widget.orderModel.canCancel) {
      setState(() {
        isCancel = true;
        isRefund = false;
      });
    } else if (widget.orderModel.canRefund) {
      setState(() {
        isCancel = false;
        isRefund = true;
      });
    } else {
      setState(() {
        isCancel = false;
        isRefund = false;
      });
    }
  }

//      .getCanceledOrder
  presentConfirmDialog(cancelFunction, id) {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: TranslationBase.of(context).confirmCancellation,
        okText: TranslationBase.of(context).confirm,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () =>
            cancelFunction.getCanceledOrder(id, context).then((value) {
              print(":D");
              print(value);
//          Navigator.pop(context);
              Navigator.push(
                context,
                FadePage(
                    page: OrderPage(
//                        customerID: model.ordersList[0].customerId.toString()
                        customerID: widget.orderModel.customerId.toString())),
              );
            }),
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  getCanceledOrder(order) {
    Navigator.pop(context);
    if (widget.orderModel.canCancel && widget.orderModel.canRefund == false) {
//       getCanceledOrder(order);
//        AppToast.showSuccessToast(message: "Request Sent Successfully");
//       Navigator.push(context,
//       MaterialPageRoute(builder: (context) => OrderPage()));

    }
  }

  /***
   *
   * Online payment methods
   */

  openPayment(
    OrderDetailModel order,
    AuthenticatedUser authenticatedUser,
  ) {
    browser = new MyInAppBrowser(
        onExitCallback: onBrowserExit, onLoadStartCallback: onBrowserLoadStart);

    browser.openPharmacyPaymentBrowser(
        order,
        order.orderTotal,
        'ePharmacy Order',
        order.id,
        order.billingAddress.email,
        order.customValuesXml,
        "${authenticatedUser.firstName} ${authenticatedUser.middleName} ${authenticatedUser.lastName}",
        authenticatedUser.patientID,
        authenticatedUser,
        browser);
  }

  onBrowserLoadStart(String url) {
    print("onBrowserLoadStart");
    print(url);

    MyInAppBrowser.successURLS.forEach((element) {
      if (url.contains(element)) {
        if (browser.isOpened()) browser.close();
        MyInAppBrowser.isPaymentDone = true;
        return;
      }
    });

    MyInAppBrowser.errorURLS.forEach((element) {
      if (url.contains(element)) {
        if (browser.isOpened()) browser.close();
        MyInAppBrowser.isPaymentDone = false;
        return;
      }
    });
  }

  onBrowserExit(AppoitmentAllHistoryResultList appo, bool isPaymentMade) {
    print("onBrowserExit Called!!!!");
    if (isPaymentMade) {
      AppToast.showSuccessToast(
          message: "شكراً\nPayment status for your order is Paid");
      Navigator.pop(context);
      Navigator.pop(context);
    } else {
      AppToast.showErrorToast(
          message:
              "Transaction Failed!\Your transaction is field to some reason please try again or contact to the administration");
    }
  }
}
