import 'dart:io';

import 'package:flutter/cupertino.dart' hide Image;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rasadyar_chicken/data/models/response/iran_province_city/iran_province_city_model.dart';
import 'package:rasadyar_chicken/data/models/response/roles_products/roles_products.dart';
import 'package:rasadyar_chicken/data/models/response/steward_free_bar/steward_free_bar.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/steward/inventory_widget.dart';
import 'package:rasadyar_core/core.dart';

import 'logic.dart';

class BuyOutOfProvincePage extends GetView<BuyOutOfProvinceLogic> {
  const BuyOutOfProvincePage({super.key});

  @override
  Widget build(BuildContext context) {
    return ChickenBasePage(
      routes: controller.routesName,
      backId: stewardFirstKey,
      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(
                    listType: ListType.separated,
                    resource: data.value,
                    hasMore: data.value.data?.next != null,
                    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),
                          labelColor: AppColor.blueLight,
                          labelIcon: Assets.vec.truckFastOutlinedSvg.path,
                        );
                      }, controller.expandedListIndex);
                    },
                    itemCount: data.value.data?.results?.length ?? 0,
                    separatorBuilder: (context, index) => SizedBox(height: 8.h),
                    onLoadMore: () async => controller.getStewardPurchaseOutOfProvince(true),
                  );
                }, controller.purchaseOutOfProvinceList),
              ],
            ),
          ),
          Positioned(
            right: 5,
            bottom: 95,
            child: RFab.add(
              onPressed: () {
                Get.bottomSheet(
                  addPurchasedInformationBottomSheet(),
                  isScrollControlled: true,
                  ignoreSafeArea: false,
                ).whenComplete(() {
                  controller.resetSubmitForm();
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  Container itemListExpandedWidget(StewardFreeBar 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),
              ),
            ],
          ),
          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.killHouseName ?? 'N/A'),

          buildRow(
            title: 'تلفن فروشنده',
            value: item.killHouseMobile ?? 'N/A',
            valueStyle: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
          ),
          buildRow(title: 'محصول', value: item.product?.name ?? 'N/A'),
          buildRow(
            title: 'وزن خریداری شده',
            value: '${item.weightOfCarcasses?.separatedByCommaFa} کیلوگرم',
          ),
          buildRowOnTapped(
            title: 'مشاهده بارنامه',
            titleStyle: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
            valueWidget: Assets.vec.clipboardEyeSvg.svg(
              width: 20,
              height: 24,
              colorFilter: ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
            ),
            onTap: () {
              Get.bottomSheet(
                BaseBottomSheet(
                  height: 400,
                  child: Column(
                    spacing: 16,
                    children: [
                      Text(
                        'بارنامه',
                        style: AppFonts.yekan16Bold.copyWith(color: AppColor.blueNormal),
                      ),

                      Image.network(
                        item.barImage ?? '',
                        fit: BoxFit.cover,
                        height: 300,
                        errorBuilder: (context, error, stackTrace) {
                          eLog(error.toString());
                          return Center(child: Text('خطایی پیش آمده!'));
                        },
                        loadingBuilder: (context, child, loadingProgress) {
                          if (loadingProgress == null) return child;
                          return CupertinoActivityIndicator();
                        },
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            spacing: 16.w,
            children: [
              RElevated(
                text: 'ویرایش',
                width: 150.w,
                height: 40.h,
                onPressed: () {
                  controller.setEditData(item);
                  Get.bottomSheet(
                    addPurchasedInformationBottomSheet(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: () => controller.deleteStewardPurchaseOutOfProvince(item.key!),
                    onRefresh: () async {
                      controller.rootLogic.onRefresh();
                      controller.onRefresh();
                      controller.toggleExpansion();
                    },
                  );
                },
                borderColor: AppColor.redNormal,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Row itemListWidget(StewardFreeBar item) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        SizedBox(width: 20),
        Expanded(
          flex: 2,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            spacing: 3,
            children: [
              Text(
                item.killHouseName ?? 'N/A',
                textAlign: TextAlign.start,
                style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal),
              ),
              Text(
                item.date?.formattedJalaliDate ?? 'N/A',
                textAlign: TextAlign.center,
                style: AppFonts.yekan14.copyWith(color: AppColor.bgDark),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 3,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                spacing: 3,
                children: [
                  Visibility(
                    visible: item.product?.name?.contains('مرغ گرم') ?? false,
                    child: Assets.vec.hotChickenSvg.svg(
                      width: 24,
                      height: 24,
                      colorFilter: ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
                    ),
                  ),
                  Text(
                    '${item.weightOfCarcasses?.separatedByCommaFa}kg',
                    textAlign: TextAlign.left,
                    style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal),
                  ),
                ],
              ),

              SizedBox(height: 2),

              Text(
                '${item.province}',
                textAlign: TextAlign.center,
                style: AppFonts.yekan12.copyWith(color: AppColor.bgDark),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 1,
          child: Assets.vec.scanSvg.svg(
            width: 32.w,
            height: 32.h,
            colorFilter: ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
          ),
        ),
      ],
    );
  }

  Widget addPurchasedInformationBottomSheet([bool isOnEdit = false]) {
    return BaseBottomSheet(
      child: Form(
        key: controller.formKey,
        child: Column(
          spacing: 8,
          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: [_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.sellerNameController,
                    label: 'نام فروشنده',
                    borderColor: AppColor.darkGreyLight,
                    filled: true,
                    filledColor: AppColor.bgLight,
                  ),
                  RTextField(
                    controller: controller.sellerPhoneController,
                    label: 'تلفن فروشنده',
                    keyboardType: TextInputType.phone,
                    borderColor: AppColor.darkGreyLight,
                    maxLength: 11,
                    filled: true,
                    filledColor: AppColor.bgLight,
                    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;
                    },
                  ),

                  UnitTextField(
                    controller: controller.carcassWeightController,
                    hint: 'وزن',
                    unit: 'کیلوگرم',
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      SeparatorInputFormatter(),
                    ],
                  ),

                  UnitTextField(
                    controller: controller.carcassCountController,
                    hint: 'حجم',
                    unit: 'قطعه',
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      SeparatorInputFormatter(),
                    ],
                  ),
                ],
              ),
            ),
            _imageCarcasesWidget(isOnEdit),
            submitButtonWidget(isOnEdit),
            SizedBox(),
          ],
        ),
      ),
    );
  }

  Widget submitButtonWidget(bool isOnEdit) {
    return Obx(() {
      return RElevated(
        text: isOnEdit ? 'ویرایش' : 'ثبت',
        width: Get.width,
        backgroundColor: AppColor.greenNormal,
        isLoading: controller.isOnLoadingSubmitOrEdit.value,
        enabled: controller.isSubmitButtonEnabled.value,
        onPressed: isOnEdit
            ? () async {
                var res = await controller.editStewardPurchaseOutOfProvince();
                Get.back();
              }
            : () async {
                var res = await controller.createStewardPurchaseOutOfProvince();
                if (res) {
                  Get.back();
                }
              },
        height: 40,
      );
    });
  }

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

  Widget _provinceWidget() {
    return Obx(() {
      return OverlayDropdownWidget<IranProvinceCityModel>(
        items: controller.rootLogic.provinces,
        onChanged: (value) {
          controller.selectedProvince.value = value;
        },
        selectedItem: controller.selectedProvince.value,
        itemBuilder: (item) => Text(
          item.name ?? 'بدون نام',
          style: AppFonts.yekan14.copyWith(color: AppColor.lightGreyDarker),
        ),
        labelBuilder: (item) => item?.name != null
            ? Text(item!.name!, style: AppFonts.yekan14.copyWith(color: AppColor.textColor))
            : Text(
                'انتخاب استان',
                style: AppFonts.yekan14.copyWith(color: AppColor.textColorLight),
              ),
      );
    });
  }

  Widget _cityWidget() {
    return ObxValue((data) {
      return OverlayDropdownWidget<IranProvinceCityModel>(
        items: data,
        onChanged: (value) {
          controller.selectedCity.value = value;
        },
        selectedItem: controller.selectedCity.value,
        itemBuilder: (item) => Text(
          item.name ?? 'بدون نام',
          style: AppFonts.yekan14.copyWith(color: AppColor.lightGreyDarker),
        ),
        labelBuilder: (item) => item?.name != null
            ? Text(item!.name!, style: AppFonts.yekan14.copyWith(color: AppColor.textColor))
            : Text('انتخاب شهر', style: AppFonts.yekan14.copyWith(color: AppColor.textColorLight)),
      );
    }, controller.cites);
  }

  SizedBox _imageCarcasesWidget(bool isOnEdit) {
    return SizedBox(
      width: Get.width,
      height: 370,
      child: Card(
        color: Colors.white,
        child: Padding(
          padding: const EdgeInsets.all(4.0),
          child: Column(
            spacing: 8,
            children: [
              Text('بارنامه', style: AppFonts.yekan16Bold.copyWith(color: AppColor.blueNormal)),
              Expanded(
                child: ObxValue((data) {
                  return Container(
                    width: Get.width,
                    height: 270,
                    decoration: BoxDecoration(
                      color: AppColor.lightGreyNormal,
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(width: 1, color: AppColor.blackLight),
                    ),
                    child: Center(
                      child: isOnEdit
                          ? Image.network(controller.editImageUrl.value ?? '')
                          : data.value == null
                          ? Padding(
                              padding: const EdgeInsets.fromLTRB(30, 10, 10, 30),
                              child: Assets.vec.placeHolderSvg.svg(width: 200.w, height: 150.h),
                            )
                          : Image.file(File(data.value!.path), fit: BoxFit.cover),
                    ),
                  );
                }, controller.selectedImage),
              ),

              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  RElevated(
                    text: 'گالری',
                    width: 150.w,
                    height: 40.h,
                    textStyle: AppFonts.yekan20.copyWith(color: Colors.white),
                    onPressed: () async {
                      controller.selectedImage.value = await controller.imagePicker.pickImage(
                        source: ImageSource.gallery,
                        imageQuality: 60,
                        maxWidth: 1080,
                        maxHeight: 720,
                      );
                    },
                  ),
                  SizedBox(width: 16),
                  ROutlinedElevated(
                    text: 'دوربین',
                    width: 150.w,
                    height: 40.h,
                    textStyle: AppFonts.yekan20.copyWith(color: AppColor.blueNormal),
                    onPressed: () async {
                      controller.selectedImage.value = await controller.imagePicker.pickImage(
                        source: ImageSource.camera,
                        imageQuality: 60,
                        maxWidth: 1080,
                        maxHeight: 720,
                      );
                    },
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

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