import 'dart:convert';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
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/consts.dart';
import 'package:mohem_flutter_app/classes/date_uitl.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_employee_ads_list.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';

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

  @override
  State<MyPostedAdsFragment> createState() => _MyPostedAdsFragmentState();
}

class _MyPostedAdsFragmentState extends State<MyPostedAdsFragment> {
  List<EmployeePostedAds> employeePostedAdsList = [];

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

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        margin: const EdgeInsets.all(21),
        child: employeePostedAdsList.isNotEmpty
            ? ListView.separated(
                shrinkWrap: true,
                physics: const BouncingScrollPhysics(),
                itemBuilder: (cxt, index) {
                  return 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(
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Container(
                              width: 50,
                              height: 50,
                              decoration: BoxDecoration(
                                color: Colors.white,
                                boxShadow: [
                                  BoxShadow(
                                    color: const Color(0xff000000).withOpacity(.05),
                                    blurRadius: 26,
                                    offset: const Offset(0, -3),
                                  ),
                                ],
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(6),
                                child: employeePostedAdsList[index].itemAttachments!.isNotEmpty
                                    ? Image.memory(
                                        base64Decode(employeePostedAdsList[index].itemAttachments![0].content!),
                                        fit: BoxFit.contain,
                                      )
                                    : Container(),
                              ),
                            ),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      employeePostedAdsList[index].title!.toText16(isBold: true, color: const Color(0xff2B353E)).paddingOnly(left: 12, right: 12),
                                      "Posted on ${DateUtil.formatDateToDate(DateTime.parse(employeePostedAdsList[index].created!), false)}"
                                          .toText12(color: Color(0xff969696))
                                          .paddingOnly(left: 7, right: 7),
                                    ],
                                  ),
                                  employeePostedAdsList[index].description!.toText12(color: const Color(0xff2B353E), maxLine: 1).paddingOnly(left: 12, right: 12, bottom: 12),
                                  employeePostedAdsList[index]
                                      .status!
                                      .toText12(isBold: true, color: employeePostedAdsList[index].status == 'Approved' ? MyColors.greenColor : MyColors.yellowColor)
                                      .paddingOnly(left: 12, right: 12),
                                  // Row(
                                  //   children: [
                                  //     IconButton(
                                  //         padding: EdgeInsets.zero,
                                  //         icon: const Icon(
                                  //           Icons.delete_rounded,
                                  //           size: 25,
                                  //           color: MyColors.redColor,
                                  //         ),
                                  //         constraints: const BoxConstraints(),
                                  //         onPressed: () {
                                  //           updateItemForSale(employeePostedAdsList[index].itemSaleID!);
                                  //         }),
                                  //     37.width,
                                  //     IconButton(
                                  //         padding: EdgeInsets.zero,
                                  //         icon: const Icon(
                                  //           Icons.edit_note_sharp,
                                  //           size: 25,
                                  //           color: Color(0xff2E303A),
                                  //         ),
                                  //         constraints: const BoxConstraints(),
                                  //         onPressed: () {}),
                                  //   ],
                                  // ),
                                ],
                              ),
                            ),
                          ],
                        ).paddingOnly(left: 7, right: 7, bottom: 0, top: 12),
                        const Divider(
                          color: MyColors.lightGreyEFColor,
                          thickness: 1.0,
                        ),
                        Row(
                          children: [
                            LocaleKeys.remove.tr().toText12(color: MyColors.redColor).center.onPress(() {
                              updateItemForSale(employeePostedAdsList[index]);
                            }).expanded,
                            Container(width: 1, height: 30, color: MyColors.lightGreyEFColor),
                            LocaleKeys.edit.tr().toText12(color: MyColors.gradiantEndColor).center.onPress(() {
                              GetRegionsList selectedRegion = GetRegionsList();
                              selectedRegion.regionID = employeePostedAdsList[index].regionID;
                              selectedRegion.regionName = employeePostedAdsList[index].regionName;
                              GetSaleCategoriesList selectedSaleCategory = GetSaleCategoriesList();
                              selectedSaleCategory.categoryID = employeePostedAdsList[index].categoryID;
                              selectedSaleCategory.title = employeePostedAdsList[index].categoryTitle;
                              List<String> itemPhotos = [];
                              itemPhotos.add(employeePostedAdsList[index].itemAttachments![0].content!.toString());
                              ItemReviewModel itemReviewModel = ItemReviewModel(employeePostedAdsList[index].title, employeePostedAdsList[index].description, employeePostedAdsList[index].status,
                                  selectedRegion, employeePostedAdsList[index].quotePrice, itemPhotos, selectedSaleCategory, employeePostedAdsList[index].endDate!);
                              Utils.saveStringFromPrefs(SharedPrefsConsts.editItemForSale, jsonEncode(itemReviewModel.toJson()));
                              Navigator.pushNamed(context, AppRoutes.addNewItemForSale, arguments: 1);
                            }).expanded,
                          ],
                        ),
                        8.height
                      ],
                    ),
                  );
                },
                separatorBuilder: (cxt, index) => 12.height,
                itemCount: employeePostedAdsList.length)
            : Utils.getNoDataWidget(context).paddingOnly(top: 200.0),
      ),
    );
  }

  void updateItemForSale(EmployeePostedAds employeePostedAds) async {
    Utils.showLoading(context);

    String? empNum = AppState().memberInformationList?.eMPLOYEENUMBER;
    String? empMobNum = AppState().memberInformationList?.eMPLOYEEMOBILENUMBER;
    String? loginTokenID = AppState().postParamsObject?.logInTokenID;
    String? tokenID = AppState().postParamsObject?.tokenID;

    var request = http.MultipartRequest('POST', Uri.parse("${ApiConsts.cocRest}Mohemm_ITG_UpdateItemForSaleMobile"));
    request.fields['ItgItemSaleID'] = employeePostedAds.itemSaleID.toString();
    request.fields['ItgCategoryID'] = employeePostedAds.categoryID.toString();
    request.fields['ItgTitle'] = employeePostedAds.title!;
    request.fields['ItgDescription'] = employeePostedAds.description!;
    request.fields['ItgQuotePrice'] = employeePostedAds.quotePrice.toString();
    request.fields['RegionID'] = employeePostedAds.regionID.toString();
    request.fields['Itg_EndDate'] = employeePostedAds.endDate.toString();
    request.fields['endDate'] = employeePostedAds.endDate.toString();
    request.fields['Channel'] = "31";
    request.fields['ItgIsActive'] = "false";
    request.fields['LogInToken'] = loginTokenID!;
    request.fields['Token'] = tokenID!;
    request.fields['MobileNo'] = empMobNum!;
    request.fields['EmployeeNumber'] = empNum!;
    request.fields['employeeNumber'] = empNum;

    // debugPrint(json.encode(request.fields.toString()));

    var response = await request.send().catchError((e) {
      Utils.hideLoading(context);
      Utils.handleException(e, context, null);
    });
    Utils.hideLoading(context);
    getAdsByEmployee();
  }

  void getAdsByEmployee() async {
    try {
      employeePostedAdsList.clear();
      Utils.showLoading(context);
      employeePostedAdsList = await ItemsForSaleApiClient().getEmployeePostedAds();
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
