import 'dart:convert';

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/items_for_sale/items_for_sale_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/items_for_sale/get_items_for_sale_list.dart';
import 'package:mohem_flutter_app/models/items_for_sale/get_sale_categories_list.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';

class ItemsForSaleFragment extends StatefulWidget {
  @override
  State<ItemsForSaleFragment> createState() => _ItemsForSaleFragmentState();
}

class _ItemsForSaleFragmentState extends State<ItemsForSaleFragment> {
  TextEditingController searchController = TextEditingController();

  List<GetSaleCategoriesList> getSaleCategoriesList = [];
  List<GetItemsForSaleList> getItemsForSaleList = [];
  List<GetItemsForSaleList> _foundItemsForSaleList = [];

  ScrollController gridScrollController = ScrollController();
  int currentPageNo = 1;
  int currentCategoryID = 0;

  @override
  void initState() {
    getItemForSaleCategory();
    gridScrollController.addListener(() {
      if (gridScrollController.position.atEdge) {
        bool isTop = gridScrollController.position.pixels == 0;
        if (!isTop && getItemsForSaleList.length == currentPageNo * 10) {
          currentPageNo++;
          getItemsForSale(currentPageNo, currentCategoryID);
        }
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      controller: gridScrollController,
      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: 105.0,
          child: getSaleCategoriesList.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 = getSaleCategoriesList[index].categoryID!;
                            getItemsForSaleList.clear();
                            currentPageNo = 1;
                            getItemsForSale(currentPageNo, currentCategoryID);
                          });
                        },
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SvgPicture.string(getSaleCategoriesList[index].content!, fit: BoxFit.contain),
                                currentCategoryID == getSaleCategoriesList[index].categoryID ? const Icon(Icons.check_circle_rounded, color: MyColors.greenColor, size: 16.0) : Container(),
                              ],
                            ).expanded,
                            AppState().isArabic(context)
                                ?getSaleCategoriesList[index].titleAr!.toText10()
                                :getSaleCategoriesList[index].title!.toText10()
                          ],
                        ).paddingOnly(left: 10, right: 10, bottom: 10, top: 12).expanded.objectContainerView(disablePadding: true),
                      ),
                    );
                  },
                  separatorBuilder: (cxt, index) => 12.width,
                  itemCount: getSaleCategoriesList.length)
              : Container(),
        ),
        getItemsForSaleList.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: 12),
                shrinkWrap: true,
                primary: false,
                physics: const ScrollPhysics(),
                children: getItemsForSaleWidgets(),
              )
            : Utils.getNoDataWidget(context).paddingOnly(top: 50),
        // 32.height,
      ],
    );
  }

  void _runFilter(String enteredKeyword) {
    List<GetItemsForSaleList> results = [];
    if (enteredKeyword.isEmpty) {
      results = getItemsForSaleList;
    } else {
      results = getItemsForSaleList.where((offer) => offer.title!.toLowerCase().contains(enteredKeyword.toLowerCase())).toList();
    }
    setState(() {
      _foundItemsForSaleList = results;
    });
  }

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

    _foundItemsForSaleList.forEach((element) {
      itemsList.add(getItemCard(element));
    });

    return itemsList;
  }

  Widget getItemCard(GetItemsForSaleList getItemsForSaleList) {
    return InkWell(
      onTap: () {
        Navigator.pushNamed(context, AppRoutes.itemsForSaleDetail, arguments: getItemsForSaleList);
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        // mainAxisSize: MainAxisSize.min,
        children: [
          Hero(
            tag: "ItemImage" + getItemsForSaleList.itemSaleID.toString(),
            transitionOnUserGestures: true,
            child: AspectRatio(
              aspectRatio: 148 / 127,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(6),
                child: Image.memory(
                  base64Decode(getItemsForSaleList.itemAttachments![0].content!),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          10.height,
          getItemsForSaleList.title!.toText16(maxlines: 1),
          getItemsForSaleList.description!.toText12(maxLine: 2, color: MyColors.grey57Color).expanded,
          // 8.height,
          getItemsForSaleList.status!.toText14(color: getItemsForSaleList.status == 'Approved' ? MyColors.greenColor : MyColors.yellowColor),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: ["${getItemsForSaleList.quotePrice} ${getItemsForSaleList.currencyCode!}".toText16(isBold: true), SvgPicture.asset("assets/images/arrow_next.svg").paddingOnly(bottom: 4)],
          ),
          6.height
        ],
      ).paddingAll(8).expanded.objectContainerView(disablePadding: true),
    );
  }

  void getItemForSaleCategory() async {
    try {
      Utils.showLoading(context);
      getSaleCategoriesList = await ItemsForSaleApiClient().getSaleCategories();
      Utils.hideLoading(context);
      setState(() {});
      getItemsForSale(currentPageNo, currentCategoryID);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getItemsForSale(int itgPageNo, int itgCategoryID) async {
    List<GetItemsForSaleList> getItemsForSaleListLocal = [];
    try {
      Utils.showLoading(context);
      getItemsForSaleListLocal.clear();
      getItemsForSaleListLocal = await ItemsForSaleApiClient().getItemsForSale(itgPageNo, itgCategoryID);
      getItemsForSaleList.addAll(getItemsForSaleListLocal);
      _foundItemsForSaleList = getItemsForSaleList;
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
