import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rasadyar_chicken/data/models/response/out_province_carcasses_buyer/out_province_carcasses_buyer.dart';
import 'package:rasadyar_chicken/data/models/response/roles_products/roles_products.dart';
import 'package:rasadyar_chicken/data/models/response/steward_free_sale_bar/steward_free_sale_bar.dart';
import 'package:rasadyar_chicken/presentation/routes/routes.dart';
import 'package:rasadyar_chicken/presentation/utils/nested_keys_utils.dart';
import 'package:rasadyar_chicken/presentation/widget/base_page/view.dart';
import 'package:rasadyar_chicken/presentation/widget/filter_bottom_sheet.dart';
import 'package:rasadyar_chicken/presentation/widget/steward/inventory_widget.dart';
import 'package:rasadyar_core/core.dart';

import 'logic.dart';

class SalesOutOfProvincePage extends GetView<SalesOutOfProvinceLogic> {
  const SalesOutOfProvincePage({super.key});

  @override
  Widget build(BuildContext context) {
    return ChickenBasePage(
      routes: controller.routesName,
      backId: stewardSecondKey,
      onRefresh: controller.onRefresh,
      onSearchChanged: (data) => controller.setSearchValue(data),
      onFilterTap: () {
        Get.bottomSheet(filterBottomSheet());
      },
      child: Stack(
        children: [
          Positioned.fill(
            child: Column(
              children: [
                inventoryWidget(controller.rootLogic),

                ObxValue((data) {
                  return RPaginatedListView(
                    onLoadMore: () async => controller.getOutProvinceSales(true),
                    hasMore: data.value.data?.next != null,
                    listType: ListType.separated,
                    resource: data.value,
                    padding: EdgeInsets.fromLTRB(8, 8, 8, 80),
                    itemBuilder: (context, index) {
                      var item = data.value.data!.results![index];
                      return ObxValue((val) {
                        return ExpandableListItem2(
                          selected: val.value == index,
                          onTap: () => controller.toggleExpansion(index: index),
                          index: index,
                          child: itemListWidget(item),
                          secondChild: itemListExpandedWidget(item, index),
                          labelColor: AppColor.blueLight,
                          labelIcon: Assets.vec.timerSvg.path,
                        );
                      }, controller.expandedListIndex);
                    },
                    itemCount: data.value.data?.results?.length ?? 0,
                    separatorBuilder: (context, index) => SizedBox(height: 8.h),
                  );
                }, controller.salesList),
              ],
            ),
          ),
          Positioned(
            right: 5,
            left: 0,
            bottom: 95,
            child: Row(
              children: [
                RFab.add(
                  onPressed: () {
                    Get.bottomSheet(addOrEditSaleBottomSheet(), isScrollControlled: true).then((
                      value,
                    ) {
                      controller.clearSaleForm();
                    });
                  },
                ),
                Spacer(),
                RFab(
                  icon: Icon(CupertinoIcons.person_add_solid, color: Colors.white, size: 35.w),
                  backgroundColor: AppColor.blueNormal,
                  onPressed: () {
                    Get.toNamed(ChickenRoutes.salesOutOfProvinceBuyerSteward, id: stewardSecondKey);
                  },
                ),
                SizedBox(width: 25),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /*  Padding segmentWidget() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
      child: Row(
        children: [
          Expanded(
            child: RSegment(
              children: ['فروش', 'خریداران'],
              selectedIndex: controller.selectedSegmentIndex.value,
              borderColor: const Color(0xFFB4B4B4),
              selectedBorderColor: AppColor.blueNormal,
              selectedBackgroundColor: AppColor.blueLight,
              onSegmentSelected: (index) => controller.selectedSegmentIndex.value = index,
              backgroundColor: AppColor.whiteGreyNormal,
            ),
          ),
        ],
      ),
    );
  }*/

  Widget filterBottomSheet() => filterBottomSheetWidget(
    fromDate: controller.fromDateFilter,
    onChangedFromDate: (jalali) => controller.fromDateFilter.value = jalali,
    toDate: controller.toDateFilter,
    onChangedToDate: (jalali) => controller.toDateFilter.value = jalali,
    onSubmit: () => controller.submitFilter(),
  );

  itemListWidget(StewardFreeSaleBar item) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        SizedBox(width: 12),
        Expanded(
          flex: 3,
          child: Text(
            item.date?.formattedJalaliDate ?? 'N/A',
            textAlign: TextAlign.center,
            style: AppFonts.yekan12.copyWith(color: AppColor.bgDark),
          ),
        ),
        SizedBox(width: 4),
        Expanded(
          flex: 5,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                item.buyer?.fullname ?? 'N/A',
                textAlign: TextAlign.center,
                style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
              ),

              SizedBox(height: 2),
              Text(
                item.buyer?.mobile ?? 'N/A',
                textAlign: TextAlign.center,
                style: AppFonts.yekan14.copyWith(color: AppColor.bgDark),
              ),
            ],
          ),
        ),
        SizedBox(width: 4),
        Expanded(
          flex: 4,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            spacing: 8,
            children: [
              Text(
                item.buyer?.unitName ?? 'N/A',
                textAlign: TextAlign.center,
                style: AppFonts.yekan12.copyWith(color: AppColor.bgDark),
              ),
              Text(
                '${item.weightOfCarcasses?.separatedByCommaFa ?? 0}KG',
                textAlign: TextAlign.center,
                style: AppFonts.yekan12.copyWith(color: AppColor.bgDark),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 2,
          child: Text(
            '${item.buyer?.province}\n${item.buyer?.city}',
            textAlign: TextAlign.center,
            style: AppFonts.yekan12.copyWith(color: AppColor.bgDark),
          ),
        ),
      ],
    );
  }

  itemListExpandedWidget(StewardFreeSaleBar item, int index) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8)),
      child: Column(
        spacing: 8,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(
                '${item.province} - ${item.city}',
                textAlign: TextAlign.center,
                style: AppFonts.yekan16.copyWith(color: AppColor.greenDark),
              ),
            ],
          ),
          Container(
            height: 32,
            padding: EdgeInsets.symmetric(horizontal: 8),
            decoration: ShapeDecoration(
              color: AppColor.blueLight,
              shape: RoundedRectangleBorder(
                side: BorderSide(width: 1, color: AppColor.blueLightHover),
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  spacing: 3,
                  children: [
                    Text(
                      item.date?.toJalali.formatter.wN ?? 'N/A',
                      style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                    ),

                    Text(
                      '${item.date?.toJalali.formatter.d} ${item.date?.toJalali.formatter.mN ?? 'N/A'}',
                      style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                    ),
                  ],
                ),

                Text(
                  '${item.date?.toJalali.formatter.y}',
                  style: AppFonts.yekan20.copyWith(color: AppColor.textColor),
                ),

                Text(
                  '${item.date?.toJalali.formatter.tHH}:${item.date?.toJalali.formatter.tMM ?? 'N/A'}',
                  style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                ),
              ],
            ),
          ),
          buildRow(title: 'مشخصات خریدار', value: item.buyer?.fullname ?? 'N/A'),
          buildRow(title: 'تلفن خریدار', value: item.buyer?.mobile ?? 'N/A'),
          buildRow(title: 'نام واحد', value: item.buyer?.unitName ?? 'N/A'),
          buildRow(
            title: 'وزن لاشه (کیلوگرم)',
            value: '${item.weightOfCarcasses?.separatedByCommaFa}',
          ),
          buildRow(
            title: 'حجم تقریبی لاشه (قطعه)',
            value: '${item.numberOfCarcasses?.separatedByCommaFa}',
          ),

          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            spacing: 16.w,
            children: [
              RElevated(
                text: 'ویرایش',
                width: 150.w,
                height: 40.h,
                onPressed: () {
                  controller.setEditDataSales(item);
                  Get.bottomSheet(
                    addOrEditSaleBottomSheet(true),
                    isScrollControlled: true,
                  ).whenComplete(() {
                    controller.resetSubmitForm();
                  });
                },
                textStyle: AppFonts.yekan20.copyWith(color: Colors.white),
                backgroundColor: AppColor.greenNormal,
              ),
              ROutlinedElevated(
                text: 'حذف',
                textStyle: AppFonts.yekan20.copyWith(color: AppColor.redNormal),
                width: 150.w,
                height: 40.h,
                onPressed: () {
                  buildDeleteDialog(
                    onConfirm: () async {
                      controller.toggleExpansion();
                      controller.deleteStewardPurchaseOutOfProvince(item.key!);
                    },
                    onRefresh: () async {
                      controller.onRefresh();
                    },
                  );
                },
                borderColor: AppColor.redNormal,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget addOrEditSaleBottomSheet([bool isOnEdit = false]) {
    return BaseBottomSheet(
      height: 600.h,
      child: SingleChildScrollView(
        child: Form(
          key: controller.formKey,
          child: Column(
            spacing: 16,
            children: [
              Text(
                isOnEdit ? 'ویرایش فروش' : 'افزودن فروش',
                style: AppFonts.yekan16Bold.copyWith(color: AppColor.blueNormal),
              ),
              _productDropDown(),

              Container(
                padding: EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: AppColor.darkGreyLight, width: 1),
                ),
                child: Column(
                  spacing: 12,
                  children: [
                    Row(
                      spacing: 8,
                      children: [
                        Expanded(
                          child: timeFilterWidget(
                            date: controller.saleDate,
                            onChanged: (jalali) => controller.saleDate.value = jalali,
                          ),
                        ),
                      ],
                    ),
                    _buyerWidget(),
                    RTextField(
                      controller: controller.saleWeightController,
                      label: 'وزن لاشه (کیلوگرم)',
                      keyboardType: TextInputType.number,
                      borderColor: AppColor.darkGreyLight,
                      filledColor: AppColor.bgLight,
                      filled: true,
                      inputFormatters: [
                        FilteringTextInputFormatter.digitsOnly,
                        SeparatorInputFormatter(),
                      ],

                      validator: (value) {
                        if (value == null) {
                          return 'لطفاً وزن لاشه را وارد کنید';
                        }
                        return null;
                      },
                    ),

                    RTextField(
                      controller: controller.saleCountController,
                      label: 'حجم تقریبی(قطعه)',
                      keyboardType: TextInputType.number,
                      borderColor: AppColor.darkGreyLight,
                      filledColor: AppColor.bgLight,
                      variant: RTextFieldVariant.noBorder,
                      filled: true,
                      enabled: false,
                      inputFormatters: [
                        FilteringTextInputFormatter.digitsOnly,
                        SeparatorInputFormatter(),
                      ],

                      validator: (value) {
                        if (value == null) {
                          return 'لطفاً قطعه لاشه را وارد کنید';
                        }
                        return null;
                      },
                    ),
                    RTextField(
                      controller: controller.quarantineCodeController,
                      label: 'کد قرنطینه',
                      borderColor: AppColor.darkGreyLight,
                      filledColor: AppColor.bgLight,
                      filled: true,
                      validator: (value) {
                        if (value == null) {
                          return 'لطفاً کد قرنطینه را وارد کنید';
                        }
                        return null;
                      },
                    ),

                    SizedBox(
                      height: 40,
                      child: ObxValue((data) {
                        return RadioGroup(
                          onChanged: (value) {
                            controller.saleType.value = value ?? 0;
                          },
                          groupValue: controller.saleType.value,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Radio(value: 1, enabled: false),
                              Text('فروش دولتی', style: AppFonts.yekan14),
                              SizedBox(width: 12),
                              Radio(value: 2, enabled: isOnEdit ? false : true),
                              Text('فروش آزاد', style: AppFonts.yekan14),
                            ],
                          ),
                        );
                      }, controller.saleType),
                    ),

                    SizedBox(
                      height: 40,
                      child: ObxValue((data) {
                        return RadioGroup(
                          onChanged: (value) {
                            controller.quotaType.value = value ?? 0;
                          },
                          groupValue: controller.quotaType.value,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Radio(value: 1, enabled: isOnEdit ? false : true),
                              Text('انبار دولتی', style: AppFonts.yekan14),
                              SizedBox(width: 12),
                              Radio(value: 2, enabled: isOnEdit ? false : true),
                              Text('انبار آزاد', style: AppFonts.yekan14),
                            ],
                          ),
                        );
                      }, controller.saleType),
                    ),
                  ],
                ),
              ),
              submitButtonWidget(isOnEdit),
              SizedBox(),
            ],
          ),
        ),
      ),
    );
  }

  Widget submitButtonWidget(bool isOnEdit) {
    return ObxValue((data) {
      return RElevated(
        isFullWidth: true,
        backgroundColor: AppColor.greenNormal,
        text: isOnEdit ? 'ویرایش' : 'ثبت',
        onPressed: data.value
            ? () async {
                var res = isOnEdit ? await controller.editSale() : await controller.createSale();
                if (res) {
                  Get.back();
                }
              }
            : null,
        height: 40,
      );
    }, controller.isSaleSubmitButtonEnabled);
  }

  Widget _buyerWidget() {
    return Obx(() {
      return OverlayDropdownWidget<OutProvinceCarcassesBuyer>(
        items: controller.buyerLogic.buyerList.value.data?.results ?? [],
        onChanged: (value) {
          controller.selectedBuyer.value = value;
        },
        selectedItem: controller.selectedBuyer.value,
        itemBuilder: (item) => Text(item.buyer?.fullname ?? 'بدون نام'),
        labelBuilder: (item) => Text(item?.buyer?.fullname ?? 'انتخاب خریدار'),
      );
    });
  }

  Widget _productDropDown() {
    return Obx(() {
      return OverlayDropdownWidget<ProductModel>(
        items: controller.rootLogic.rolesProductsModel,
        height: 56,
        hasDropIcon: false,
        background: Colors.white,
        onChanged: (value) {
          controller.selectedProduct.value = value;
        },
        selectedItem: controller.selectedProduct.value,
        initialValue: controller.selectedProduct.value,
        itemBuilder: (item) => Text(item.name ?? 'بدون نام'),
        labelBuilder: (item) => Row(
          spacing: 8,
          children: [
            (item?.name?.contains('مرغ گرم') ?? false)
                ? Assets.images.chicken.image(width: 40, height: 40)
                : Assets.vec.placeHolderSvg.svg(width: 40, height: 40),

            Text(item?.name ?? 'انتخاب محصول'),
            Spacer(),
            Text(
              'موجودی:${controller.rootLogic.inventoryModel.value?.totalRemainWeight.separatedByCommaFa ?? 0}',
            ),
          ],
        ),
      );
    });
  }

  GestureDetector timeFilterWidget({
    isFrom = true,
    required Rx<Jalali> date,
    required Function(Jalali jalali) onChanged,
  }) {
    return GestureDetector(
      onTap: () {
        Get.bottomSheet(modalDatePicker((value) => onChanged(value)));
      },
      child: Container(
        height: 40,
        decoration: BoxDecoration(
          color: AppColor.bgLight,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(width: 1, color: AppColor.darkGreyLight),
        ),
        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.bgDark, BlendMode.srcIn),
            ),
            Text('تاریخ', style: AppFonts.yekan16.copyWith(color: AppColor.bgDark)),
            Expanded(
              child: ObxValue((data) {
                return Text(
                  date.value.formatCompactDate(),
                  textAlign: TextAlign.center,
                  style: AppFonts.yekan16.copyWith(color: AppColor.darkGreyDark),
                );
              }, 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: controller.saleDate.value,
                mode: PersianCupertinoDatePickerMode.date,
                onDateTimeChanged: (dateTime) {
                  tempPickedDate = dateTime;
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container _informationLabelCard({
    required String title,
    required String description,
    required String iconPath,
    required Color bgDescriptionColor,
    Color? borderColor,
    String unit = 'KG',
    bool isLoading = false,
    Color? iconColor,
    Color? titleColor,
    Color? bgLabelColor,
    LinearGradient? gradient,
  }) {
    return Container(
      height: 40.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: borderColor != null ? Border.all(width: 1, color: borderColor) : null,
      ),
      clipBehavior: Clip.hardEdge,
      child: Row(
        children: [
          // Left side with icon and title
          Expanded(
            child: Container(
              height: 82,
              decoration: BoxDecoration(
                color: gradient == null ? bgLabelColor : null,
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(8),
                  bottomRight: Radius.circular(8),
                ),
                gradient: gradient,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                spacing: 4,
                children: [
                  SvgGenImage.vec(iconPath).svg(
                    width: 24,
                    height: 24,
                    colorFilter: iconColor != null
                        ? ColorFilter.mode(iconColor, BlendMode.srcIn)
                        : null,
                  ),
                  Text(
                    title,
                    textAlign: TextAlign.right,
                    style: AppFonts.yekan14.copyWith(
                      color: titleColor ?? AppColor.mediumGreyDarkActive,
                    ),
                  ),
                ],
              ),
            ),
          ),
          // Right side with description and unit
          Expanded(
            child: Container(
              padding: EdgeInsets.all(2),
              decoration: BoxDecoration(
                color: bgDescriptionColor,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(8),
                  bottomLeft: Radius.circular(8),
                ),
              ),
              child: isLoading
                  ? Center(child: CupertinoActivityIndicator())
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      spacing: 4,
                      children: [
                        Text(
                          description,
                          textAlign: TextAlign.left,
                          maxLines: 1,
                          textDirection: TextDirection.ltr,
                          overflow: TextOverflow.ellipsis,
                          style: AppFonts.yekan14.copyWith(color: AppColor.mediumGreyDarkActive),
                        ),
                        Text(
                          unit,
                          textAlign: TextAlign.center,
                          style: AppFonts.yekan12.copyWith(color: AppColor.mediumGreyDarkActive),
                        ),
                      ],
                    ),
            ),
          ),
        ],
      ),
    );
  }
}
