import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/product_detail_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacy_categorise_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/screens/cart-page/cart-order-page.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/screens/product-details/product-detail.dart';
import 'package:diplomaticquarterapp/theme/colors.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' as utils ;
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/others/StarRating.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';
import 'package:rating_bar/rating_bar.dart';

import 'base/base_view.dart';


dynamic languageID;

class FinalProductsPage extends StatefulWidget {
  final String id;
  final int productType; // 1 : default, 2 : manufacturer , 3 : recently viewed
  AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();

  FinalProductsPage({this.id, this.productType = 1});

  @override
  _FinalProductsPageState createState() => _FinalProductsPageState(id: id);
}

class _FinalProductsPageState extends State<FinalProductsPage> {
  String id;

  _FinalProductsPageState({this.id});

  String categoriseName = "Personal Care";
  String appBarTitle = "";
  bool styleOne = true;
  bool styleTwo = false;
  Icon styleIcon = Icon(
    Icons.widgets_sharp,
    color: Colors.blue,
    size: 29.0,
  );

  getLanguageID() async {
    languageID = await sharedPref.getString(APP_LANGUAGE);
  }

  void initState() {
    getLanguageID();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectProvider = Provider.of(context);
    ProjectViewModel projectViewModel = Provider.of(context);
    return BaseView<PharmacyCategoriseViewModel>(
        onModelReady: (model) {
          if (widget.productType == 1) {
            model.getFinalProducts(i: id);
            appBarTitle = TranslationBase.of(context).products;
          } else if (widget.productType == 2) {
            model.getManufacturerProducts(id);
          } else if (widget.productType == 3) {
            model.getLastVisitedProducts();
            appBarTitle = TranslationBase.of(context).recentlyViewed;
          } else if (widget.productType == 4) {
            model.getMostViewedProducts();
            appBarTitle = TranslationBase.of(context).mostViewed;
          } else if (widget.productType == 5) {
            model.getNewProducts();
            appBarTitle = TranslationBase.of(context).newProducts;
          } else {
            model.getBestSellerProducts();
            appBarTitle = TranslationBase.of(context).bestSellers;
          }
        },
        allowAny: true,
        builder: (BuildContext context, PharmacyCategoriseViewModel model, Widget child) => AppScaffold(
              isPharmacy: true,
              appBarTitle: appBarTitle,
              isBottomBar: true,
              isShowAppBar: true,
              backgroundColor: Colors.white,
              isShowDecPage: false,
              showPharmacyCart: false,
              showHomeAppBarIcon: false,
              baseViewModel: model,
              body: Container(
                height: MediaQuery.of(context).size.height * 5.87,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Texts(
                            "$appBarTitle " + TranslationBase.of(context).products,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        Row(
                          children: [
                            Container(
                              height: 44.0,
                              child: VerticalDivider(
                                color: Colors.black45,
                                thickness: 1.0,
                                //width: 0.3,
                                // indent: 0.0,
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.all(8.0),
                              child: InkWell(
                                child: styleIcon,
                                onTap: () {
                                  setState(() {
                                    if (styleOne == true) {
                                      styleOne = false;
                                      styleTwo = true;
                                      styleIcon = Icon(
                                        Icons.auto_awesome_mosaic,
                                        color: CustomColors.green,
                                        size: 29.0,
                                      );
                                    } else {
                                      styleOne = true;
                                      styleTwo = false;
                                      styleIcon = Icon(
                                        Icons.widgets_sharp,
                                        color: CustomColors.green,
                                        size: 29.0,
                                      );
                                    }
                                  });
                                },
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Divider(
                      thickness: 1.0,
                      color: Colors.grey.shade400,
                    ),
                    styleOne == true
                        ? Expanded(
                            child: model.finalProducts.length > 0
                                ? Container(
                                    height: MediaQuery.of(context).size.height * 3.90,
                                    child: GridView.builder(
                                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                        crossAxisCount: 2,
                                        crossAxisSpacing: 0.5,
                                        mainAxisSpacing: 2.0,
                                        childAspectRatio: 1.0,
                                      ),
                                      itemCount: model.finalProducts.length,
                                      itemBuilder: (BuildContext context, int index) {
                                        return NetworkBaseView(
                                            baseViewModel: model,
                                            child: InkWell(
                                              child: Card(
                                                color: model.finalProducts[index].discountName != null ? Color(0xffFFFF00) : Colors.white,
                                                elevation: 0,
                                                shape: Border(
                                                  right: BorderSide(
                                                    color: Colors.grey.shade300,
                                                    width: 1,
                                                  ),
                                                  left: BorderSide(
                                                    color: Colors.grey.shade300,
                                                    width: 1,
                                                  ),
                                                  bottom: BorderSide(
                                                    color: Colors.grey.shade300,
                                                    width: 1,
                                                  ),
                                                  top: BorderSide(
                                                    color: Colors.grey.shade300,
                                                    width: 1,
                                                  ),
                                                ),
                                                margin: EdgeInsets.symmetric(
                                                  horizontal: 8,
                                                  vertical: 4,
                                                ),
                                                child: Container(
                                                  decoration: BoxDecoration(
                                                    borderRadius: BorderRadius.only(
                                                      topLeft: Radius.circular(110.0),
                                                    ),
                                                    color: Colors.white,
                                                  ),
                                                  padding: EdgeInsets.symmetric(horizontal: 0),
                                                  width: MediaQuery.of(context).size.width / 3,
                                                  child: Column(
                                                    crossAxisAlignment: CrossAxisAlignment.start,
                                                    children: [
                                                      Stack(
                                                        children: [
                                                          Container(
                                                            margin: EdgeInsets.fromLTRB(0, 16, 0, 0),
                                                            alignment: Alignment.center,
                                                             child: (model.finalProducts[index].images != null &&
                                                                 model.finalProducts[index].images.length > 0)
                                                                 ? Image.network(
                                                               model.finalProducts[index].images[0].src,
                                                               fit: BoxFit.cover,
                                                               height: 80,
                                                               width: 80,

                                                             )
                                                                 : Image.asset(
                                                               "assets/images/no_image.png",
                                                               fit: BoxFit.cover,
                                                               height: 80,
                                                               width: 80,
                                                             ),
//                                                            Image.network(
//                                                              model.finalProducts[index].images.isNotEmpty
//                                                                  ? model.finalProducts[index].images[0].thumb
//                                                                  : 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/No_image_3x4.svg/1200px-No_image_3x4.svg.png',
//                                                              fit: BoxFit.cover,
//                                                              height: 80,
//                                                            ),
                                                          ),
                                                          Container(
                                                            width: model.finalProducts[index].rxMessage != null ? double.infinity : 0,
                                                            //MediaQuery.of(context).size.width / 2.8 : 0,
                                                            padding: EdgeInsets.all(4),
                                                            decoration: BoxDecoration(
                                                              color: Color(0xffb23838),
                                                            //  borderRadius: BorderRadius.only(topLeft: Radius.circular(6)
                                                             // ),
                                                            ),
                                                            child: model.finalProducts[index].rxMessage != null
                                                                ? Texts(
                                                                   projectProvider.isArabic ? model.finalProducts[index].rxMessagen : model.finalProducts[index].rxMessage,
                                                                    color: Colors.white,
                                                                    regular: true,
                                                                    fontSize: 10,
                                                                    fontWeight: FontWeight.w600,
                                                                  )
                                                                : Texts(""),
                                                          ),
                                                        ],
                                                      ),
                                                      Container(
                                                        margin: EdgeInsets.symmetric(
                                                          horizontal: 6,
                                                          vertical: 0,
                                                        ),
                                                        child: Column(
                                                          crossAxisAlignment: CrossAxisAlignment.start,
                                                          children: [
                                                            if (model.finalProducts[index].discountName != null)
                                                              Container(
                                                                width: double.infinity,
                                                                height: 13.0,
                                                                decoration: BoxDecoration(
                                                                  color: Color(0xff5AB145),
                                                                ),
                                                                child: Center(
                                                                  child: Texts(
                                                                    model.finalProducts[index].discountName,
                                                                    regular: true,
                                                                    color: Colors.white,
                                                                    fontSize: 10.4,
                                                                  ),
                                                                ),
                                                              ),
                                                            Texts(projectViewModel.isArabic ? model.finalProducts[index].namen : model.finalProducts[index].name,
//                                                              model.finalProducts[index].name,
                                                              regular: true,
                                                              fontSize: 12,
                                                              fontWeight: FontWeight.w400,
                                                            ),
                                                            Padding(
                                                              padding: const EdgeInsets.only(top: 4, bottom: 4),
                                                              child: Texts(
                                                                "SAR ${model.finalProducts[index].price}",
                                                                bold: true,
                                                                fontSize: 14,
                                                              ),
                                                            ),
                                                            Row(
                                                              children: [
//                                                                StarRating(
//                                                                    totalAverage: model.finalProducts[index].approvedRatingSum > 0
//                                                                        ? (model.finalProducts[index].approvedRatingSum.toDouble() / model.finalProducts[index].approvedRatingSum.toDouble()).toDouble()
//                                                                        : 0,
//                                                                    forceStars: true),
                                                                RatingBar.readOnly(
                                                                  initialRating: model.finalProducts[index].approvedRatingSum.toDouble(),
                                                                  size: 15.0,
                                                                  filledColor: Colors.yellow[700],
                                                                  emptyColor: Colors.grey[500],
                                                                  isHalfAllowed: true,
                                                                  halfFilledIcon: Icons.star_half,
                                                                  filledIcon: Icons.star,
                                                                  emptyIcon: Icons.star,
                                                                ),
                                                                Texts(
                                                                  "(${model.finalProducts[index].approvedTotalReviews})",
                                                                  regular: true,
                                                                  fontSize: 10,
                                                                  fontWeight: FontWeight.w400,
                                                                )
                                                              ],
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                              onTap: () => {
                                                Navigator.push(
                                                    context,
                                                    FadePage(
                                                      page: ProductDetailPage(model.finalProducts[index]),
                                                    )),
                                              },
                                            ));
                                      },
                                    ),
                                  )
                                : Container(
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: [
                                        Align(
                                          alignment: Alignment.center,
                                          child: Image.asset(
                                            'assets/images/pharmacy/empty_box.png',
                                            width: 100,
                                            height: 100,
                                          ),
                                        ),
                                        Text(
                                          TranslationBase.of(context).noResult,
                                          style: TextStyle(
                                            fontSize: 20.0,
//                                      fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                          )
                        : Expanded(
                            child: model.finalProducts.length > 0
                                ? Container(
                                    height: MediaQuery.of(context).size.height * 5.0,
                                    child: ListView.builder(
                                        itemCount: model.finalProducts.length,
                                        itemBuilder: (BuildContext context, int index) {
                                          return InkWell(
                                            child: Card(
                                              child: Row(
                                                children: [
                                                  Stack(
                                                    children: [
                                                      Column(
                                                        children: [
                                                          Container(
                                                            decoration: BoxDecoration(),
                                                            child: Padding(
                                                              padding: EdgeInsets.only(
                                                                left: 9.0,
                                                                top: 8.0,
                                                                right: 10.0,
                                                              ),
                                                            ),
                                                          ),
                                                          Container(
                                                            margin: EdgeInsets.fromLTRB(0, 0, 0, 8),
                                                            alignment: Alignment.center,
                                                            child:(model.finalProducts[index].images != null &&
                                                                model.finalProducts[index].images.length > 0)
                                                                ? Image.network(
                                                              model.finalProducts[index].images[0].src,
                                                              fit: BoxFit.cover,
                                                              height: 80,
                                                              width: 80,

                                                            )
                                                                : Image.asset(
                                                              "assets/images/no_image.png",
                                                              fit: BoxFit.cover,
                                                              height: 80,
                                                              width: 80,
                                                            ),
//                                                            Image.network(
//                                                              model.finalProducts[index].images.isNotEmpty
//                                                                  ? model.finalProducts[index].images[0].thumb
//                                                                  : 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/No_image_3x4.svg/1200px-No_image_3x4.svg.png',
//                                                              fit: BoxFit.contain,
//                                                              height: 80,
//                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                      Column(
                                                        children: [
                                                          Container(
                                                            width: model.finalProducts[index].rxMessage != null ? MediaQuery.of(context).size.width / 3.70 : 0,
                                                            padding: EdgeInsets.all(4),
                                                            decoration: BoxDecoration(
                                                              color: Color(0xffb23838),
                                                              //borderRadius: BorderRadius.only(topLeft: Radius.circular(5)),
                                                            ),
                                                            child:model.finalProducts[index].rxMessage != null
                                                                ? Texts(
                                                              projectProvider.isArabic ? model.finalProducts[index].rxMessagen : model.finalProducts[index].rxMessage,
                                                              color: Colors.white,
                                                              regular: true,
                                                              fontSize: 8,
                                                              fontWeight: FontWeight.w600,
                                                            )
                                                                : Texts(""),
//                                                            Texts(
//                                                              model.finalProducts[index].rxMessage != null ? model.finalProducts[index].rxMessage : "",
//                                                              color: Colors.white,
//                                                              regular: true,
//                                                              fontSize: 10,
//                                                              fontWeight: FontWeight.w600,
//                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                    ],
                                                  ),
                                                  Container(
                                                    height: 100.0,
                                                    margin: EdgeInsets.symmetric(
                                                      horizontal: 6,
                                                      vertical: 0,
                                                    ),
                                                    child: Column(
                                                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                                                      crossAxisAlignment: CrossAxisAlignment.start,
                                                      children: [
                                                        SizedBox(
                                                          height: 4.0,
                                                        ),
                                                        Container(
                                                          width: MediaQuery.of(context).size.width * 0.55,
                                                          child: Texts(projectViewModel.isArabic ? model.finalProducts[index].namen : model.finalProducts[index].name,
//                                                            model.finalProducts[index].name,
                                                            regular: true,
                                                            fontSize: 13.2,
                                                            fontWeight: FontWeight.w500,
                                                            maxLines: 5,
                                                          ),
                                                        ),
                                                        SizedBox(
                                                          height: 8.0,
                                                        ),
                                                        Padding(
                                                          padding: const EdgeInsets.only(top: 4, bottom: 4),
                                                          child: Texts(
                                                            "SAR ${model.finalProducts[index].price}",
                                                            bold: true,
                                                            fontSize: 14,
                                                          ),
                                                        ),
                                                        Row(
                                                          children: [
//                                                            StarRating(
//                                                                totalAverage: model.finalProducts[index].approvedRatingSum > 0
//                                                                    ? (model.finalProducts[index].approvedRatingSum.toDouble() / model.finalProducts[index].approvedRatingSum.toDouble()).toDouble()
//                                                                    : 0,
//                                                                forceStars: true),
                                                            RatingBar.readOnly(
                                                              initialRating: model.finalProducts[index].approvedRatingSum.toDouble(),
                                                              size: 15.0,
                                                              filledColor: Colors.yellow[700],
                                                              emptyColor: Colors.grey[500],
                                                              isHalfAllowed: true,
                                                              halfFilledIcon: Icons.star_half,
                                                              filledIcon: Icons.star,
                                                              emptyIcon: Icons.star,
                                                            ),
                                                            Texts(
                                                              "(${model.finalProducts[index].approvedTotalReviews})",
                                                              regular: true,
                                                              fontSize: 10,
                                                              fontWeight: FontWeight.w400,
                                                            )
                                                          ],
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                  widget.authenticatedUserObject.isLogin
                                                      ? Container(
                                                          child: IconButton(
                                                              icon: Icon(
                                                                Icons.shopping_cart,
                                                                size: 18,
                                                                color: CustomColors.green,
                                                              ),
                                                              onPressed: () async {
                                                                if (model.finalProducts[index].isRx == false) {
                                                                  GifLoaderDialogUtils.showMyDialog(context);
                                                                  await addToCartFunction(1, model.finalProducts[index].id);
                                                                  GifLoaderDialogUtils.hideDialog(context);
                                                                  // Navigator.push(context, FadePage(page: CartOrderPage()));
                                                                  utils.Utils.navigateToCartPage();


                                                                } else {
                                                                  AppToast.showErrorToast(message: TranslationBase.of(context).needPrescription);
                                                                }
//
                                                              }),
                                                        )
                                                      : Container(),
                                                ],
                                              ),
                                            ),
                                            onTap: () => {
                                              Navigator.push(
                                                  context,
                                                  FadePage(
                                                    page: ProductDetailPage(model.finalProducts[index]),
                                                  )),
                                            },
                                          );
                                        }),
                                  )
                                : Container(
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: [
                                        Align(
                                          alignment: Alignment.center,
                                          child: Image.asset(
                                            'assets/images/pharmacy/empty_box.png',
                                            width: 100,
                                            height: 100,
                                          ),
                                        ),
                                        Text(
                                          TranslationBase.of(context).noResult,
                                          style: TextStyle(
                                            fontSize: 20.0,
//                                      fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                          )
                  ],
                ),
              ),
            ));
  }

  addToCartFunction(quantity, itemID) async {
    ProductDetailViewModel x = new ProductDetailViewModel();
    await x.addToCartData(quantity, itemID, context);
  }
}
