import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rasadyar_chicken/data/models/response/waiting_arrival/waiting_arrival.dart';
import 'package:rasadyar_chicken/presentation/utils/string_utils.dart';
import 'package:rasadyar_core/core.dart';

import 'logic.dart';

class BuyInProvinceAllPage extends GetView<BuyInProvinceAllLogic> {
  const BuyInProvinceAllPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8),
      child: 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: getLabelColor(item.receiverState),
                labelIcon: controller.getVecPathItem(item.receiverState),
              );
            }, controller.isExpandedListIndex);
          },
          itemCount: data.value.data?.results?.length ?? 0,
          separatorBuilder: (context, index) => SizedBox(height: 8.h),
          onLoadMore: () async => controller.getAllArrivals(true),
        );
      }, controller.allProduct),
    );
  }

  Row itemListWidget(WaitingArrivalModel 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.toSteward?.user?.fullname ?? '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(
            spacing: 3,
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                spacing: 6,
                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),
                  ),
                ],
              ),

              Text(
                item.toSteward?.guildsName ?? 'N/Aaq',
                textAlign: TextAlign.start,
                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),
          ),
        ),
      ],
    );
  }

  Container itemListExpandedWidget(WaitingArrivalModel 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.steward?.user?.fullname ?? 'N/A',
                textAlign: TextAlign.center,
                style: AppFonts.yekan16.copyWith(color: AppColor.greenDark),
              ),
              Spacer(),
              Text(
                item.receiverState?.faItem,
                textAlign: TextAlign.center,
                style: AppFonts.yekan10.copyWith(color: AppColor.darkGreyDark),
              ),
              SizedBox(width: 7),
              SvgGenImage.vec(controller.getVecPathItem(item.receiverState)).svg(
                width: 16.w,
                height: 16.h,
                colorFilter: ColorFilter.mode(AppColor.darkGreyDark, BlendMode.srcIn),
              ),
            ],
          ),
          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.steward?.user?.fullname ?? 'N/A'),
          buildRow(
            title: 'تلفن فروشنده',
            value: item.steward?.user?.mobile ?? 'N/A',
            valueStyle: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
          ),
          buildRow(title: 'نوع تخصیص', value: item.allocationType?.faAllocationType ?? 'N/A'),
          buildRow(title: 'محصول', value: item.product?.name ?? 'N/A'),
          buildRow(
            title: 'وزن خریداری شده',
            value: '${item.weightOfCarcasses?.separatedByCommaFa} کیلوگرم',
          ),
          buildRow(title: 'قیمت کل', value: '${item.totalAmount?.separatedByCommaFa} ریال'),
          Visibility(
            visible: item.receiverState == 'pending',
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              spacing: 16.w,
              children: [
                ObxValue((data) {
                  return RElevated(
                    text: 'تایید',
                    width: 150.w,
                    height: 40.h,
                    isLoading: data[item.key!] ?? false,
                    onPressed: () async {
                      Get.bottomSheet(conformationBottomSheet(item), isScrollControlled: true).then(
                        (value) {
                          Get.back();
                          controller.clearApprovedController();
                        },
                      );
                    },
                    textStyle: AppFonts.yekan20.copyWith(color: Colors.white),
                    backgroundColor: AppColor.greenNormal,
                  );
                }, controller.isLoadingConfirmMap),
                ROutlinedElevated(
                  text: 'رد',
                  textStyle: AppFonts.yekan20.copyWith(color: AppColor.redNormal),
                  width: 150.w,
                  height: 40.h,
                  onPressed: () {
                    buildWarningDialog(
                      title: 'اخطار',
                      middleText: 'آیا از رد شدن این مورد اطمینان دارید؟',
                      onConfirm: () => controller.denyEntries(item),
                      onRefresh: () => controller.getAllArrivals(),
                    );
                  },
                  borderColor: AppColor.redNormal,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Color getLabelColor(String? item) {
    switch (item) {
      case 'pending':
        return AppColor.blueLight;
      case 'accepted':
        return AppColor.greenLightHover;
      case 'rejected':
        return AppColor.redLightHover;
      default:
        return AppColor.blueLight;
    }
  }

  Widget conformationBottomSheet(WaitingArrivalModel item) {
    controller.weightController.text = item.weightOfCarcasses.separatedByComma;
    return BaseBottomSheet(
      height: 430.h,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          RTextField(
            label: 'وزن(کیلوگرم)',
            controller: controller.weightController,
            keyboardType: TextInputType.number,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly, SeparatorInputFormatter()],
          ),
          SizedBox(height: 16.h),
          RTextField(
            label: 'حجم(قطعه)',
            controller: controller.countController,
            keyboardType: TextInputType.number,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly, SeparatorInputFormatter()],
          ),
          SizedBox(height: 16.h),
          RTextField(
            label: 'افت وزن(کیلوگرم)',
            controller: controller.lossController,
            keyboardType: TextInputType.number,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly, SeparatorInputFormatter()],
          ),
          SizedBox(height: 16.h),

          Text('تایید ', style: AppFonts.yekan16Bold.copyWith(color: AppColor.textColor)),
          ObxValue((data) {
            return Column(
              children: [
                RadioGroup(
                  groupValue: data.value,
                  onChanged: (value) {
                    controller.approvedWithOtpCode.value = value ?? false;
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      radioRow(
                        value: true,
                        label: ' با کد احراز',
                        onTap: () {
                          controller.approvedWithOtpCode.value = true;
                        },
                      ),
                      radioRow(
                        value: false,
                        label: 'بدون کد احراز',
                        onTap: () {
                          controller.approvedWithOtpCode.value = false;
                        },
                      ),
                    ],
                  ),
                ),
                Visibility(
                  child: RTextField(
                    controller: controller.approvedWithOtpController,
                    label: 'کد احراز',
                    keyboardType: TextInputType.number,
                  ),
                  visible: data.value,
                ),
              ],
            );
          }, controller.approvedWithOtpCode),
          SizedBox(height: 30.h),
          ObxValue((data) {
            return RElevated(
              enabled: controller.approvedWithOtpCode.value
                  ? controller.approvedWithOtpController.text.isNotEmpty
                  : true,
              text: 'تایید',
              onPressed: () async {
                await controller.acceptEntries(item);
              },
              isFullWidth: true,
            );
          }, controller.approvedWithOtpCode),
          SizedBox(height: 20.h),
        ],
      ),
    );
  }

  Widget radioRow({
    required bool value,
    required String label,
    TextStyle? textStyle,
    GestureTapCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        children: [
          Radio(value: value),
          Text(label, style: textStyle ?? AppFonts.yekan16.copyWith(color: AppColor.textColor)),
        ],
      ),
    );
  }
}
