import 'dart:convert';

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/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/add_item_for_sale_image_model.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/add_details_fragment.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';

class ItemReviewFragment extends StatefulWidget {
  final Function changePageViewIndex;

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

  @override
  State<ItemReviewFragment> createState() => _ItemReviewFragmentState();
}

class _ItemReviewFragmentState extends State<ItemReviewFragment> {
  ItemReviewModel? itemReviewModel;
  late bool isUpdate;

  @override
  void initState() {
    itemReviewModel = AddItemDetailsFragment.itemReviewModel;
    itemReviewModel!.selectedSaleCategory = SelectCategoryFragment.selectedSaleCategory;
    isUpdate = AddItemDetailsFragment.isUpdate;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: const Color(0xff000000).withOpacity(.05),
            blurRadius: 26,
            offset: const Offset(0, -3),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          itemReviewModel!.itemTitle.toString().toText17(isBold: true).paddingOnly(top: 12),
          itemReviewModel!.itemDescription.toString().toText14().paddingOnly(top: 8),
          itemReviewModel!.itemCondition.toString().toText14(color: MyColors.yellowColor).paddingOnly(top: 12),
          SizedBox(
            height: 105.0,
            child: ListView.separated(
                shrinkWrap: true,
                physics: const BouncingScrollPhysics(),
                scrollDirection: Axis.horizontal,
                itemBuilder: (cxt, index) {
                  return Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10),
                      boxShadow: [
                        BoxShadow(
                          color: const Color(0xff000000).withOpacity(.05),
                          blurRadius: 26,
                          offset: const Offset(0, -3),
                        ),
                      ],
                    ),
                    width: 100,
                    height: 100,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(6),
                      child: Image.memory(
                        base64Decode(itemReviewModel!.itemPhotos![index]),
                        fit: BoxFit.contain,
                      ),
                    ),
                  ).paddingOnly(top: 12.0, bottom: 12.0);
                },
                separatorBuilder: (cxt, index) => 8.width,
                itemCount: itemReviewModel!.itemPhotos!.length),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              "Selling for  ".toText14(),
              "${itemReviewModel!.itemPrice.toString()} SAR".toText20(isBold: true),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              const Icon(
                Icons.warning_sharp,
                size: 20,
                color: MyColors.redColor,
              ).paddingOnly(top: 21),
              "This ad will be valid for 2 weeks after approval.".toText11(color: MyColors.redColor).paddingOnly(left: 10, right: 10),
            ],
          ),
          const Spacer(),
          Row(
            children: [
              DefaultButton(
                LocaleKeys.cancel.tr(),
                () async {
                  Navigator.of(context).pop();
                },
                colors: const [Color(0xffD02127), Color(0xffD02127)],
              ).expanded,
              12.width,
              DefaultButton(
                LocaleKeys.submit.tr(),
                () async {
                  submitItemForSale();
                },
                disabledColor: MyColors.lightGrayColor,
              ).expanded
            ],
          ).paddingOnly(top: 21),
        ],
      ),
    ).paddingAll(21);
  }

  void submitItemForSale() async {
    List<Map<String, dynamic>> imagesList = [];
    int attachmentID = 1;
    for (var element in itemReviewModel!.itemPhotos!) {
      imagesList.add(AddItemForSaleImageModel(attachmentID: attachmentID, base64Data: element, fileName: "Image_$attachmentID", contentType: "image/png").toJson());
      attachmentID++;
    }

    try {
      Utils.showLoading(context);
      String message = await ItemsForSaleApiClient().addItemForSale(itemReviewModel!, imagesList);
      Utils.hideLoading(context);
      Utils.showToast(message);
      Navigator.of(context).pop();
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
