import 'dart:convert';
import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/items_for_sale/items_for_sale_api_client.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/consts.dart';
import 'package:mohem_flutter_app/classes/utils.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_regions_list.dart';
import 'package:mohem_flutter_app/models/items_for_sale/get_sale_categories_list.dart';
import 'package:mohem_flutter_app/models/items_for_sale/item_review_model.dart';
import 'package:mohem_flutter_app/ui/screens/items_for_sale/fragments/select_category_fragment.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/button/simple_button.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';
import 'package:mohem_flutter_app/widgets/image_picker.dart';
import 'package:mohem_flutter_app/widgets/radio/show_radio.dart';

class AddItemDetailsFragment extends StatefulWidget {
  final Function changePageViewIndex;
  final GetSaleCategoriesList selectedSaleCategory;
  static late ItemReviewModel itemReviewModel;
  static late bool isUpdate;

  AddItemDetailsFragment({Key? key, required this.changePageViewIndex, required this.selectedSaleCategory}) : super(key: key);

  @override
  State<AddItemDetailsFragment> createState() => _AddItemDetailsFragmentState();
}

class _AddItemDetailsFragmentState extends State<AddItemDetailsFragment> {
  String itemTitle = "";
  String itemDescription = "";
  num itemPrice = 0;
  String selectedItemCondition = "new";

  List<GetRegionsList> getRegionsList = [];
  GetRegionsList selectedRegion = GetRegionsList();

  List<String> images = [];

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

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListView(
          padding: const EdgeInsets.only(left: 21, right: 21, bottom: 21),
          children: [
            LocaleKeys.addDetails.tr().toText20(),
            12.height,
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                DynamicTextFieldWidget(
                  LocaleKeys.title.tr(),
                  itemTitle.isEmpty ? LocaleKeys.itemTitle.tr() : itemTitle,
                  isEnable: true,
                  suffixIconData: Icons.search,
                  isPopup: false,
                  lines: 1,
                  isInputTypeNum: false,
                  isReadOnly: false,
                  onChange: (String value) {
                    itemTitle = value;
                  },
                ),
                DynamicTextFieldWidget(
                  LocaleKeys.description.tr(),
                  itemDescription.isEmpty ? LocaleKeys.itemDescription.tr() : itemDescription,
                  isEnable: true,
                  suffixIconData: Icons.search,
                  isPopup: false,
                  lines: 4,
                  isInputTypeNum: false,
                  isReadOnly: false,
                  onChange: (String value) {
                    itemDescription = value;
                  },
                ).paddingOnly(top: 12),
                LocaleKeys.itemCondition.tr().toText14().paddingOnly(top: 21),
                Row(
                  children: [
                    ShowRadio(title: LocaleKeys.newString.tr(), value: "new", groupValue: selectedItemCondition, selectedColor: MyColors.gradiantStartColor).onPress(() {
                      selectedItemCondition = "new";
                      setState(() {});
                    }),
                    12.width,
                    ShowRadio(title: LocaleKeys.used.tr(), value: "used", groupValue: selectedItemCondition, selectedColor: MyColors.gradiantStartColor).onPress(() {
                      selectedItemCondition = "used";
                      setState(() {});
                    }),
                  ],
                ).paddingOnly(top: 12),
                PopupMenuButton(
                  child: DynamicTextFieldWidget(
                    LocaleKeys.region.tr(),
                    selectedRegion.regionName ?? LocaleKeys.selectRegion.tr(),
                    isEnable: false,
                    isPopup: true,
                    isInputTypeNum: true,
                    isReadOnly: false,
                  ),
                  itemBuilder: (_) => <PopupMenuItem<int>>[
                    for (int i = 0; i < getRegionsList!.length; i++) PopupMenuItem<int>(child: Text(getRegionsList[i].regionName!), value: i),
                  ],
                  onSelected: (int popupIndex) {
                    selectedRegion = getRegionsList![popupIndex];
                    setState(() {});
                  },
                ).paddingOnly(top: 21),
                DynamicTextFieldWidget(
                  LocaleKeys.itemPrice.tr(),
                  itemPrice == 0 ? LocaleKeys.price.tr() : itemPrice.toString(),
                  isEnable: true,
                  suffixIconData: Icons.search,
                  isPopup: false,
                  lines: 1,
                  isInputTypeNum: true,
                  isReadOnly: false,
                  onChange: (String value) {
                    itemPrice = num.parse(value);
                  },
                ).paddingOnly(top: 12),
                LocaleKeys.itemPhotos.tr().toText14().paddingOnly(top: 21),
                attachmentView(LocaleKeys.attachments.tr()).paddingOnly(top: 12),
              ],
            ).objectContainerView(title: LocaleKeys.itemInfo.tr()),
          ],
        ).expanded,
        1.divider,
        Row(
          children: [
            DefaultButton(
              LocaleKeys.cancel.tr(),
              () async {
                Navigator.of(context).pop();
              },
              colors: const [Color(0xffD02127), Color(0xffD02127)],
            ).expanded,
            8.width,
            DefaultButton(
              LocaleKeys.next.tr(),
              isButtonDisabled()
                  ? null
                  : () async {
                      AddItemDetailsFragment.itemReviewModel = getItemReviewObject();
                      widget.changePageViewIndex(2);
                    },
              disabledColor: MyColors.lightGrayColor,
            ).expanded
          ],
        ).insideContainer
      ],
    );
  }

  ItemReviewModel getItemReviewObject() {
    ItemReviewModel itemReviewModel = ItemReviewModel(itemTitle, itemDescription, selectedItemCondition, selectedRegion, itemPrice, images, widget.selectedSaleCategory);
    return itemReviewModel;
  }

  bool isButtonDisabled() {
    if (itemTitle.isNotEmpty && itemDescription.isNotEmpty && selectedRegion != null && itemPrice != 0 && images.isNotEmpty) {
      return false;
    } else {
      return true;
    }
  }

  Widget attachmentView(String title) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            title.toText16().expanded,
            6.width,
            SimpleButton(LocaleKeys.add.tr(), () {
              ImageOptions.showImageOptionsNew(context, false, (String image, File file) {
                setState(() {
                  images.add(image);
                  Navigator.of(context).pop();
                });
              });
            }, fontSize: 14),
          ],
        ),
        if (images.isNotEmpty) 12.height,
        if (images.isNotEmpty)
          ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (cxt, index) {
                return Container(
                  margin: const EdgeInsets.all(10),
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          const Icon(Icons.attach_file_sharp),
                          const SizedBox(
                            width: 8,
                          ),
                          'image ${index + 1}.png'.toText16(),
                        ],
                      ),
                      InkWell(
                        onTap: () {
                          setState(() {
                            images.remove(images[index]);
                          });
                        },
                        child: Icon(
                          Icons.delete_sharp,
                          color: Colors.red[300],
                        ),
                      )
                    ],
                  ),
                );
              },
              separatorBuilder: (cxt, index) => 6.height,
              itemCount: images.length),
      ],
    ).objectContainerView();
  }

  Future<void> getAdDetails() async {
    // todo need to change this  method later , its not a good approach to do it like this.
    String details = await Utils.getStringFromPrefs(SharedPrefsConsts.editItemForSale);
    if(details.isNotEmpty) {
      var body = json.decode(details);
      AddItemDetailsFragment.isUpdate = true;

      GetRegionsList selectedRegionAd = GetRegionsList();

      GetSaleCategoriesList selectedSaleCategoryAd = GetSaleCategoriesList();

      itemTitle = body["itemTitle"];
      itemDescription = body["itemDescription"];
      selectedItemCondition = body["itemCondition"].toString().toLowerCase();
      selectedRegionAd.regionID = body["selectedRegion"]["regionID"];
      selectedRegionAd.regionName = body["selectedRegion"]["regionName"];
      selectedRegion = selectedRegionAd;
      itemPrice = body["itemPrice"];
      selectedSaleCategoryAd.categoryID = body["selectedSaleCategory"]["categoryID"];
      selectedSaleCategoryAd.title = body["selectedSaleCategory"]["title"];
      if (body["itemPhotos"].length != 0) {
        images.add(body["itemPhotos"][0]);
      }
      ItemReviewModel itemReviewModel =
      ItemReviewModel(body["itemTitle"], body["itemDescription"], body["itemCondition"].toString().toLowerCase(), selectedRegionAd, body["itemPrice"], images, selectedSaleCategoryAd);

      AddItemDetailsFragment.itemReviewModel = itemReviewModel;
      SelectCategoryFragment.selectedSaleCategory = selectedSaleCategoryAd;
    } else {
      AddItemDetailsFragment.isUpdate = false;
    }
  }

  void getRegions() async {
    try {
      Utils.showLoading(context);
      getRegionsList = await ItemsForSaleApiClient().getRegions();
      await getAdDetails();
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
