import 'package:after_layout/after_layout.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:diplomaticquarterapp/core/enum/PaymentOptions.dart';
import 'package:diplomaticquarterapp/core/model/ResponseModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/AddProductToCartRequestModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/OffersCategoriesRequestModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/OffersProductsRequestModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/order_model_view_model.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/packages_offers/ClinicOfferAndPackagesPage.dart';
import 'package:diplomaticquarterapp/pages/packages_offers/OfferAndPackageDetailPage.dart';
import 'package:diplomaticquarterapp/pages/packages_offers/PackageOrderCompletedPage.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/screens/pharmacy-terms-conditions-page.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart' as utils;
import 'package:diplomaticquarterapp/widgets/Loader/gif_loader_container.dart';
import 'package:diplomaticquarterapp/widgets/carousel_indicator/carousel_indicator.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/loadings/ShimmerLoading.dart';
import 'package:diplomaticquarterapp/widgets/offers_packages/PackagesCartItemCard.dart';
import 'package:diplomaticquarterapp/widgets/offers_packages/PackagesOfferCard.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_material_pickers/flutter_material_pickers.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

dynamic languageID;
const _columnCount = 1;

AnimationController _animationController;

class PackagesCartPage extends StatefulWidget {
  PackagesCartPage();

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

class _PackagesCartPageState extends State<PackagesCartPage>
    with AfterLayoutMixin<PackagesCartPage>, SingleTickerProviderStateMixin {
  getLanguageID() async {
    languageID = await sharedPref.getString(APP_LANGUAGE);
  }

  @override
  void initState() {
    _agreeTerms = false;
    _selectedPaymentMethod = null;
    _animationController =
        AnimationController(vsync: this, duration: Duration(seconds: 500));
    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    viewModel.cartItemList.clear();
    super.dispose();
  }

  PackagesViewModel viewModel;

  bool loadWidgets = false;

  onTermsClick(bool isAgree) {
    setState(() => _agreeTerms = isAgree);
  }

  onTermsInfoClick() {
    Navigator.push(context, FadePage(page: PharmacyTermsConditions()));
  }

  onPayNowClick() async {
    await viewModel.service
        .placeOrder(
            context: context,
            paymentOption: _selectedPaymentMethod.toUpperCase())
        .then((orderId) {
      if (orderId.runtimeType == int) {
        // result ==  order_id
        var browser = MyInAppBrowser(
            context: context,
            onExitCallback: (data, isDone) => paymentClosed(
                orderId: orderId, withStatus: isDone, data: data));
        browser.openPackagesPaymentBrowser(
            customer_id: viewModel.service.customer.id, order_id: orderId);
      } else {
        utils.Utils.showErrorToast(
            'Failed to place order, please try again later');
      }
    }).catchError((error) {
      utils.Utils.showErrorToast(error);
    });
  }

  @override
  void afterFirstLayout(BuildContext context) {
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<PackagesViewModel>(
        allowAny: true,
        onModelReady: (model) => viewModel = model,
        builder: (_, model, wi) {
          return AppScaffold(
            appBarTitle: TranslationBase.of(context).offerAndPackages,
            isShowAppBar: true,
            isPharmacy: false,
            showPharmacyCart: false,
            showHomeAppBarIcon: false,
            isOfferPackages: true,
            showOfferPackagesCart: false,
            isShowDecPage: false,
            body: Column(
              children: [
                Expanded(
                  child: Padding(
                      padding: const EdgeInsets.all(5),
                      child: StaggeredGridView.countBuilder(
                        crossAxisCount: (_columnCount * _columnCount),
                        itemCount: viewModel.cartItemList.length,
                        itemBuilder: (BuildContext context, int index) {
                          var item = viewModel.cartItemList[index];
                          return Dismissible(
                              key: Key(index.toString()),
                              direction: DismissDirection.startToEnd,
                              background: _cartItemDeleteContainer(),
                              secondaryBackground: _cartItemDeleteContainer(),
                              confirmDismiss: (direction) async {
                                bool status = await viewModel.service
                                    .deleteProductFromCart(item.id,
                                        context: context, showLoading: false);
                                return status;
                              },
                              onDismissed: (direction) {
                                debugPrint('Index: $index');
                                viewModel.cartItemList.removeAt(index);
                              },
                              child: PackagesCartItemCard(
                                itemModel: item,
                                shouldStepperChangeApply: (apply, total) async {
                                  var request = AddProductToCartRequestModel(
                                      product_id: item.productId,
                                      quantity: apply);
                                  ResponseModel response = await viewModel
                                      .service
                                      .addProductToCart(request,
                                          context: context, showLoading: false)
                                      .catchError((error) {
                                    utils.Utils.showErrorToast(error);
                                  });
                                  return response.status ?? false;
                                },
                              ));
                        },
                        staggeredTileBuilder: (int index) =>
                            StaggeredTile.fit(_columnCount),
                        mainAxisSpacing: 0,
                        crossAxisSpacing: 10,
                      )),
                ),
                Container(
                  height: 0.25,
                  color: Theme.of(context).primaryColor,
                ),
                Container(
                  color: Colors.white,
                  child: Column(
                    children: [
                      Texts(TranslationBase.of(context).selectPaymentOption,
                          fontSize: 10, fontWeight: FontWeight.bold),
                      Container(
                        height: 0.25,
                        width: 100,
                        color: Colors.grey[300],
                      ),
                      _paymentOptions(context, (paymentMethod) {
                        setState(() => _selectedPaymentMethod = paymentMethod);
                      }),
                      Container(
                        height: 0.25,
                        color: Colors.grey[300],
                      ),
                      Container(
                          height: 40,
                          child: _termsAndCondition(context,
                              onSelected: onTermsClick,
                              onInfoClick: onTermsInfoClick)),
                      Container(
                        height: 0.25,
                        color: Colors.grey[300],
                      ),
                      _payNow(context, onPayNowClick: onPayNowClick)
                    ],
                  ),
                )
              ],
            ),
          );
        });
  }

  fetchData() async {
    await viewModel.service.cartItems(context: context).catchError((error) {});
    setState(() {});
  }

  paymentClosed(
      {@required int orderId, @required bool withStatus, dynamic data}) async {
    viewModel.service.getOrderById(orderId, context: context).then((value) {
      var heading = withStatus ? "Success" : "Failed";
      var title = "Your order has been placed successfully";
      var subTitle = "Order# ${value.data.customOrderNumber}";
      Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => PackageOrderCompletedPage(
              heading: heading, title: title, subTitle: subTitle)));
    }).catchError((error) {
      debugPrint(error);
    });
  }
}

// /* Payment Footer Widgets */
// ---------------------------
String _selectedPaymentMethod;
Widget _paymentOptions(BuildContext context, Function(String) onSelected) {
  double height = 30;

  Widget buttonContent(bool isSelected, String imageName) {
    return Container(
        decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: isSelected ? Colors.green[50] : Colors.grey[200],
                blurRadius: 1,
                spreadRadius: 2,
              ),
            ],
            borderRadius: BorderRadius.all(Radius.circular(5)),
            border: Border.all(
                color: isSelected ? Colors.green : Colors.grey,
                width: isSelected ? 1 : 0.5)),
        child: Padding(
          padding: const EdgeInsets.all(4),
          child: Image.asset('assets/images/new-design/$imageName'),
        ));
  }

  return Padding(
    padding: const EdgeInsets.all(5),
    child: Container(
      height: height,
      color: Colors.transparent,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          InkWell(
            child: buttonContent(_selectedPaymentMethod == "mada", 'mada.png'),
            onTap: () {
              onSelected("mada");
            },
          ),
          SizedBox(
            width: 5,
          ),
          InkWell(
            child: buttonContent(_selectedPaymentMethod == "visa", 'visa.png'),
            onTap: () {
              onSelected("visa");
            },
          ),
          SizedBox(
            width: 5,
          ),
          InkWell(
            child: buttonContent(
                _selectedPaymentMethod == "mastercard", 'mastercard.png'),
            onTap: () {
              onSelected("mastercard");
            },
          ),
          SizedBox(
            width: 5,
          ),
          InkWell(
            child: buttonContent(
                _selectedPaymentMethod == "installment", 'installment.png'),
            onTap: () {
              onSelected("installment");
            },
          ),
        ],
      ),
    ),
  );
}

bool _agreeTerms = false;
Widget _termsAndCondition(BuildContext context,
    {@required Function(bool) onSelected, @required VoidCallback onInfoClick}) {
  return Padding(
    padding: const EdgeInsets.all(5),
    child: Row(
      children: [
        InkWell(
          child: Icon(
            _agreeTerms
                ? Icons.check_circle
                : Icons.radio_button_unchecked_sharp,
            size: 20,
            color: _agreeTerms ? Colors.green[600] : Colors.grey[400],
          ),
          onTap: () {
            onSelected(!_agreeTerms);
          },
        ),
        Expanded(
            child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: Texts(
            TranslationBase.of(context).pharmacyServiceTermsCondition,
            fontWeight: FontWeight.normal,
            fontSize: 13,
          ),
        )),
        InkWell(
          child: Icon(
            Icons.info,
            size: 20,
            color: Colors.grey[600],
          ),
          onTap: () {
            onInfoClick();
          },
        ),
      ],
    ),
  );
}

Widget _payNow(BuildContext context, {@required VoidCallback onPayNowClick}) {
  bool isPayNowAQctive = (_agreeTerms && (_selectedPaymentMethod != null));

  return Padding(
    padding: const EdgeInsets.all(5),
    child: Container(
        child: Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Padding(
          padding: const EdgeInsets.all(5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Texts(
                  '${TranslationBase.of(context).subtotal}:    ${'999.9'} ${TranslationBase.of(context).sar}',
                  heightFactor: 1.5,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey,
                  fontSize: 8),
              Texts(
                  '${TranslationBase.of(context).vat}:   ${'14.9'} ${TranslationBase.of(context).sar}',
                  heightFactor: 1.5,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey,
                  fontSize: 8),
              Padding(
                padding: const EdgeInsets.all(3),
                child: Container(
                  height: 0.25,
                  width: 120,
                  color: Colors.grey[300],
                ),
              ),
              Texts(
                  '${TranslationBase.of(context).total}:   999.99 ${TranslationBase.of(context).sar}',
                  heightFactor: 1.5,
                  fontWeight: FontWeight.bold,
                  color: Colors.black54,
                  fontSize: 15)
            ],
          ),
        ),
        Expanded(child: Container()),
        RaisedButton(
          child: Texts(
            TranslationBase.of(context).payNow,
            fontSize: 15,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
          padding: EdgeInsets.only(top: 5, bottom: 5, left: 0, right: 0),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(5),
              side: BorderSide(
                  color: Theme.of(context).primaryColor, width: 0.5)),
          color: Theme.of(context).primaryColor,
          onPressed: isPayNowAQctive ? onPayNowClick : null,
        ),
      ],
    )),
  );
}
// -------------------

Widget _cartItemDeleteContainer() {
  _animationController.duration = Duration(milliseconds: 500);
  _animationController.repeat(reverse: true);
  return FadeTransition(
    opacity: _animationController,
    child: Padding(
      padding: const EdgeInsets.all(5),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.red,
          boxShadow: [
            BoxShadow(
              color: Colors.grey[500],
              blurRadius: 2,
              spreadRadius: 1,
            ),
          ],
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
        child: Center(
            child: Texts(
          "Deleting...",
          fontWeight: FontWeight.normal,
          fontSize: 15,
          color: Colors.white,
        )),
      ),
    ),
  );
}
