import 'package:flutter/material.dart';
import 'package:rasadyar_chicken/data/models/response/poultry_order/poultry_order.dart';
import 'package:rasadyar_chicken/presentation/pages/poultry_science/killing_registration/view.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 GenocidePage extends GetView<GenocideLogic> {
  const GenocidePage({super.key});

  @override
  Widget build(BuildContext context) {
    return ChickenBasePage(
      routes: controller.routesName,
      hasSearch: true,
      hasFilter: true,
      onRefresh: controller.onRefresh,
      onSearchChanged: (data) {
        controller.searchedValue.value = data;
        controller.getPoultryOrderList();
      },
      backId: poultryFirstKey,
      onFilterTap: () {
        Get.bottomSheet(
          isScrollControlled: true,
          backgroundColor: Colors.transparent,
          filterBottomSheet(),
        );
      },
      child: Stack(
        fit: StackFit.expand,
        children: [
          Positioned.fill(child: poultryOrderListWidget()),
          Positioned(
            bottom: 130,
            right: 16,
            child: RFab.add(
              onPressed: () {
                Get.bottomSheet(
                  isScrollControlled: true,
                  backgroundColor: Colors.transparent,
                  killRegistrationBottomSheet(),
                ).whenComplete(() {
                  controller.killRegistration.clearAllFields();
                  controller.killRegistration.onReady();
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  //region List and Items
  Widget poultryOrderListWidget() {
    return 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.isEqual(index),
              onTap: () => controller.toggleExpanded(index),
              index: index,
              child: itemListWidget(item),
              secondChild: itemListExpandedWidget(item),
              labelColor: AppColor.blueLight,
              labelIcon: Assets.vec.timerSvg.path,
            );
          }, controller.expandedIndex);
        },
        itemCount: data.value.data?.results?.length ?? 0,
        separatorBuilder: (context, index) => SizedBox(height: 8.h),
        onLoadMore: () async => controller.getPoultryOrderList(true),

      );
    }, controller.poultryOrderList);
  }

  Container itemListExpandedWidget(PoultryOrder 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.poultry?.unitName ?? 'N/A',
                textAlign: TextAlign.center,
                style: AppFonts.yekan16.copyWith(color: AppColor.greenDark),
              ),
              Spacer(),

              Visibility(
                child: Text(
                  '${item.poultry?.address?.province?.name} / ${item.poultry?.address?.city?.name}',
                  textAlign: TextAlign.center,
                  style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                ),
              ),
            ],
          ),
          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: [
                Text(
                  'سن مرغ:${item.hatching?.age ?? '-'} (روز)',
                  style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                ),

                Text(
                  item.sendDate?.formattedJalaliDate ?? '-',
                  style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                ),

                Text(
                  'تعداد:${item.quantity.separatedByComma ?? '-'} (قطعه)',
                  style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                ),
              ],
            ),
          ),

          buildRow(title: 'کد سفارش', value: '${item.orderCode} '),
          buildRow(
            title: 'نوع فروش',
            value: (item.freeSaleInProvince ?? false) ? 'آزاد' : 'دولتی ',
          ),
          buildRow(title: 'نوع کشتار ', value: controller.getKillType(item)),
          buildRow(title: 'درخواست', value: controller.getRequestType(item) ?? 'N/A'),

          buildRow(title: 'میانگین وزنی', value: '${(item.indexWeight)} (کیلوگرم)'),
          buildRow(title: 'قیمت مرغدار', value: '${item.amount.separatedByComma} (ریال)'),
          buildRow(
            title: 'مانده در سالن ',
            value: '${item.hatching?.leftOver.separatedByComma ?? 0} (قطعه)',
          ),
          buildRow(title: '	وضعیت', value: controller.getState(item)),

          Visibility(
            visible: item.stateProcess == 'pending',
            child: ObxValue((data) {
              return ROutlinedElevatedIcon(
                height: 40.h,
                width: Get.width,
                text: 'حذف',
                icon: Assets.vec.trashSvg.svg(
                  width: 16.w,
                  height: 16.h,
                  colorFilter: ColorFilter.mode(AppColor.error, BlendMode.srcIn),
                ),
                textStyle: AppFonts.yekan16Bold.copyWith(color: AppColor.error),
                borderColor: AppColor.error,
                foregroundColor: AppColor.error,
                pressedBackgroundColor: AppColor.error,
                onPressed: data.value
                    ? null
                    : () => _buildDeleteDialog(
                        onConfirm: () async {
                          Get.back();
                          await controller.deletePoultryOrder(item.id!);
                          controller.getPoultryOrderList();
                        },
                      ),
              );
            }, controller.isLoadingDelete),
          ),
        ],
      ),
    );
  }

  Widget itemListWidget(PoultryOrder item) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(width: 20),
        Expanded(
          flex: 2,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            spacing: 3,
            children: [
              Text(
                item.poultry?.unitName ?? 'N/A',
                textAlign: TextAlign.start,
                style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal),
              ),
              Text(
                item.sendDate?.formattedJalaliDate ?? '-',
                textAlign: TextAlign.center,
                style: AppFonts.yekan14.copyWith(color: AppColor.bgDark),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 3,
          child: Column(
            spacing: 3,
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                'کد سفارش : ${item.orderCode ?? '-'}',
                textAlign: TextAlign.start,
                style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal),
              ),

              Text(
                'تعداد:${item.quantity.separatedByComma ?? '-'} (قطعه)',
                style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 1,
          child: Assets.vec.scanSvg.svg(
            width: 32.w,
            height: 32.h,
            colorFilter: ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
          ),
        ),
      ],
    );
  }

  //endregion

  //region other widgets
  void _buildDeleteDialog({required VoidCallback onConfirm}) {
    Get.defaultDialog(
      title: 'حذف درخواست کشتار',
      middleText: 'آیا از حذف این درخواست کشتار مطمئن هستید؟',
      confirm: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: AppColor.error,
          foregroundColor: Colors.white,
        ),
        onPressed: onConfirm,
        child: Text('بله'),
      ),
      cancel: ElevatedButton(
        onPressed: () {
          Get.back();
        },
        child: Text('خیر'),
      ),
    );
  }

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

  //endregion

  //region kill registration bottom sheet
  Widget killRegistrationBottomSheet() {
    return BaseBottomSheet(
      height: Get.height * 0.9,
      bgColor: Color(0x66E4E4E4),
      child: KillingRegistrationPage(),
    );
  }

  //endregion
}
