import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:mohem_flutter_app/api/offers_and_discounts_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/offers_and_discounts/get_categories_list.dart';
import 'package:mohem_flutter_app/models/offers_and_discounts/get_offers_list.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';

class OffersAndDiscountsHome extends StatefulWidget {
  const OffersAndDiscountsHome({Key? key}) : super(key: key);

  @override
  State<OffersAndDiscountsHome> createState() => _OffersAndDiscountsHomeState();
}

class _OffersAndDiscountsHomeState extends State<OffersAndDiscountsHome> {
  List<GetCategoriesList> getCategoriesList = [];
  List<OffersListModel> getOffersList = [];
  List<OffersListModel> _foundOffersList = [];

  int currentCategoryID = 0;

  @override
  void initState() {
    getCategoriesListAPI();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(context, title: LocaleKeys.offerAndDiscounts.tr(), showHomeButton: true),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            DynamicTextFieldWidget(
              LocaleKeys.search.tr(),
              LocaleKeys.searchItems.tr(),
              isEnable: true,
              suffixIconData: Icons.search,
              isPopup: false,
              lines: 1,
              isInputTypeNum: false,
              isReadOnly: false,
              onChange: (String value) {
                _runFilter(value);
              },
            ).paddingOnly(left: 21, right: 21, top: 21),
            LocaleKeys.browseCategories.tr().toText17().paddingOnly(left: 21, right: 21, top: 21),
            SizedBox(
              height: 110.0,
              child: getCategoriesList.isNotEmpty
                  ? ListView.separated(
                      shrinkWrap: true,
                      physics: const BouncingScrollPhysics(),
                      padding: const EdgeInsets.only(left: 21, right: 21, top: 13, bottom: 13),
                      scrollDirection: Axis.horizontal,
                      itemBuilder: (cxt, index) {
                        return AspectRatio(
                          aspectRatio: 1 / 1,
                          child: InkWell(
                            onTap: () {
                              setState(() {
                                currentCategoryID = getCategoriesList[index].id!;
                                getCategoryOffersListAPI();
                                // getItemsForSaleList.clear();
                                // currentPageNo = 1;
                                // getItemsForSale(currentPageNo, currentCategoryID);
                              });
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(15),
                                boxShadow: [
                                  BoxShadow(
                                    color: const Color(0xff000000).withOpacity(.05),
                                    blurRadius: 26,
                                    offset: const Offset(0, -3),
                                  ),
                                ],
                              ),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      SvgPicture.string(
                                        getCategoriesList[index].content!,
                                        fit: BoxFit.contain,
                                        width: 25,
                                        height: 25,
                                      ),
                                      currentCategoryID == getCategoriesList[index].id ? const Icon(Icons.check_circle_rounded, color: MyColors.greenColor, size: 16.0) : Container(),
                                    ],
                                  ).expanded,
                                  AppState().isArabic(context) ? getCategoriesList[index].categoryNameAr!.toText10(maxlines: 1) : getCategoriesList[index].categoryNameEn!.toText10(maxlines: 1)
                                ],
                              ).paddingOnly(left: 10, right: 10, bottom: 10, top: 12),
                            ),
                          ),
                        );
                      },
                      separatorBuilder: (cxt, index) => 12.width,
                      itemCount: getCategoriesList.length,
                    )
                  : Container(),
            ),
            getOffersList.isNotEmpty
                ? GridView(
                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 162 / 266, crossAxisSpacing: 12, mainAxisSpacing: 12),
                    padding: const EdgeInsets.only(left: 21, right: 21, bottom: 21, top: 21),
                    shrinkWrap: true,
                    primary: false,
                    physics: const ScrollPhysics(),
                    children: getItemsForSaleWidgets(),
                  )
                : Utils.getNoDataWidget(context).paddingOnly(top: 50),
          ],
        ),
      ),
    );
  }

  List<Widget> getItemsForSaleWidgets() {
    List<Widget> itemsList = [];

    for (var element in _foundOffersList) {
      itemsList.add(getItemCard(element));
    }

    return itemsList;
  }

  Widget getItemCard(OffersListModel getOffersList) {
    return InkWell(
      onTap: () {
        navigateToDetails(getOffersList);
      },
      child: Container(
        padding: const EdgeInsets.all(10.0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: const Color(0xff000000).withOpacity(.05),
              blurRadius: 26,
              offset: const Offset(0, -3),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Hero(
              tag: "ItemImage" + getOffersList.rowID!,
              transitionOnUserGestures: true,
              child: AspectRatio(
                aspectRatio: 118 / 127,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(6),
                  child: Image.network(
                    getOffersList.bannerImage!,
                    fit: BoxFit.contain,
                  ),
                ),
              ),
            ),
            AppState().isArabic(context)
                ? getOffersList.titleAR!.toText16(isBold: true, color: const Color(0xff2B353E), maxlines: 1)
                : getOffersList.title!.toText16(isBold: true, color: const Color(0xff2B353E), maxlines: 1),
            // Html(
            //     data: AppState().isArabic(context) ? getOffersList.descriptionAR! : getOffersList.description ?? "",
            //     // onLinkTap: (String? url, RenderContext context, Map<String, String> attributes, _) {
            //   //   launchUrl(Uri.parse(url!));
            //   // }
            // ),
            // getOffersList.description!.toText12(maxLine: 2, color: const Color(0xff535353)),
            // 8.height,
            getOffersList.discount!.toText14(isBold: true, maxlines: 1),
            20.height,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [checkDate(getOffersList.endDate!), SvgPicture.asset("assets/images/arrow_next.svg").paddingOnly(bottom: 4)],
            ),
          ],
        ),
      ),
    );
  }

  void _runFilter(String enteredKeyword) {
    List<OffersListModel> results = [];
    if (enteredKeyword.isEmpty) {
      results = getOffersList;
    } else {
      if (AppState().isArabic(context)) {
        results = getOffersList.where((offer) => offer.titleAR!.toLowerCase().contains(enteredKeyword.toLowerCase())).toList();
      } else {
        results = getOffersList.where((offer) => offer.title!.toLowerCase().contains(enteredKeyword.toLowerCase())).toList();
      }
    }
    setState(() {
      _foundOffersList = results;
    });
  }

  void navigateToDetails(OffersListModel offersListModelObj) {
    List<OffersListModel> getOffersDetailList = [];
    getOffersDetailList.clear();
    int counter = 1;

    getOffersDetailList.add(offersListModelObj);

    getOffersList.forEach((element) {
      if (counter <= 4) {
        if (element.rowID != offersListModelObj.rowID) {
          getOffersDetailList.add(element);
          counter++;
        }
      }
    });

    Navigator.pushNamed(context, AppRoutes.offersAndDiscountsDetails, arguments: getOffersDetailList);
  }

  Widget checkDate(String endDate) {
    DateTime endDateObj = DateFormat("yyyy-MM-dd").parse(endDate);
    if (endDateObj.isAfter(DateTime.now())) {
      return LocaleKeys.offerValid.tr().toText14(isBold: true, color: MyColors.greenColor);
    } else {
      return LocaleKeys.offerExpired.tr().toText14(isBold: true, color: MyColors.redColor);
    }
  }

  void getCategoriesListAPI() async {
    try {
      Utils.showLoading(context);
      getCategoriesList = await OffersAndDiscountsApiClient().getSaleCategories();
      Utils.hideLoading(context);
      setState(() {});
      getCategoryOffersListAPI();
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getCategoryOffersListAPI() async {
    try {
      Utils.showLoading(context);
      getOffersList = await OffersAndDiscountsApiClient().getOffersList(currentCategoryID, 100);
      _foundOffersList = getOffersList;
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
