import 'package:flutter/material.dart';
import 'package:rasadyar_chicken/data/models/response/iran_province_city/iran_province_city_model.dart';
import 'package:rasadyar_chicken/data/models/response/out_province_carcasses_buyer/out_province_carcasses_buyer.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_core/core.dart';

import 'logic.dart';

class SalesOutOfProvinceBuyersPage extends GetView<SalesOutOfProvinceBuyersLogic> {
  const SalesOutOfProvinceBuyersPage({super.key});

  @override
  Widget build(BuildContext context) {
    return ChickenBasePage(
      routes: controller.routesName,
      backId: stewardSecondKey,
      onRefresh: controller.onRefresh,
      onSearchChanged: (data) => controller.setSearchValue(data),
      filteringWidget: filterBottomSheet(),
      child: Stack(
        children: [
          Positioned.fill(
            child: Column(
              children: [
                Container(
                  width: Get.width,
                  height: 39,
                  margin: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: AppColor.greenLight,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: AppColor.textColor, width: 0.5),
                  ),
                  alignment: Alignment.center,
                  child: Text(
                    'لیست خریداران خارج از استان',
                    style: AppFonts.yekan16.copyWith(color: AppColor.mediumGreyDarkHover),
                  ),
                ),

                Expanded(
                  child: ObxValue((data) {
                    return RPaginatedListView(
                      onLoadMore: () async => controller.getOutProvinceCarcassesBuyer(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),
                            labelColor: AppColor.blueLight,
                            labelIcon: Assets.vec.userRaduisSvg.path,
                          );
                        }, controller.expandedListIndex);
                      },
                      itemCount: data.value.data?.results?.length ?? 0,
                      separatorBuilder: (context, index) => SizedBox(height: 8.h),
                    );
                  }, controller.buyerList),
                ),
              ],
            ),
          ),
          Positioned(
            bottom: 100,
            child: RFab.add(
              onPressed: () {
                Get.bottomSheet(
                  addOrEditBuyerBottomSheet(),
                  isScrollControlled: true,
                  ignoreSafeArea: false,
                ).whenComplete(() => controller.resetSubmitForm());
              },
            ),
          ),
        ],
      ),
    );
  }

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

              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: [_provinceWidget(), _cityWidget()]),
              ),

              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: [
                    RTextField(
                      controller: controller.buyerNameController,
                      label: 'نام خریدار',
                      borderColor: AppColor.darkGreyLight,
                      filledColor: AppColor.bgLight,
                      filled: true,
                    ),
                    RTextField(
                      controller: controller.buyerLastNameController,
                      label: 'نام خانوادگی خریدار',
                      borderColor: AppColor.darkGreyLight,
                      filledColor: AppColor.bgLight,
                      filled: true,
                    ),
                    RTextField(
                      controller: controller.buyerPhoneController,
                      label: 'تلفن خریدار',
                      keyboardType: TextInputType.phone,
                      borderColor: AppColor.darkGreyLight,
                      filledColor: AppColor.bgLight,
                      filled: true,
                      maxLength: 11,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'لطفاً شماره موبایل را وارد کنید';
                        }
                        // حذف کاماها برای اعتبارسنجی
                        String cleaned = value.replaceAll(',', '');
                        if (cleaned.length != 11) {
                          return 'شماره موبایل باید ۱۱ رقم باشد';
                        }
                        if (!cleaned.startsWith('09')) {
                          return 'شماره موبایل باید با 09 شروع شود';
                        }
                        return null;
                      },
                    ),
                    RTextField(
                      controller: controller.buyerUnitNameController,
                      label: 'نام واحد',
                      borderColor: AppColor.darkGreyLight,
                      filledColor: AppColor.bgLight,
                      filled: true,
                    ),

                    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 = await controller.createBuyer();
                if (res) {
                  Get.back();
                }
              }
            : null,
        height: 40,
      );
    }, controller.isBuyerSubmitButtonEnabled);
  }

  Widget _provinceWidget() {
    return Obx(() {
      return OverlayDropdownWidget<IranProvinceCityModel>(
        items: controller.rootLogic.provinces,
        onChanged: (value) {
          controller.selectedProvince.value = value;
          print('Selected Product: ${value.name}');
        },
        selectedItem: controller.selectedProvince.value,
        itemBuilder: (item) => Text(item.name ?? 'بدون نام'),
        labelBuilder: (item) => Text(item?.name ?? 'انتخاب استان'),
      );
    });
  }

  Widget _cityWidget() {
    return ObxValue((data) {
      return OverlayDropdownWidget<IranProvinceCityModel>(
        items: data,
        onChanged: (value) {
          controller.selectedCity.value = value;
          print('Selected Product: ${value.name}');
        },
        selectedItem: controller.selectedCity.value,
        itemBuilder: (item) => Text(item.name ?? 'بدون نام'),
        labelBuilder: (item) => Text(item?.name ?? 'انتخاب شهر'),
      );
    }, controller.cites);
  }

  Padding itemListWidget(OutProvinceCarcassesBuyer item) {
    return Padding(
      padding: const EdgeInsets.only(right: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          SizedBox(width: 8),

          Expanded(
            flex: 2,
            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),
                ),
              ],
            ),
          ),

          Expanded(
            flex: 2,
            child: Text(
              '${item.unitName}',
              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.darkGreyDark),
            ),
          ),
        ],
      ),
    );
  }

  itemListExpandedWidget(OutProvinceCarcassesBuyer item) {
    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),
              ),

              SizedBox(),
            ],
          ),

          buildRow(title: 'مشخصات خریدار', value: item.fullname ?? 'N/A'),
          buildRow(title: 'نام واحد', value: item.unitName ?? 'N/A'),
          buildRow(
            title: 'تعداد درخواست ها',
            value: '${item.requestsInfo?.numberOfRequests.separatedByCommaFa}',
          ),
          buildRow(title: 'وزن', value: '${item.requestsInfo?.totalWeight.separatedByCommaFa}'),

          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            spacing: 16.w,
            children: [
              RElevated(
                text: 'ویرایش',
                width: 150.w,
                height: 40.h,
                onPressed: () {
                  controller.setEditDataBuyer(item);
                  Get.bottomSheet(
                    addOrEditBuyerBottomSheet(true),
                    isScrollControlled: true,
                  ).whenComplete(() => controller.resetSubmitForm());
                },
                textStyle: AppFonts.yekan20.copyWith(color: Colors.white),
                backgroundColor: AppColor.greenNormal,
              ),
            ],
          ),
        ],
      ),
    );
  }

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