import 'package:hmg_patient_app/core/model/packages_offers/responses/PackagesResponseModel.dart';
import 'package:hmg_patient_app/core/viewModels/packages_offers/PackagesOffersViewModel.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/theme/colors.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/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:expandable/expandable.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:html/parser.dart';


class OfferAndPackagesDetail extends StatefulWidget {
  final PackagesResponseModel itemModel;
  final Function(PackagesResponseModel product) onCartClick;
  bool showAddToCartFooter = true;

  OfferAndPackagesDetail({required this.itemModel, required this.onCartClick, Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => OfferAndPackagesDetailState();
}

class OfferAndPackagesDetailState extends State<OfferAndPackagesDetail> {
  PackagesViewModel? viewModel;

  bool expandFlag = false;
  var controller = new ExpandableController();

  @override
  Widget build(BuildContext context) {
    final images = widget.itemModel.images ?? [];
    String image = "";
    if(images.isNotEmpty)
     image = widget.itemModel.images!.first.src ?? "";

    return BaseView<PackagesViewModel>(
      onModelReady: (model) {
        viewModel = model;
      },
      builder: (_, model, wi) => AppScaffold(
        appBarTitle: TranslationBase.of(context).offerAndPackages,
        isShowAppBar: true,
        isPharmacy: false,
        showPharmacyCart: false,
        showHomeAppBarIcon: false,
        isOfferPackages: true,
        showOfferPackagesCart: true,
        isShowDecPage: false,
        showNewAppBar: true,
        showNewAppBarTitle: true,
        body: Column(
          children: [
            Expanded(
              child: ListView(
                physics: BouncingScrollPhysics(),
                children: [
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.all(21.0),
                    child: AspectRatio(
                      aspectRatio: 333 / 333,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(15.0),
                        child: Image.network(
                          image,
                          fit: BoxFit.fill,
                          errorBuilder: (a1,a2,a3) => Container(color: Colors.grey.withOpacity(0.25),),
                        ),
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(21.0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.itemModel.name!,
                          maxLines: 1,
                          style: TextStyle(fontSize: 19.0, fontWeight: FontWeight.bold, color: Color(0xff2E303A), letterSpacing: -1.14),
                        ),
                        Text(
                          widget.itemModel.shortDescription!,
                          style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.w600, color: Color(0xff575757), letterSpacing: -.56),
                        ),
                        SizedBox(height: 9),
                        Row(
                          children: [
                            // RatingBar.readOnly(
                            //   initialRating: 4.5,
                            //   // todo ask haroon about rating value
                            //   size: 18.0,
                            //   filledColor: Color(0XFFD02127),
                            //   emptyColor: Color(0XFFD02127),
                            //   isHalfAllowed: true,
                            //   halfFilledIcon: Icons.star_half,
                            //   filledIcon: Icons.star,
                            //   emptyIcon: Icons.star_border,
                            // ),
                            RatingBar(
                              initialRating: 4.5,
                              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);
                              },
                            )
                          ],
                        ),
                        SizedBox(height: 16),
                        SizedBox(
                          height: 34,
                          child: ListView.separated(
                            scrollDirection: Axis.horizontal,
                            shrinkWrap: true,
                            physics: BouncingScrollPhysics(),
                            itemCount: widget.itemModel.storeNames!.length,
                            separatorBuilder: (context, index) {
                              return mWidth(5.0);
                            },
                            itemBuilder: (BuildContext context, int index) {
                              return contactButton(widget.itemModel.storeNames![index].toString());
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  ExpandableNotifier(
                    initialExpanded: true,
                    child: Container(
                      color: Colors.white,
                      margin: EdgeInsets.only(bottom: 21),
                      child: Column(
                        children: <Widget>[
                          ScrollOnExpand(
                            scrollOnExpand: true,
                            scrollOnCollapse: false,
                            child: ExpandablePanel(

                              theme: const ExpandableThemeData(
                                headerAlignment: ExpandablePanelHeaderAlignment.center,
                                tapBodyToCollapse: true,
                              ),
                              header: InkWell(
                                onTap: () {
                                  setState(() {
                                    expandFlag = !expandFlag;
                                    controller.expanded = expandFlag;
                                  });
                                },
                                child: Padding(
                                  padding: const EdgeInsets.all(21),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          TranslationBase.of(context).description,
                                          maxLines: 1,
                                          style: TextStyle(fontSize: 19.0, color: Color(0xff2E303A), fontWeight: FontWeight.bold, letterSpacing: -1.14),
                                        ),
                                      ),
                                      Icon(
                                        expandFlag ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                                        color: Color(0xff2E303A),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              builder: (_, collapsed, expanded) {
                                return Expandable(
                                  controller: controller,
                                  collapsed: collapsed,
                                  expanded: Padding(
                                    padding: const EdgeInsets.only(bottom: 21, left: 21, right: 21),
                                    child: Text(parseHtmlString(widget.itemModel.fullDescription!),
                                        style: TextStyle(
                                          fontSize: 14.0,
                                          fontWeight: FontWeight.w600,
                                          letterSpacing: -0.56,
                                          color: Color(0xff575757),
                                        ),
                                        overflow: TextOverflow.clip),
                                  ),
                                  theme: const ExpandableThemeData(crossFadePoint: 0),
                                );
                              }, collapsed: SizedBox(), expanded: SizedBox(),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            if(widget.showAddToCartFooter && widget.onCartClick != null)
              Row(
              children: [
                Expanded(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (widget.itemModel.hasDiscountsApplied!)
                        Text(widget.itemModel.oldPrice.toString() + " " + TranslationBase.of(context).sar,
                            style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.w600, letterSpacing: -0.6, decoration: TextDecoration.lineThrough, color: CustomColors.grey2)),
                      Text(widget.itemModel.price.toString().trim() + " " + TranslationBase.of(context).sar,
                          style: TextStyle(fontSize: 19.0, fontWeight: FontWeight.bold, letterSpacing: -0.76, color: Color(0xff2B353E))),
                    ],
                  ),
                ),
                SizedBox(width: 8),
                Expanded(
                  child: DefaultButton(
                    TranslationBase.of(context).addToCart,
                    () {
                      widget.onCartClick(widget.itemModel);
                    },
                    svgIcon: "assets/images/new/add_to_cart.svg",
                    isTextExpanded: false,
                  ),
                ),
              ],
            ).insideContainer
          ],
        ),
      ),
    );
  }

  String parseHtmlString(String htmlString) {
    var document = parse(htmlString);
    String parsedString = parse(document.body!.text!).documentElement!.text!;
    return parsedString;
  }

  Widget contactButton(String title) {
    return Container(
      height: 34,
      padding: EdgeInsets.only(left: 12, right: 12, top: 8, bottom: 9),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Color(0xffEAEAEA), width: 1),
        borderRadius: BorderRadius.all(
          Radius.circular(36.0),
        ),
      ),
      child: Text(
        title,
        style: TextStyle(
          fontSize: 10,
          letterSpacing: -0.4,
          fontWeight: FontWeight.w600,
          color: Color(0xff535353),
        ),
        maxLines: 1,
      ),
    );
  }
}
