import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/Addresses.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/OrderPreviewViewModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/screens/pharmacy-terms-conditions-page.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/widgets/ProductOrderItem.dart';
import 'package:diplomaticquarterapp/pages/pharmacy/order/Order.dart';
import 'package:diplomaticquarterapp/pages/pharmacy/pharmacyAddresses/PharmacyAddresses.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/buttons/GestureIconButton.dart';
import 'package:diplomaticquarterapp/widgets/buttons/custom_text_button.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/others/network_base_view.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class CartOrderPage extends StatefulWidget {
  final Function(int) changeTab;

  const CartOrderPage({Key key, this.changeTab}) : super(key: key);

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

class _CartOrderPageState extends State<CartOrderPage> {
  bool isLoading = true;
  String customerId;
  String customerGUID;

  @override
  void initState() {
    super.initState();
    getCustomer();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    OrderPreviewViewModel model = Provider.of(context);

    final height = mediaQuery.size.height - 60 - mediaQuery.padding.top;
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).shoppingCart,
      isShowAppBar: true,
      isPharmacy: true,
      showHomeAppBarIcon: false,
      isShowDecPage: false,
      isMainPharmacyPages: true,
      showPharmacyCart: false,
      baseViewModel: model,
      backButtonTab: () {
        widget.changeTab(0);
      },
      backgroundColor: Colors.white,
      body: NetworkBaseView(
        isLoading: isLoading,
        isLocalLoader: true,
        child: !(model.cartResponse.shoppingCarts == null || model.cartResponse.shoppingCarts.length == 0)
            ? Container(
                height: height * 0.85,
                width: double.infinity,
                child: SingleChildScrollView(
                  child: Container(
                    margin: EdgeInsets.all(10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        GestureIconButton(
                          TranslationBase.of(context).deleteAllItems,
                          Icon(
                            Icons.delete_outline_sharp,
                            color: Colors.grey.shade700,
                          ),
                          onTap: () => {model.deleteShoppingCart()},
                        ),
                        const Divider(
                          color: Color(0xFFD6D6D6),
                          height: 20,
                          thickness: 1,
                          indent: 0,
                          endIndent: 0,
                        ),
                        Container(
                          child: ListView.builder(
                              itemCount: model.cartResponse.shoppingCarts.length,
                              scrollDirection: Axis.vertical,
                              shrinkWrap: true,
                              physics: ScrollPhysics(),
                              // physics: const AlwaysScrollableScrollPhysics(),
                              itemBuilder: (context, index) {
                                return ProductOrderItem(
                                  item: model.cartResponse.shoppingCarts[index],
                                  changeCartItems: () async {
                                    GifLoaderDialogUtils.showMyDialog(context);
                                    await model.changeProductQuantity(model.cartResponse.shoppingCarts[index]);
                                    if (model.state != ViewState.Error) {}
                                    if (model.state == ViewState.ErrorLocal) {
                                      Utils.showErrorToast(model.error);
                                    }
                                    GifLoaderDialogUtils.hideDialog(context);
                                  },
                                  deleteCartItems: () async {
                                    GifLoaderDialogUtils.showMyDialog(context);
                                    await model.deleteProduct(model.cartResponse.shoppingCarts[index]).then((value) {
                                      if (model.state == ViewState.ErrorLocal) {
                                        Utils.showErrorToast(model.error);
                                      }
                                      GifLoaderDialogUtils.hideDialog(context);
                                    });
                                  },
                                  model: model,
                                );
                              }),
                        ),
                        const Divider(
                          color: Color(0xFFD6D6D6),
                          height: 20,
                          thickness: 2,
                          indent: 0,
                          endIndent: 0,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Texts(
                              TranslationBase.of(context).subtotal,
                              fontSize: 14,
                              color: Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                            Texts(
                              "${TranslationBase.of(context).sar} ${(model.cartResponse.subtotal).toStringAsFixed(2)}",
                              fontSize: 14,
                              color: Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                          ],
                        ),
                        const Divider(
                          color: Color(0xFFD6D6D6),
                          height: 20,
                          thickness: 1,
                          indent: 0,
                          endIndent: 0,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Texts(
                              "${TranslationBase.of(context).vat}",
                              fontSize: 14,
                              color: Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                            Texts(
                              "${TranslationBase.of(context).sar} ${(model.cartResponse.subtotalVatAmount).toStringAsFixed(2)}",
                              fontSize: 14,
                              color: Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                          ],
                        ),
                        const Divider(
                          color: Color(0xFFD6D6D6),
                          height: 20,
                          thickness: 1,
                          indent: 0,
                          endIndent: 0,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Texts(
                              TranslationBase.of(context).total,
                              fontSize: 14,
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                            ),
                            Texts(
                              "${TranslationBase.of(context).sar} ${(model.cartResponse.subtotalWithVat).toStringAsFixed(2)}",
                              fontSize: 14,
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                            ),
                          ],
                        ),
                        const Divider(
                          color: Color(0xFFD6D6D6),
                          height: 20,
                          thickness: 1,
                          indent: 0,
                          endIndent: 0,
                        ),
                        Image.asset(
                          "assets/images/pharmacy_module/payment.png",
                          width: mediaQuery.size.width - 20,
                          height: 30.0,
                          fit: BoxFit.scaleDown,
                        ),
                        SizedBox(
                          height: 120,
                        )
                      ],
                    ),
                  ),
                ),
              )
            : Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Image.asset(
                        'assets/images/new-design/empty_box.png',
                        width: 100,
                        height: 100,
                        fit: BoxFit.cover,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        TranslationBase.of(context).noData,
                        style: TextStyle(fontSize: 30),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(60.0, 8.0, 60.0, 0.0),
                      child: DefaultButton(
                        TranslationBase.of(context).ordersDashboard,
                        () {
                          Navigator.push(context, FadePage(page: OrderPage(customerID: customerId, customerGUID: customerGUID)));
                        },
                        color: Colors.green,
                      ),
                    ),
                  ],
                ),
              ),
      ),
      bottomSheet: Container(
        height: !(model.cartResponse.shoppingCarts == null || model.cartResponse.shoppingCarts.length == 0) ? height * 0.15 : 0,
        color: Colors.white,
        child: OrderBottomWidget(model.addresses, height, model, isLoading),
      ),
    );
  }

  getCustomer() async {
    String custID;
    String custGUID;
    custID = await sharedPref.getString(PHARMACY_CUSTOMER_ID);
    custGUID = await sharedPref.getObject(PHARMACY_CUSTOMER_GUID);
    setState(() {
      customerId = custID;
      customerGUID = custGUID;
    });
    print("customer Id is" + customerId);
    print("customer GUID is" + customerGUID);
    return customerId;
  }

  void getData() async {
    await Provider.of<OrderPreviewViewModel>(context, listen: false).getShoppingCart();
    setState(() {
      isLoading = false;
    });
  }
}

class OrderBottomWidget extends StatefulWidget {
  final List<Addresses> addresses;
  final double height;
  final OrderPreviewViewModel model;
  final bool isLoading;

  OrderBottomWidget(this.addresses, this.height, this.model, this.isLoading);

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

class _OrderBottomWidgetState extends State<OrderBottomWidget> {
  bool isAgree = false;

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectProvider = Provider.of(context);

    return !widget.isLoading && !(widget.model.cartResponse.shoppingCarts == null || widget.model.cartResponse.shoppingCarts.length == 0)
        ? Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Divider(
                color: Color(0xFFD6D6D6),
                height: 1,
                thickness: 1,
                indent: 0,
                endIndent: 0,
              ),
              Container(
                height: widget.height * 0.070,
                color: Color(0xffe6ffe0),
                padding: EdgeInsets.only(left: 15.0, right: 15.0),
                child: Row(
                  children: [
                    InkWell(
                      onTap: () {
                        setState(() {
                          isAgree = !isAgree;
                        });
                      },
                      child: Container(
                        width: 25.0,
                        height: widget.height * 0.070,
                        decoration: new BoxDecoration(
                          color: !isAgree ? Color(0xffeeeeee) : Colors.green,
                          shape: BoxShape.circle,
                        ),
                        child: !isAgree
                            ? null
                            : Padding(
                                padding: const EdgeInsets.all(0.0),
                                child: Icon(
                                  Icons.check,
                                  color: Colors.white,
                                  size: 25,
                                ),
                              ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 4),
                        margin: const EdgeInsets.symmetric(vertical: 4),
                        child: Texts(
                          TranslationBase.of(context).pharmacyServiceTermsCondition,
                          fontSize: 13,
                          color: Colors.grey.shade800,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ),
                    InkWell(
                      onTap: () => {Navigator.push(context, FadePage(page: PharmacyTermsConditions()))},
                      child: Container(
                        child: Icon(
                          Icons.info,
                          size: 25,
                          color: Color(0xFF4CAF50),
//                          color: Color(0xff005aff),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                height: widget.height * 0.065,
                margin: EdgeInsets.only(top: 5.0, bottom: 5.0),
                padding: EdgeInsets.only(left: 20.0, right: 20.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(horizontal: 0, vertical: 0),
                            child: Row(
                              children: [
                                Texts(
                                  "${TranslationBase.of(context).sar} ${(widget.model.cartResponse.subtotalWithVat).toStringAsFixed(2)}",
                                  fontSize: projectProvider.isArabic ? 12 : 14,
                                  fontWeight: FontWeight.bold,
                                ),
                                Padding(
                                  padding: const EdgeInsets.symmetric(horizontal: 4),
                                  child: Texts(
                                    "${TranslationBase.of(context).inclusiveVat}",
                                    fontSize: 8,
                                    color: Colors.grey,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Texts(
                            "${widget.model.cartResponse.quantityCount} ${TranslationBase.of(context).items}",
                            fontSize: 10,
                            color: Colors.grey,
                            fontWeight: FontWeight.bold,
                          ),
                        ],
                      ),
                    ),
                    CustomTextButton(
                      backgroundColor: Color(0xFF4CAF50),
                      disabledForegroundColor: Color(0xFF848484).withOpacity(0.38),
                      disabledBackgroundColor: Color(0xFF848484).withOpacity(0.12),
                      onPressed: isAgree
                          ? () => {
                                if (widget.model.isCartItemsOutOfStock())
                                  {AppToast.showErrorToast(message: TranslationBase.of(context).outOfStockMsg)}
                                else
                                  {_navigateToAddressPage(projectProvider.user.patientIdentificationNo)}
                              }
                          : null,
                      child: new Text(
                        "${TranslationBase.of(context).checkOut}",
                        style: new TextStyle(color: isAgree ? Colors.white : Colors.grey.shade300, fontSize: 14),
                      ),

//                      disabledColor: Color(0xff005aff),
                    )
                  ],
                ),
              ),
            ],
          )
        : Container();
  }

  _navigateToAddressPage(String identificationNo) {
    Navigator.push(
        context,
        FadePage(
            page: PharmacyAddressesPage(
          orderPreviewViewModel: widget.model,
          isShippingAddress: true,
        ))).then((result) async {
      if (result != null) {
        GifLoaderDialogUtils.showMyDialog(context);
        var address = result;
        widget.model.paymentCheckoutData.address = Addresses.fromJson(address.toJson());
        await widget.model.getInformationsByAddress(identificationNo);
        await widget.model.getShoppingCart();
        // widget.changeMainState();
        GifLoaderDialogUtils.hideDialog(context);
      }
    });
  }
}
