import 'package:auto_size_text/auto_size_text.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/model/pharmacies/PharmacyProduct.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/pages/pharmacies/screens/product-details/product-detail.dart';
import 'package:hmg_patient_app/pages/pharmacies/screens/product-details/shared/icon_with_bg.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/data_display/text.dart';
import 'package:hmg_patient_app/widgets/others/StarRating.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';

import 'dart:math' as math;

class ProductTileItem extends StatelessWidget {
  final AppSharedPreferences sharedPref = AppSharedPreferences();
  final PharmacyProduct item;
  final double itemHeight;

  ProductTileItem(this.item, this.itemHeight);

  void productOnClick(BuildContext ctx) {
    _saveLastVisitProducts();
    Navigator.push(ctx, FadePage(page: ProductDetailPage(item)));
  }

  void _saveLastVisitProducts() async {
    String lastVisited = "";
    bool isIdExist = false;
    List items = [];
    if (await this.sharedPref.getString(PHARMACY_LAST_VISITED_PRODUCTS) !=
        null) {
      lastVisited =
          await this.sharedPref.getString(PHARMACY_LAST_VISITED_PRODUCTS);
      lastVisited.split(",").forEach((id) {
        if (id == item.id) {
          isIdExist = true;
        }
        items.add(id);
      });
    }

    if (items.length >= 15) {
      items.removeAt(0);
      // lastVisited = lastVisited.replaceFirst(RegExp('$itemToRemove'), '');
    }

    lastVisited = "";
    for (int i = items.length - 1; i >= 0; i--) {
      if (lastVisited == "") {
        // it means there is no lastVisited yet
        lastVisited = "${items[i]}";
      } else {
        // there is lastVisited id's and this product id is not found
        lastVisited += ",${items[i]}";
      }
    }

    if (!isIdExist) {
      if (lastVisited == "") {
        // it means there is no lastVisited yet
        lastVisited = "${item.id}";
      } else {
        // there is lastVisited id's and this product id is not found
        lastVisited += ",${item.id}";
      }
    }
    sharedPref.setString(PHARMACY_LAST_VISITED_PRODUCTS, lastVisited);
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectProvider = Provider.of(context);
    return InkWell(
      onTap: () => productOnClick(context),
      child: Container(
        margin: EdgeInsets.all(7),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey.shade300, width: 0.2),
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
          shape: BoxShape.rectangle,
          boxShadow: [
            BoxShadow(
              color: Color(0xffF1F1F1),
              spreadRadius: 4,
              blurRadius: 5.5,
              offset: Offset(0, 3), // changes position of shadow
            ),
          ],
        ),
        padding: EdgeInsets.symmetric(horizontal: 4),
        width: MediaQuery.of(context).size.width / 2.8,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Stack(
            //   children: [
            //     Container(
            //       margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
            //       alignment: Alignment.center,
            //       child: (item.images != null && item.images.length > 0)
            //           ? Image.network(
            //         item.images[0].src,
            //         fit: BoxFit.cover,
            //         height: itemHeight / 2,
            //       )
            //           : Image.asset(
            //         "assets/images/no_image.png",
            //         fit: BoxFit.cover,
            //         height: itemHeight / 2,
            //       ),
            //     ),
            //   ],
            // ),

            Container(
              width: double.infinity,
              height: MediaQuery.of(context).size.width * 0.3,
              padding:
                  EdgeInsets.only(left: 10, right: 10, top: 7, bottom: 3.5),
              color: Colors.white,
              child: Container(
                width: double.infinity,
                height: double.infinity,
                clipBehavior: Clip.antiAlias,
                decoration: containerRadiusWithGradientServices(0.0,
                    prescriptionRequired: item.rxMessage != null,
                    isProduct: true,
                    isEnglish: !projectProvider.isArabic,
                    lightColor: Colors.transparent,
                    darkColor: Colors.transparent),
                child: Stack(
                  children: [
                    Stack(
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            border: Border.all(
                                color: Color(0xffF0F0F0), width: 1.0),
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(
                                  item.rxMessage != null &&
                                          projectProvider.isArabic
                                      ? 20
                                      : 8),
                              bottomLeft: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                              topLeft: Radius.circular(item.rxMessage != null &&
                                      !projectProvider.isArabic
                                  ? 20
                                  : 8),
                            ),
                          ),
                          margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                          alignment: Alignment.center,
                          child: (item.images != null && item.images!.length > 0)
                              ? Padding(
                                  padding: EdgeInsets.all(12.0),
                                  child: Image.network(
                                    item.images![0].src!,
                                    fit: BoxFit.cover,
                                    height: itemHeight / 2,
                                  ),
                                )
                              : Padding(
                                  padding: EdgeInsets.all(8.0),
                                  child: Image.asset(
                                    "assets/images/no_image.png",
                                    fit: BoxFit.cover,
                                    height: itemHeight / 2,
                                  ),
                                ),
                        ),
                      ],
                    ),
                    if (item.rxMessage != null)
                      projectProvider.isArabic
                          ? Positioned(
                              right: -16,
                              top: 2,
                              child: Transform.rotate(
                                angle: math.pi / 4,
                                child: Container(
                                  color: CustomColors.accentColor,
                                  padding: EdgeInsets.only(
                                      left: 18, right: 18, top: 6, bottom: 3),
                                  child: Padding(
                                    padding: EdgeInsets.all(2.0),
                                    child: Text(
                                      "الوصفة\n مطلوبة",
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 7.0,
                                        height: 0.8,
                                        fontWeight: FontWeight.w600,
                                        letterSpacing: -0.27,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            )
                          : Positioned(
                              left: -24,
                              top: 2,
                              child: Transform.rotate(
                                angle: -math.pi / 4,
                                child: Container(
                                  padding: EdgeInsets.only(
                                      left: 18, right: 18, top: 6, bottom: 3),
                                  color: CustomColors.accentColor,
                                  child: Text(
                                    "\n E-Prescription \n Is required",
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 7.0,
                                      //letterSpacing: -0.27,
                                      height: 1.2,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10.0),
              child: Container(
                height: MediaQuery.of(context).size.height * 0.075,
                child: Texts(
                  projectProvider.isArabic ? item.namen : item.name,
                  //regular: true,
                  fontSize: 10,
                  color: Color(0xff2B353E),
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
            SizedBox(
              height: 7.0,
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.symmetric(
                  horizontal: 4,
                  vertical: 0,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  //mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 10, vertical: 2),
                      child: Texts(
                        "SAR ${item.price}",
                        fontWeight: FontWeight.w700,
                        fontSize: 11,
                        color: Color(0xff2B353E),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 5),
                      child: Row(
                        children: [
                          //  Expanded(
                          // RatingBar.readOnly(
                          //   initialRating: item.approvedRatingSum.toDouble(),
                          //   size: 13.0,
                          //   filledColor: Color(0XFFD02127),
                          //   emptyColor: Color(0XFFD02127),
                          //   isHalfAllowed: true,
                          //   halfFilledIcon: Icons.star_half,
                          //   filledIcon: Icons.star,
                          //   emptyIcon: Icons.star_border,
                          // ),
                          //
                          //

                          RatingBar(
                            initialRating: item.approvedRatingSum!.toDouble(),
                            direction: Axis.horizontal,
                            allowHalfRating: true,
                            itemCount: 5,
                            itemSize: 20,
                            ignoreGestures: true,
                            ratingWidget: RatingWidget(
                              full: Icon(Icons.star, color: CustomColors.accentColor,),
                              half: Icon(Icons.star_half, color: CustomColors.accentColor,),
                              empty: Icon(Icons.star, color: CustomColors.accentColor,),
                            ),
                            tapOnlyMode: true,
                            unratedColor: Colors.grey[500],
                            itemPadding: EdgeInsets.symmetric(horizontal: 4.0),
                            onRatingUpdate: (rating) {
                              print(rating);
                            },
                          ),
                          Texts(
                            "(${item.approvedTotalReviews})",
                            regular: true,
                            fontSize: 10,
                            fontWeight: FontWeight.w400,
                          ),

                          SizedBox(
                            width: 9.0,
                          ),
                          Icon(
                            Icons.arrow_forward,
                            size: 15,
                            color: Color(0xff2D2F39),
                          ),

//                          StarRating(
//                              totalAverage: item.approvedTotalReviews > 0
//                                  ? (item.approvedRatingSum.toDouble() /
//                                  item.approvedTotalReviews.toDouble())
//                                  .toDouble()
//                                  : 0,
//                              forceStars: true),
                          //   ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(
              height: 1,
            ),
          ],
        ),
      ),
    );
  }
}
