import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/PharmacyProduct.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/product_detail_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/screens/product-details/product-name-and-price.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/screens/product-details/reviews_info.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/screens/product-details/shared/custom-divider.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.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/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'availability_info.dart';
import 'details_info.dart';
import 'discount_description.dart';
import 'footor/footer-widget.dart';
import 'shared/product_details_app_bar.dart';

String itemID;
PharmacyProduct specificationData;

class ProductDetailPage extends StatefulWidget {
  final PharmacyProduct product;

  ProductDetailPage(this.product);

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

class __ProductDetailPageState extends State<ProductDetailPage> {
  AppSharedPreferences sharedPref = AppSharedPreferences();

  bool isTrue = true;
  bool isDetails = true;
  bool isReviews = false;
  bool isAvailability = false;
  String customerId;
  bool isSelected = true;
  bool isOverQuantity = false;
  bool isInWishList = false;
  int quantity = 0;

  checkWishlist() async {
    GifLoaderDialogUtils.showMyDialog(context);
    ProductDetailViewModel model = new ProductDetailViewModel();
    await model.checkWishlistData();

    for (int i = 0; i < model.wishListItems.length; i++) {
      if (itemID == model.wishListItems[i].product.id) {
        isInWishList = true;
        break;
      } else {
        isInWishList = false;
      }
    }
    GifLoaderDialogUtils.hideDialog(context);
    setState(() {});
  }

  void initState() {
    quantity = 1;
    specificationData = widget.product;

    userInfo();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void userInfo() async {
    print(specificationData);
    customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID);
    if (customerId != null) {
      itemID = widget.product.id;
      checkWishlist();
    }
    setState(() {});
  }

  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return BaseView<ProductDetailViewModel>(
        allowAny: true,
        onModelReady: (model) async {
          await model.getProductReviewsData(widget.product.id).then((value) {});
        },
        builder: (_, model, wi) => AppScaffold(
              appBarTitle: TranslationBase.of(context).productDetails,
              isShowAppBar: true,
              isPharmacy: true,
              isShowDecPage: false,
              customAppBar: ProductAppBar(
                product: widget.product,
                quantity: quantity,
                model: model,
                addToWishlistFunction: () async {
                  await addToWishlistFunction(itemID: itemID, model: model);
                },
                deleteFromWishlistFunction: () async {
                  await deleteFromWishlistFunction(itemID: itemID, model: model);
                },
                isInWishList: isInWishList,
                addToCartFunction: addToCartFunction,
              ),
              body: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      width: double.infinity,
                      color: Colors.white,
                      child: Column(
                        children: [
                          if (widget.product.images.isNotEmpty)
                            Stack(
                              children: [
                                Container(
                                  height: MediaQuery.of(context).size.height * .40,
                                  child: Center(
                                    child: Image.network(
                                      widget.product.images[0].src.trim(),
                                      fit: BoxFit.contain,
                                    ),
                                  ),
                                ),
                                if (model.isStockAvailable != null && !model.isStockAvailable)
                                  Container(
                                    height: MediaQuery.of(context).size.height * .40,
                                    color: Colors.white.withOpacity(0.6),
                                    // child: AppText("Out of Stock"),
                                  ),
                                if (model.isStockAvailable != null && !model.isStockAvailable)
                                  Positioned(
                                    // bottom: 10,
                                    top: MediaQuery.of(context).size.height * .088,
                                    left: MediaQuery.of(context).size.width * .32,
                                    child: Center(
                                      child: Container(
                                        height: MediaQuery.of(context).size.height * .40,
                                        // color: Colors.white.withOpacity(0.75),
                                        child: RotationTransition(
                                            turns: new AlwaysStoppedAnimation(310 / 360),
                                            child: AppText(
                                              TranslationBase.of(context).productOutOfStock,
                                              color: Color(0xFF000000).withOpacity(0.19),
                                              fontSize: projectViewModel.isArabic ? 40 : 50,
                                              fontWeight: FontWeight.bold,
                                            )),
                                      ),
                                    ),
                                  ),
                              ],
                            ),
                          if (widget.product.discountDescription != null) DiscountDescription(product: widget.product)
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 4,
                    ),
                    Container(
                      color: Colors.white,
                      child: ProductNameAndPrice(
                        context,
                        widget.product,
                        customerId: customerId,
                        addToWishlistFunction: (item) {
                          addToWishlistFunction(itemID: item, model: model);
                          setState(() {});
                        },
                        deleteFromWishlistFunction: (item) {
                          deleteFromWishlistFunction(itemID: item, model: model);
                          setState(() {});
                        },
                        notifyMeWhenAvailable: (context, itemId) {
                          notifyMeWhenAvailable(itemId: itemId, customerId: customerId, model: model);
                        },
                        isInWishList: isInWishList,
                        isStockAvailable: model.isStockAvailable,
                        stockAvailability: projectViewModel.isArabic ? model.stockAvailabilityn : model.stockAvailability,
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
//                    Container(
//                      color: Colors.white,
//                      child: Column(
//                        mainAxisAlignment: MainAxisAlignment.start,
//                        crossAxisAlignment: CrossAxisAlignment.start,
//                        children: [
//                          Container(
//                            padding: EdgeInsets.symmetric(vertical: 15, horizontal: 10),
//                            child: Texts(
//                              TranslationBase.of(context).specification,
//                              fontSize: 15,
//                              fontWeight: FontWeight.bold,
//                            ),
//                            width: double.infinity,
//                          ),
//                          // Divider(color: Colors.grey),
//                        ],
//                      ),
//                    ),
//                    SizedBox(
//                      height: 6,
//                    ),
                    Container(
                      // width: 500,
                      margin: EdgeInsets.only(bottom: 10),
                      padding: EdgeInsets.only(bottom: 10),
                      color: Colors.white,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Column(
                                children: [
                                  FlatButton(
                                    onPressed: () {
                                      setState(() {
                                        isDetails = true;
                                        isReviews = false;
                                        isAvailability = false;
                                      });
                                    },
                                    child: Text(
                                      TranslationBase.of(context).details,
                                      style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14, letterSpacing: -0.84),
                                    ),
                                    color: Colors.white,
                                  ),
                                  CustomDivider(
                                    color: isDetails ? Colors.green : Colors.transparent,
                                  )
                                ],
                              ),
                              SizedBox(
                                width: 20,
                              ),
                              Column(
                                children: [
                                  FlatButton(
                                    onPressed: () async {
                                      if (widget.product.approvedTotalReviews > 0) {
                                        GifLoaderDialogUtils.showMyDialog(context);
                                        await model.getProductReviewsData(widget.product.id);
                                        GifLoaderDialogUtils.hideDialog(context);
                                      } else {
                                        model.clearReview();
                                      }
                                      setState(() {
                                        isDetails = false;
                                        isReviews = true;
                                        isAvailability = false;
                                      });
                                    },
                                    child: Text(
                                      TranslationBase.of(context).reviews,
                                      style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14, letterSpacing: -0.84),
                                    ),
                                    color: Colors.white,
                                  ),
                                  CustomDivider(
                                    color: isReviews ? Colors.green : Colors.transparent,
                                  ),
                                ],
                              ),
                              SizedBox(
                                width: 20,
                              ),
                              Column(
                                children: [
                                  FlatButton(
                                    onPressed: model.isStockAvailable != null && model.isStockAvailable
                                        ? () async {
                                            GifLoaderDialogUtils.showMyDialog(context);
                                            await model.getProductLocationData(widget.product.sku);
                                            GifLoaderDialogUtils.hideDialog(context);
//
                                            setState(() {
                                              isDetails = false;
                                              isReviews = false;
                                              isAvailability = true;
                                            });
                                          }
                                        : null,
                                    child: Text(
                                      TranslationBase.of(context).availability,
                                      style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14, letterSpacing: -0.84),
                                    ),
                                    color: Colors.white,
                                  ),
                                  CustomDivider(
                                    color: isAvailability ? Colors.green : Colors.transparent,
                                  ),
                                ],
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          isDetails
                              ? DetailsInfo(
                                  product: widget.product,
                                )
                              : isReviews
                                  ? ReviewsInfo(
                                      product: widget.product,
                                      previousModel: model,
                                    )
                                  : isAvailability
                                      //&& widget.product.stockAvailability != "Out of stock"
                                      ? AvailabilityInfo(previousModel: model)
//                                      : isAvailability && widget.product.stockAvailability == "Out of stock"
//                                          ? Container(
//                                              //   padding: EdgeInsets.all(15),
//                                              padding: EdgeInsets.fromLTRB(15, 15, 15, 20),
//                                              margin: EdgeInsets.only(bottom: 20),
//                                              alignment: Alignment.center,
//                                              child: Text(
//                                                TranslationBase.of(context).noLocationAvailable,
//                                              ),
//                                            )
                                      : Container(),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
//                    if (projectViewModel.isLogin)
//                      RecommendedProducts(
//                        product: widget.product,
//                        productDetailViewModel: model,
//                        addToWishlistFunction: (itemID) async {
//                          await addToWishlistFunction(itemID: itemID, model: model);
//                        },
//                        deleteFromWishlistFunction: (itemID) async {
//                          await deleteFromWishlistFunction(itemID: itemID, model: model);
//                        },
//                      )
                  ],
                ),
              ),
              // : AppCircularProgressIndicator(),
              bottomSheet: model.state == ViewState.Idle || model.state == ViewState.ErrorLocal
                  ? FooterWidget(
                      model.isStockAvailable,
                      widget.product.orderMaximumQuantity,
                      widget.product.orderMinimumQuantity,
                      model.stockQuantity,
                      widget.product,
                      quantity: quantity,
                      isOverQuantity: isOverQuantity,
                      addToCartFunction: addToCartFunction,
                      addToShoppingCartFunction: addToShoppingCartFunction,
                      model: model,
                    )
                  : SizedBox(),
            ));
  }

  addToShoppingCartFunction({quantity, itemID, ProductDetailViewModel model}) async {
    GifLoaderDialogUtils.showMyDialog(context);
    await model.addToCartData(quantity, itemID, context);
    GifLoaderDialogUtils.hideDialog(context);
    if (model.state != ViewState.ErrorLocal) Utils.navigateToCartPage();
  }

  addToWishlistFunction({itemID, ProductDetailViewModel model}) async {
    isInWishList = true;
    await model.addToWishlistData(itemID, context);
    setState(() {});
  }

  deleteFromWishlistFunction({itemID, ProductDetailViewModel model}) async {
    isInWishList = false;
    await model.deleteWishlistData(itemID, context);
    setState(() {});
  }

  addToCartFunction({
    quantity,
    itemID,
    ProductDetailViewModel model,
  }) async {
    GifLoaderDialogUtils.showMyDialog(context);
    await model.addToCartData(quantity, itemID, context);
    GifLoaderDialogUtils.hideDialog(context);
  }

  notifyMeWhenAvailable({itemId, customerId, ProductDetailViewModel model}) async {
    await model.notifyMe(customerId, itemId);
  }
}
