import 'package:flutter/cupertino.dart';
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/pages/sales_out_of_province/logic.dart';
import 'package:rasadyar_chicken/presentation/pages/sales_out_of_province/widgets/search_widget.dart';
import 'package:rasadyar_core/core.dart';

import '../widgets/empty_widget.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          searchWidget(controller.searchIsSelected, (data) {
            controller.searchedValue.value = data;
            controller.getOutProvinceCarcassesBuyer();
          }),

          buyerListWidget(),
        ],
      ),
      floatingActionButton: RFab.add(
        onPressed: () {
          Get.bottomSheet(
            addOrEditBuyerBottomSheet(),
            isScrollControlled: true,
          );
        },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.startFloat,
    );
  }

  Widget buyerListWidget() {
    return ObxValue((data) {
      switch (data.value.status) {
        case Status.initial:
        case Status.loading:
          return Center(child: CupertinoActivityIndicator());
        case Status.success:
          return ListView.separated(
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            padding: EdgeInsets.fromLTRB(8, 8, 18, 80),
            itemBuilder: (context, index) {
              return ObxValue(
                (expandList) => buyerListItem(
                  expandList: expandList,
                  index: index,
                  item: data.value.data![index],
                ),
                controller.isExpandedList,
              );
            },
            separatorBuilder: (context, index) => SizedBox(height: 8),
            itemCount: data.value.data?.length ?? 0,
          );
        case Status.error:
          return Center(
            child: Text(
              data.value.message ?? 'خطا در دریافت اطلاعات',
              style: AppFonts.yekan16.copyWith(color: AppColor.error),
            ),
          );
        case Status.empty:
          return emptyWidget();
      }
    }, controller.buyerList);
  }

  GestureDetector buyerListItem({
    required RxList<int> expandList,
    required int index,
    required OutProvinceCarcassesBuyer item,
  }) {
    return GestureDetector(
      onTap: () {
        if (expandList.contains(index)) {
          controller.isExpandedList.remove(index);
        } else {
          controller.isExpandedList.add(index);
        }
      },
      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: 0.5,
                    color: AppColor.darkGreyNormal,
                  ),
                ),
                child: AnimatedCrossFade(
                  alignment: Alignment.center,
                  firstChild: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        SizedBox(width: 12),

                        Expanded(
                          flex: 2,
                          child: Column(
                            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: 8),
                        Expanded(
                          flex: 2,
                          child: Text(
                            '${item.unitName}',
                            textAlign: TextAlign.center,
                            style: AppFonts.yekan12.copyWith(
                              color: AppColor.bgDark,
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Text(
                            '${item.buyer?.province}\n${item.buyer?.city}',
                            textAlign: TextAlign.center,
                            style: AppFonts.yekan12.copyWith(
                              color: AppColor.darkGreyDark,
                            ),
                          ),
                        ),

                        Icon(CupertinoIcons.chevron_down, size: 12),
                        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.setEditDataBuyer(item);
                                Get.bottomSheet(
                                  addOrEditBuyerBottomSheet(true),
                                  isScrollControlled: true,
                                ).whenComplete(() {
                                  controller.resetSubmitForm();
                                });
                              },
                              child: Assets.vec.editSvg.svg(
                                width: 20,
                                height: 20,
                                colorFilter: ColorFilter.mode(
                                  AppColor.blueNormal,
                                  BlendMode.srcIn,
                                ),
                              ),
                            ),

                            Text(
                              '${item.province}-${item.city}',
                              textAlign: TextAlign.center,
                              style: AppFonts.yekan16.copyWith(
                                color: AppColor.greenDark,
                              ),
                            ),

                            SizedBox(),
                          ],
                        ),

                        buildRow('مشخصات خریدار', item.fullname ?? 'N/A'),
                        buildRow('نام واحد', item.unitName ?? 'N/A'),
                        buildRow(
                          'تعداد درخواست ها',
                          '${item.requestsInfo?.numberOfRequests.separatedByComma}',
                        ),
                        buildRow(
                          'وزن',
                          '${item.requestsInfo?.totalWeight.separatedByComma}',
                        ),
                      ],
                    ),
                  ),
                  crossFadeState: expandList.contains(index)
                      ? CrossFadeState.showSecond
                      : CrossFadeState.showFirst,
                  duration: Duration(milliseconds: 300),
                ),
              ),
            ),
            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),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  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 addOrEditBuyerBottomSheet([bool isOnEdit = false]) {
    return BaseBottomSheet(
      height: 600,
      child: SingleChildScrollView(
        child: Form(
          key: controller.formKey,
          child: Column(
            spacing: 16,
            children: [
              Text(
                isOnEdit ? 'ویرایش خریدار' : 'افزودن خریدار',
                style: AppFonts.yekan16Bold.copyWith(
                  color: AppColor.darkGreyDarkHover,
                ),
              ),

              RTextField(
                controller: controller.buyerPhoneController,
                label: 'تلفن خریدار',
                keyboardType: TextInputType.phone,
                borderColor: AppColor.darkGreyLight,
                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.buyerNameController,
                label: 'نام خریدار',
                borderColor: AppColor.darkGreyLight,
              ),
              RTextField(
                controller: controller.buyerLastNameController,
                label: 'نام خانوادگی خریدار',
                borderColor: AppColor.darkGreyLight,
              ),

              RTextField(
                controller: controller.buyerUnitNameController,
                label: 'نام واحد',
                borderColor: AppColor.darkGreyLight,
              ),
              _provinceWidget(),
              _cityWidget(),
              submitButtonWidget(isOnEdit),
              SizedBox(),
            ],
          ),
        ),
      ),
    );
  }

  Widget submitButtonWidget(bool isOnEdit) {
    return ObxValue((data) {
      return RElevated(
        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);
  }
}
