import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rasadyar_chicken/data/models/request/conform_allocation/conform_allocation.dart';
import 'package:rasadyar_chicken/data/models/response/allocated_made/allocated_made.dart';
import 'package:rasadyar_chicken/data/models/response/guild/guild_model.dart';
import 'package:rasadyar_chicken/data/models/response/roles_products/roles_products.dart';
import 'package:rasadyar_chicken/presentation/pages/entering_the_warehouse/string_utils.dart';
import 'package:rasadyar_chicken/presentation/routes/routes.dart';
import 'package:rasadyar_core/core.dart';

import 'logic.dart';

class SalesInProvincePage extends GetView<SalesInProvinceLogic> {
  SalesInProvincePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: RAppBar(
        titleTextStyle: AppFonts.yekan16Bold.copyWith(color: Colors.white),
        hasBack: false,
        leadingWidth: 155,
        leading: Row(
          mainAxisSize: MainAxisSize.min,
          spacing: 6,
          children: [
            Assets.vec.chickenSvg.svg(
              width: 24,
              height: 24,
              colorFilter: const ColorFilter.mode(Colors.white, BlendMode.srcIn),
            ),
            Text('رصدطیور', style: AppFonts.yekan16Bold.copyWith(color: Colors.white)),
          ],
        ),
        additionalActions: [
          GestureDetector(
            onTap: () {
              controller.searchIsSelected.value = !controller.searchIsSelected.value;
            },
            child: Assets.vec.searchSvg.svg(
              width: 24,
              height: 24,
              colorFilter: const ColorFilter.mode(Colors.white, BlendMode.srcIn),
            ),
          ),
          SizedBox(width: 8),
          GestureDetector(
            onTap: () {
              Get.bottomSheet(filterBottomSheet());
            },
            child: Assets.vec.filterOutlineSvg.svg(
              width: 20,
              height: 20,
              colorFilter: const ColorFilter.mode(Colors.white, BlendMode.srcIn),
            ),
          ),
          SizedBox(width: 8),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            routePageWidget(),
            buildSearchWidget(),
            inventoryWidget(),
            allocationsMade(),
            SizedBox(height: 40),
          ],
        ),
      ),
      floatingActionButton: RFab.add(
        onPressed: () {
          Get.bottomSheet(showAddBottomSheet(), isScrollControlled: true, backgroundColor: Colors.transparent);
        },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.startFloat,
    );
  }

  Widget inventoryWidget() {
    return Container(
      width: Get.width,
      height: 39,
      margin: EdgeInsets.all(4),
      decoration: BoxDecoration(color: AppColor.greenLight, borderRadius: BorderRadius.circular(8)),
      alignment: Alignment.center,
      child: ObxValue((data) {
        return Text(
          ' موجودی انبار: ${data.value?.totalRemainWeight?.toInt().separatedByComma ?? '0'} کیلوگرم',
          style: AppFonts.yekan16.copyWith(color: AppColor.mediumGreyDarkHover),
        );
      }, controller.rootLogic.inventoryModel),
    );
  }

  Widget buildRow(String title, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Flexible(
            flex: 2,
            child: Text(
              title,
              textAlign: TextAlign.right,
              style: AppFonts.yekan14.copyWith(color: AppColor.darkGreyDarkHover),
            ),
          ),
          Flexible(
            flex: 2,
            child: Text(
              value,
              textAlign: TextAlign.left,
              style: AppFonts.yekan14.copyWith(color: AppColor.darkGreyDarkHover),
            ),
          ),
        ],
      ),
    );
  }

  Widget allocationsMade() {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 6),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('تخصیصات صورت گرفته', style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal)),
              RElevated(
                text: 'تایید یکجا',
                height: 30,
                textStyle: AppFonts.yekan12.copyWith(color: Colors.white),
                onPressed: () {
                  controller.confirmAllAllocations();
                },
              ),
            ],
          ),
        ),
        ObxValue((data) {
          if (data.value == null) {
            return Container(
              height: 80,
              margin: const EdgeInsets.all(4),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: AppColor.blueNormal, width: 1),
              ),
              child: Center(child: CircularProgressIndicator()),
            );
          } else if (data.value?.isEmpty ?? true) {
            return Container(
              height: 80,
              margin: const EdgeInsets.all(8),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: AppColor.blueNormal, width: 1),
              ),
              child: Center(child: Text('هیچ تخصیصات صورت نگرفته  است ')),
            );
          } else {
            return Container(
              margin: const EdgeInsets.symmetric(vertical: 2),
              child: ListView.separated(
                padding: const EdgeInsets.all(8.0),
                shrinkWrap: true,
                controller: controller.scrollControllerAllocationsMade,
                itemCount: data.value?.length ?? 0,
                itemBuilder: (BuildContext context, int index) {
                  if (index == data.value!.length) {
                    return Obx(
                      () => controller.isLoadingMoreAllocationsMade.value
                          ? const Padding(
                              padding: EdgeInsets.symmetric(vertical: 8),
                              child: Center(child: CircularProgressIndicator()),
                            )
                          : const SizedBox(),
                    );
                  }
                  final result = data.value![index];
                  return ObxValue((data) {
                    return allocationsMadeListItem(expandList: controller.isExpandedList, index: index, item: result);
                  }, controller.isExpandedList);
                },
                separatorBuilder: (BuildContext context, int index) => SizedBox(height: 8),
              ),
            );
          }
        }, controller.allocatedMadeModel),
      ],
    );
  }

  Widget showAddBottomSheet([bool isEditMode = false]) {
    return BaseBottomSheet(
      height: Get.height * (isEditMode ? 0.45 : 0.75),
      child: Padding(
        padding: EdgeInsets.only(
          left: 16,
          right: 16,
          top: 16,
          bottom: MediaQuery.of(Get.context!).viewInsets.bottom + 16,
        ),
        child: Form(
          key: controller.formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '${isEditMode ? 'ویرایش' : 'ثبت'} توزیع/ فروش',
                style: AppFonts.yekan16Bold.copyWith(color: AppColor.blueNormal),
              ),
              Visibility(
                visible: isEditMode == false,
                child: Column(
                  children: [
                    const SizedBox(height: 12),
                    RTextField(
                      controller: TextEditingController(),
                      label: 'تاریخ',
                      enabled: false,
                      initText: Jalali.now().formatCompactDate(),
                    ),
                    const SizedBox(height: 12),
                    Material(type: MaterialType.transparency, child: productDropDown()),
                    const SizedBox(height: 12),
                    SizedBox(
                      height: 40,
                      child: ObxValue((data) {
                        return Row(
                          children: [
                            Radio(
                              value: 1,
                              groupValue: controller.saleType.value,
                              onChanged: (value) {
                                controller.saleType.value = value!;

                                controller.selectedGuildModel.value = null;
                                controller.selectedGuildModel.refresh();
                              },
                            ),
                            Text('فروش اختصاصی', style: AppFonts.yekan14),
                            SizedBox(width: 12),
                            Radio(
                              value: 2,
                              groupValue: controller.saleType.value,
                              onChanged: (value) {
                                controller.saleType.value = value!;
                              },
                            ),
                            Text('فروش آزاد', style: AppFonts.yekan14),
                          ],
                        );
                      }, controller.saleType),
                    ),
                    const SizedBox(height: 12),

                    guildsDropDown(),
                  ],
                ),
              ),
              const SizedBox(height: 12),
              RTextField(
                controller: controller.weightController,
                keyboardType: TextInputType.number,
                borderColor: AppColor.darkGreyLight,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly, SeparatorInputFormatter()],
                validator: (value) {

                  if (int.parse(value!.clearComma) > (controller.rootLogic.inventoryModel.value?.totalRemainWeight?.toInt() ?? 100) ){
                    return 'وزن تخصیصی بیشتر از موجودی انبار است';
                  }
                  return null;
                },
                onChanged: (p0) {
                  controller.weight.value = int.tryParse(p0.clearComma) ?? 0;
                },
                label: 'وزن لاشه',
              ),
              const SizedBox(height: 12),
              RTextField(
                controller: controller.pricePerKiloController,
                borderColor: AppColor.darkGreyLight,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly, SeparatorInputFormatter()],

                onChanged: (p0) {
                  controller.pricePerKilo.value = int.tryParse(p0.clearComma) ?? 0;
                },
                keyboardType: TextInputType.number,
                label: 'قیمت هر کیلو',
              ),
              const SizedBox(height: 12),
              RTextField(
                enabled: false,
                keyboardType: TextInputType.number,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly, SeparatorInputFormatter()],
                borderColor: AppColor.darkGreyLight,
                controller: controller.totalCostController,
                label: 'هزینه کل',
              ),
              const SizedBox(height: 20),
              ObxValue((data) {
                return RElevated(
                  text: isEditMode ? 'ویرایش' : 'ثبت',
                  textStyle: AppFonts.yekan16.copyWith(color: Colors.white),
                  height: 40,
                  onPressed: data.value
                      ? () async {
                    if (controller.formKey.currentState?.validate() ?? false) {
                      iLog("s2");
                      controller.setSubmitData();
                      iLog("s3");
                      Get.bottomSheet(show2StepAddBottomSheet());
                    }
                         /* isEditMode
                              ? await controller.updateAllocation()
                              : () {
                                  iLog("s1");
                                  if (controller.formKey.currentState?.validate() ?? false) {
                                    iLog("s2");
                                    controller.setSubmitData();
                                    iLog("s3");
                                    Get.bottomSheet(show2StepAddBottomSheet());
                                  }
                                };

                          controller.clearForm();
                          controller.getAllocatedMade();
                          Get.back();*/
                        }
                      : null,
                );
              }, controller.isValid),
              const SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }

  Widget guildsDropDown() {
    return Obx(() {
      final item = controller.selectedGuildModel.value;
      return OverlayDropdownWidget<GuildModel>(
        key: ValueKey(item?.user?.fullname ?? ''),
        items: controller.guildsModel,
        onChanged: (value) {
          controller.selectedGuildModel.value = value;
        },
        selectedItem: item,
        itemBuilder: (item) => Text(
          item.user != null
              ? '${item.steward == true ? 'مباشر' : 'صنف'} ${item.user!.fullname} (${item.user!.mobile})'
              : 'بدون نام',
        ),
        labelBuilder: (item) => Text(
          item?.user != null
              ? '${item?.steward == true ? 'مباشر' : 'صنف'} ${item?.user!.fullname} (${item?.user!.mobile})'
              : 'انتخاب مباشر/صنف',
        ),
      );
    });
  }

  Widget productDropDown() {
    return Obx(() {
      return OverlayDropdownWidget<ProductModel>(
        items: controller.rolesProductsModel,
        onChanged: (value) {
          controller.selectedProductModel.value = value;
        },
        selectedItem: controller.selectedProductModel.value,
        itemBuilder: (item) => Text(item.name ?? 'بدون نام'),
        labelBuilder: (item) => Text(item?.name ?? 'انتخاب محصول'),
      );
    });
  }

  Padding routePageWidget() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        children: [
          SizedBox(width: 8),
          RichText(
            text: TextSpan(
              style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
              children: [
                WidgetSpan(
                  child: Row(
                    children: [
                      Assets.vec.cubeSearchSvg.svg(
                        width: 24,
                        height: 24,
                        colorFilter: const ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
                      ),
                      SizedBox(width: 6),
                    ],
                  ),
                ),

                TextSpan(text: 'داخل استان'),
                TextSpan(text: '/'),
                TextSpan(text: 'فروش'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget allocationsMadeListItem({
    required RxList<int> expandList,
    required int index,
    required AllocatedMadeModel item,
  }) {
    return GestureDetector(
      onTap: () {
        if (expandList.contains(index)) {
          controller.isExpandedList.remove(index);
        } else {
          controller.isExpandedList.add(index);
        }
      },
      child: Container(
        width: Get.width,
        margin: const EdgeInsets.fromLTRB(0, 0, 10, 0),
        decoration: BoxDecoration(color: getTintColor(item), borderRadius: BorderRadius.circular(8)),
        child: AnimatedSize(
          duration: Duration(milliseconds: 400),
          alignment: Alignment.center,
          child: Stack(
            clipBehavior: Clip.none,
            alignment: Alignment.centerRight,
            children: [
              AnimatedSize(
                duration: Duration(milliseconds: 300),
                child: Container(
                  width: Get.width - 30,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(width: 2, color: getTintColor(item)),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: AnimatedCrossFade(
                          alignment: Alignment.center,
                          firstChild: Container(
                            height: 75,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.only(
                                bottomLeft: Radius.zero,
                                bottomRight: Radius.circular(8),
                                topLeft: Radius.zero,
                                topRight: Radius.circular(8),
                              ),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,

                              children: [
                                SizedBox(width: 12),

                                Expanded(
                                  flex: 2,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    spacing: 4,
                                    children: [
                                      Text(
                                        item.steward?.user?.fullname ?? 'N/A',
                                        textAlign: TextAlign.center,
                                        style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                                      ),

                                      SizedBox(height: 2),
                                      Text(
                                        item.createDate?.formattedJalaliDate ?? 'N/A',
                                        textAlign: TextAlign.center,
                                        style: AppFonts.yekan14.copyWith(color: AppColor.bgDark),
                                      ),
                                    ],
                                  ),
                                ),

                                SizedBox(width: 8),
                                Expanded(
                                  flex: 2,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    spacing: 4,
                                    children: [
                                      Text(
                                        '${item.weightOfCarcasses.separatedByComma} Kg',
                                        textAlign: TextAlign.center,
                                        style: AppFonts.yekan12.copyWith(color: AppColor.bgDark),
                                      ),
                                      Text(
                                        '${item.amount.separatedByComma} ریال',
                                        textAlign: TextAlign.center,
                                        style: AppFonts.yekan12.copyWith(color: AppColor.darkGreyDark),
                                      ),
                                    ],
                                  ),
                                ),
                                Expanded(
                                  flex: 1,
                                  child: Text(
                                    '${item.allocationType?.faAllocationType}',
                                    textAlign: TextAlign.center,
                                    style: AppFonts.yekan10.copyWith(color: AppColor.darkGreyDark),
                                  ),
                                ),

                                SizedBox(width: 8),
                              ],
                            ),
                          ),
                          secondChild: Container(
                            padding: EdgeInsets.fromLTRB(8, 12, 14, 12),

                            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8)),
                            child: Column(
                              spacing: 8,
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        controller.setEditData(item);
                                        Get.bottomSheet(
                                          showAddBottomSheet(true),
                                          isScrollControlled: true,
                                        ).whenComplete(() {
                                          controller.clearForm();
                                        });
                                      },
                                      child: Assets.vec.editSvg.svg(
                                        width: 20,
                                        height: 20,
                                        colorFilter: ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
                                      ),
                                    ),

                                    Text(
                                      item.allocationType?.faAllocationType,
                                      textAlign: TextAlign.center,
                                      style: AppFonts.yekan16.copyWith(color: AppColor.greenDark),
                                    ),

                                    GestureDetector(
                                      onTap: () {
                                        buildDeleteDialog(
                                          onConfirm: () {
                                            expandList.remove(index);
                                            return controller.deleteAllocation(item);
                                          },
                                        );
                                      },
                                      child: Assets.vec.trashSvg.svg(
                                        width: 16,
                                        height: 16,
                                        colorFilter: ColorFilter.mode(AppColor.error, BlendMode.srcIn),
                                      ),
                                    ),
                                  ],
                                ),

                                buildRow('تاریخ ثبت', item.date!.formattedJalaliDate ?? 'N/A'),
                                buildRow(
                                  'نام و نام خانوادگی خریدار',
                                  getBuyerInformation(item)?.user?.fullname ?? 'N/A',
                                ),
                                buildRow('شماره خریدار', getBuyerInformation(item)?.user?.mobile ?? 'N/A'),
                                buildRow('نوع فروش', item.sellType?.faItem ?? 'N/A'),
                                buildRow('قیمت هر کیلو', '${item.amount.separatedByComma ?? 0} ریال '),
                                buildRow('قیمت کل', '${item.totalAmount.separatedByComma ?? 0} ریال'),
                                buildRow(
                                  'وزن تخصیصی',
                                  '${item.weightOfCarcasses?.toInt().separatedByComma ?? 0} کیلوگرم',
                                ),
                                buildRow('کداحراز', item.registrationCode?.toString() ?? 'N/A'),
                                buildRow(
                                  'وضعیت کد احراز',
                                  item.systemRegistrationCode == true ? "ارسال شده" : "ارسال نشده" ?? 'N/A',
                                ),
                                buildRow('افت وزن(کیلوگرم)', item.weightLossOfCarcasses?.toInt().toString() ?? 'N/A'),

                                Row(
                                  spacing: 10,
                                  children: [
                                    Expanded(
                                      child: RElevated(
                                        backgroundColor: AppColor.greenNormal,
                                        height: 40,
                                        text: 'تایید',
                                        textStyle: AppFonts.yekan18.copyWith(color: Colors.white),
                                        onPressed: () {
                                          ConformAllocation confromation = ConformAllocation(
                                            allocation_key: item.key,
                                            number_of_carcasses: item.numberOfCarcasses,
                                            weight_of_carcasses: item.weightOfCarcasses?.toInt(),
                                            amount: item.amount,
                                            total_amount: item.totalAmount,
                                          );

                                          controller.confirmAllocation(confromation);
                                        },
                                      ),
                                    ),
                                    Expanded(
                                      child: ROutlinedElevated(
                                        height: 40,
                                        borderColor: AppColor.error,
                                        text: 'رد',
                                        textStyle: AppFonts.yekan18.copyWith(color: AppColor.error),
                                        onPressed: () {
                                          controller.denyAllocation(item.key ?? '');
                                        },
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          crossFadeState: expandList.contains(index)
                              ? CrossFadeState.showSecond
                              : CrossFadeState.showFirst,
                          duration: Duration(milliseconds: 300),
                        ),
                      ),
                      Container(
                        width: 20,
                        child: Center(
                          child: RotatedBox(
                            quarterTurns: 3,
                            child: Text(item.state?.faItem, style: AppFonts.yekan8, textAlign: TextAlign.center),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              Positioned(
                right: -12,
                child: Container(
                  width: index < 999 ? 24 : null,
                  height: index < 999 ? 24 : null,
                  padding: EdgeInsets.all(2),
                  decoration: BoxDecoration(
                    color: AppColor.greenLightHover,
                    borderRadius: BorderRadius.circular(4),
                    border: Border.all(width: 0.50, color: AppColor.greenDarkActive),
                  ),
                  alignment: Alignment.center,
                  child: Text((index + 1).toString(), style: AppFonts.yekan12.copyWith(color: Colors.black)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Color getTintColor(AllocatedMadeModel model) {
    Color res;

    if (model.receiverState == 'pending') {
      res = AppColor.yellowNormal;
    } else if (model.receiverState == 'approved') {
      res = AppColor.greenLightActive;
    } else if (model.receiverState == 'rejected') {
      res = AppColor.redLight;
    } else {
      res = AppColor.blueLight;
    }

    return res;
  }

  Steward? getBuyerInformation(AllocatedMadeModel model) {
    if (model.allocationType?.buyerIsGuild) {
      return model.toGuilds;
    } else {
      return model.steward;
    }
  }

  Future<void> buildDeleteDialog({required Future<void> Function() onConfirm}) async {
    await Get.defaultDialog(
      title: 'حذف ',
      middleText: 'آیا از حذف این مورد مطمئن هستید؟',
      confirm: ElevatedButton(
        style: ElevatedButton.styleFrom(backgroundColor: AppColor.error, foregroundColor: Colors.white),
        onPressed: () async {
          await onConfirm();
          Get.back();
        },
        child: Text('بله'),
      ),
      cancel: ElevatedButton(
        onPressed: () {
          Get.back();
        },
        child: Text('خیر'),
      ),
    ).whenComplete(() => controller.getAllocatedMade());
  }

  ObxValue<RxBool> buildSearchWidget() {
    return ObxValue((data) {
      return AnimatedContainer(
        duration: Duration(milliseconds: 300),
        padding: EdgeInsets.only(top: 5),
        curve: Curves.easeInOut,
        height: data.value ? 50 : 0,
        child: Visibility(
          visible: data.value,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8),
            child: RTextField(
              suffixIcon: Padding(
                padding: const EdgeInsets.all(12.0),
                child: Assets.vec.searchSvg.svg(
                  width: 10,
                  height: 10,
                  colorFilter: ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
                ),
              ),
              hintText: 'جستجو',
              onChanged: (value) {
                controller.searchedValue.value = value;
              },
              controller: TextEditingController(),
            ),
          ),
        ),
      );
    }, controller.searchIsSelected);
  }

  Widget filterBottomSheet() {
    return BaseBottomSheet(
      height: 250,
      child: Column(
        spacing: 16,
        children: [
          Text('فیلترها', style: AppFonts.yekan16Bold.copyWith(color: AppColor.darkGreyDarkHover)),
          Row(
            spacing: 8,
            children: [
              Expanded(
                child: timeFilterWidget(
                  date: controller.fromDateFilter,
                  onChanged: (jalali) => controller.fromDateFilter.value = jalali,
                ),
              ),
              Expanded(
                child: timeFilterWidget(
                  isFrom: false,
                  date: controller.toDateFilter,
                  onChanged: (jalali) => controller.toDateFilter.value = jalali,
                ),
              ),
            ],
          ),
          SizedBox(height: 2),
          RElevated(
            text: 'اعمال فیلتر',
            onPressed: () {
              controller.getAllocatedMade();
              Get.back();
            },
            height: 40,
          ),
          SizedBox(height: 16),
        ],
      ),
    );
  }

  GestureDetector timeFilterWidget({
    isFrom = true,
    required Rxn<Jalali> date,
    required Function(Jalali jalali) onChanged,
  }) {
    return GestureDetector(
      onTap: () {
        Get.bottomSheet(modalDatePicker((value) => onChanged(value)));
      },
      child: Container(
        height: 35,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(width: 1, color: AppColor.blueNormal),
        ),
        padding: EdgeInsets.symmetric(horizontal: 11, vertical: 4),
        child: Row(
          spacing: 8,
          children: [
            Assets.vec.calendarSvg.svg(
              width: 24,
              height: 24,
              colorFilter: const ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
            ),
            Text(isFrom ? 'از' : 'تا', style: AppFonts.yekan16.copyWith(color: AppColor.blueNormal)),
            Expanded(
              child: ObxValue((data) {
                return Text(
                  date.value?.formatCompactDate() ?? Jalali.now().formatCompactDate(),
                  textAlign: TextAlign.center,
                  style: AppFonts.yekan16.copyWith(color: AppColor.lightGreyNormalActive),
                );
              }, date),
            ),
          ],
        ),
      ),
    );
  }

  Container modalDatePicker(ValueChanged<Jalali> onDateSelected) {
    Jalali? tempPickedDate;
    return Container(
      height: 250,
      color: Colors.white,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            child: Row(
              children: [
                SizedBox(width: 20),
                RElevated(
                  height: 35,
                  width: 70,
                  textStyle: AppFonts.yekan14.copyWith(color: Colors.white),
                  onPressed: () {
                    onDateSelected(tempPickedDate ?? Jalali.now());
                    Get.back();
                  },
                  text: 'تایید',
                ),
                Spacer(),
                RElevated(
                  height: 35,
                  width: 70,
                  backgroundColor: AppColor.error,
                  textStyle: AppFonts.yekan14.copyWith(color: Colors.white),
                  onPressed: () {
                    onDateSelected(tempPickedDate ?? Jalali.now());
                    Get.back();
                  },
                  text: 'لغو',
                ),
                SizedBox(width: 20),
              ],
            ),
          ),
          Divider(height: 0, thickness: 1),
          Expanded(
            child: Container(
              child: PersianCupertinoDatePicker(
                initialDateTime: Jalali.now(),
                mode: PersianCupertinoDatePickerMode.date,
                onDateTimeChanged: (dateTime) {
                  tempPickedDate = dateTime;
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget show2StepAddBottomSheet() {
    return BaseBottomSheet(
      height: Get.height*.35,
      child: Column(
        spacing: 8,
        children: [
          buildRow('تاریخ ثبت', controller.tmpStewardAllocation?.date?.formattedJalaliDate ?? 'N/A'),
          buildRow(
            'نام و نام خانوادگی خریدار',
            controller.guildsModel
                    .firstWhere((p0) => p0.key == controller.tmpStewardAllocation?.guildKey)
                    .user
                    ?.fullname ??
                'N/A',
          ),
          buildRow(
            'شماره خریدار',
            controller.guildsModel.firstWhere((p0) => p0.key == controller.tmpStewardAllocation?.guildKey).user?.mobile ??
                'N/A',
          ),

          buildRow('قیمت هر کیلو', '${controller.tmpStewardAllocation?.amount.separatedByComma ?? 0} ریال '),
          buildRow(
            'وزن تخصیصی',
            '${controller.tmpStewardAllocation?.weightOfCarcasses?.toInt().separatedByComma ?? 0} کیلوگرم',
          ),
          buildRow('قیمت کل', '${controller.tmpStewardAllocation?.totalAmount.separatedByComma ?? 0} ریال'),

          Row(
            spacing: 10,
            children: [
              Expanded(
                child: RElevated(
                  backgroundColor: AppColor.greenNormal,
                  height: 40,
                  text: 'ثبت',
                  textStyle: AppFonts.yekan18.copyWith(color: Colors.white),
                  onPressed: () async {
                     await controller.submitAllocation();
                     Get..back()..back();
                  },
                ),
              ),
              Expanded(
                child: ROutlinedElevated(
                  height: 40,
                  borderColor: AppColor.error,
                  text: ' بازگشت',
                  textStyle: AppFonts.yekan18.copyWith(color: AppColor.error),
                  onPressed: () {
                    Get.until((route) => route.settings.name == ChickenRoutes.salesInProvince);
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
