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_core/core.dart';

import 'logic.dart';

class SalesOutOfProvinceSalesListPage extends GetView<SalesOutOfProvinceSalesListLogic> {
  const SalesOutOfProvinceSalesListPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: 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,
                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),
      floatingActionButton: Row(
        children: [
          RFab.add(
            onPressed: () {
              Get.bottomSheet(
                addOrEditSaleBottomSheet(),
                ignoreSafeArea: false,
                isScrollControlled: true,
              ).whenComplete(() {
                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: 1);
            },
          ),
          SizedBox(width: 25),
        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.startFloat,
    );
  }

  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}'),

          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: () => controller.getOutProvinceSales(),
                  );
                },
                borderColor: AppColor.redNormal,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget addOrEditSaleBottomSheet([bool isOnEdit = false]) {
    return BaseBottomSheet(
      height: 500.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,
                      filled: true,
                      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;
                      },
                    ),
                    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) {
                  controller.getOutProvinceSales();
                  controller.clearSaleForm();
                  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;
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}
