import 'dart:io';

import 'package:flutter/material.dart';
import 'package:rasadyar_chicken/data/models/response/hatching/hatching_models.dart';
import 'package:rasadyar_chicken/data/models/response/hatching_report/hatching_report.dart';
import 'package:rasadyar_chicken/presentation/widget/base_page/view.dart';
import 'package:rasadyar_chicken/presentation/widget/page_route.dart';
import 'package:rasadyar_core/core.dart';

import 'logic.dart';

class InspectionPoultrySciencePage extends GetView<InspectionPoultryScienceLogic> {
  const InspectionPoultrySciencePage({super.key});

  @override
  Widget build(BuildContext context) {
    return BasePage(
      isBase: true,
      routesWidget: ObxValue((route) => buildPageRoute(route), controller.routesName),
      onBackPressed: () => Get.back(id: 0),
      widgets: [
        segmentWidget(),

        ObxValue((data) {
          return data.value == 0 ? hatchingWidget() : reportWidget();
        }, controller.selectedSegmentIndex),
      ],
    );
  }

  ObxValue<Rx<Resource<PaginationModel<HatchingModel>>>> hatchingWidget() {
    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.contains(index),
              onTap: () => controller.isExpandedList.toggle(index),
              index: index,
              child: itemListWidget(item),
              secondChild: itemListExpandedWidget(item),
              labelColor: AppColor.blueLight,
              labelIcon: Assets.vec.checkSquareSvg.path,
            );
          }, controller.isExpandedList);
        },
        itemCount: data.value.data?.results?.length ?? 0,
        separatorBuilder: (context, index) => SizedBox(height: 8.h),
        onLoadMore: () async => controller.getHatchingList(true),
        onRefresh: () async {
          controller.currentPage.value = 1;
          await controller.getHatchingList();
        },
      );
    }, controller.hatchingList);
  }



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

              Visibility(
                child: Text(
                  item.violation == true ? 'پیگیری' : 'عادی',
                  textAlign: TextAlign.center,
                  style: AppFonts.yekan10.copyWith(color: AppColor.redDark),
                ),
              ),
            ],
          ),
          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('نژاد:', style: AppFonts.yekan14.copyWith(color: AppColor.textColor)),
                    Text(
                      item.breed?.first.breed ?? 'N/A',
                      style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                    ),

                    SizedBox(width: 2),

                    Text(
                      ' سن${item.age}',

                      style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                    ),
                  ],
                ),

                Text(
                  ' دوره جوجه ریزی:${item.period}',
                  style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                ),
              ],
            ),
          ),

          buildRow(title: 'شماره مجوز جوجه ریزی', value: item.licenceNumber ?? 'N/A'),
          buildRow(
            title: 'حجم جوجه ریزی',
            value: item.quantity.separatedByComma ?? 'N/A',
            valueStyle: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
          ),
          buildRow(title: 'مانده در سالن', value: item.leftOver.separatedByComma ?? 'N/A'),
          buildRow(title: 'تلفات', value: item.losses.separatedByComma ?? 'N/A'),
          buildRow(
            title: 'دامپزشک فارم',
            value: '${item.vetFarm?.vetFarmFullName}(${item.vetFarm?.vetFarmMobile})',
          ),
          buildRow(
            title: 'شرح بازرسی',
            value: item.reportInfo?.image == false ? 'ارسال تصویر جوجه ریزی فارم ' : 'تکمیل شده',
            titleStyle: AppFonts.yekan14.copyWith(
              color: (item.reportInfo?.image ?? false) ? AppColor.greenNormal : AppColor.redDark,
            ),
            valueStyle: AppFonts.yekan14.copyWith(
              color: (item.reportInfo?.image ?? false) ? AppColor.greenNormal : AppColor.redDark,
            ),
          ),
          Visibility(
            visible: (item.reportInfo?.image == false ?? false),
            child: RElevated(
              text: 'ثبت بازرسی',
              isFullWidth: true,
              width: 150.w,
              height: 40.h,
              onPressed: () {
                cameraBottomSheet(item.id!);
              },
              textStyle: AppFonts.yekan20.copyWith(color: Colors.white),
              backgroundColor: AppColor.greenNormal,
            ),
          ),
        ],
      ),
    );
  }

  void cameraBottomSheet(int id) {
    Get.bottomSheet(
      isDismissible: false,
      isScrollControlled: false,

      BaseBottomSheet(
        child: Column(
          children: [
            GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4,
                mainAxisSpacing: 8,
                crossAxisSpacing: 8,
                childAspectRatio: 1,
              ),
              shrinkWrap: true,
              itemCount: 7,
              itemBuilder: (context, index) {
                return ObxValue((data) {
                  if (index + 1 > data.length) {
                    return GestureDetector(
                      onTap: () async {
                        await controller.pickImages();
                      },
                      child: Container(
                        width: 80.h,
                        height: 80.h,
                        decoration: BoxDecoration(
                          color: AppColor.lightGreyNormal,
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Center(
                          child: Icon(
                            Icons.camera_alt,
                            color: AppColor.lightGreyDarker,
                            size: 32.h,
                          ),
                        ),
                      ),
                    );
                  } else {
                    return Container(
                      width: 80.h,
                      height: 80.h,
                      decoration: BoxDecoration(
                        color: AppColor.lightGreyNormal,
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: Stack(
                        children: [
                          Positioned.fill(
                            child: Image.file(File(data[index].path), fit: BoxFit.cover),
                          ),

                          Positioned(
                            top: 4,
                            left: 4,
                            child: GestureDetector(
                              onTap: () {
                                controller.removeImage(index);
                              },
                              child: Container(
                                width: 24.w,
                                height: 24.h,
                                clipBehavior: Clip.antiAlias,
                                padding: EdgeInsets.all(4),
                                decoration: ShapeDecoration(
                                  color: Colors.white.withValues(alpha: 0.80),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                ),
                                child: Assets.vec.trashSvg.svg(
                                  width: 8.w,
                                  height: 8.h,
                                  colorFilter: ColorFilter.mode(
                                    AppColor.redNormal,
                                    BlendMode.srcIn,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  }
                }, controller.pickedImages);
              },
            ),

            SizedBox(height: 20),
            Row(
              spacing: 16,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Obx(() {
                  return RElevated(
                    height: 40.h,
                    text: 'ارسال',
                    backgroundColor: AppColor.greenNormal,
                    progress: controller.presentUpload.value,
                    isLoading: controller.isOnUpload.value,
                    enabled: controller.pickedImages.length >= 2,
                    onPressed: () async {
                      controller.submitInspectionReport(id: id);
                    },
                  );
                }),
                ObxValue((data) {
                  return RElevated(
                    height: 40.h,
                    text: 'انصراف',
                    backgroundColor: AppColor.redNormal,
                    enabled: !data.value,
                    onPressed: () {
                      if (!data.value) {
                        controller.clearImages();
                        Get.back();
                      }
                    },
                  );
                }, controller.isOnUpload),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Padding segmentWidget() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
      child: Row(
        children: [
          Expanded(
            child: RSegment(
              children: ['بازرسی', 'بایگانی'],
              selectedIndex: 0,
              borderColor: const Color(0xFFB4B4B4),
              selectedBorderColor: AppColor.blueNormal,
              selectedBackgroundColor: AppColor.blueLight,
              onSegmentSelected: (index) => controller.selectedSegmentIndex.value = index,
              backgroundColor: AppColor.whiteGreyNormal,
            ),
          ),
        ],
      ),
    );
  }

  Widget reportWidget() {
    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.contains(index),
              onTap: () => controller.isExpandedList.toggle(index),
              index: index,
              child: itemListWidgetReport(item),
              secondChild: itemListExpandedWidgetReport(item),
              labelColor: AppColor.blueLight,
              labelIcon: Assets.vec.checkSquareSvg.path,
            );
          }, controller.isExpandedList);
        },
        itemCount: data.value.data?.results?.length ?? 0,
        separatorBuilder: (context, index) => SizedBox(height: 8.h),
        onLoadMore: () async => controller.getHatchingReport(true),
        onRefresh: () async {
          controller.currentPage.value = 1;
          await controller.getHatchingReport();
        },
      );
    }, controller.hatchingReportList);
  }

  Widget itemListExpandedWidgetReport(HatchingReport 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.hatching?.poultry?.fullname ?? 'N/A',
                textAlign: TextAlign.center,
                style: AppFonts.yekan16.copyWith(color: AppColor.greenDark),
              ),
              Spacer(),

              Visibility(
                child: Text(
                  item.hatching?.violation == true ? 'پیگیری' : 'عادی',
                  textAlign: TextAlign.center,
                  style: AppFonts.yekan10.copyWith(color: AppColor.redDark),
                ),
              ),
            ],
          ),
          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('نژاد:', style: AppFonts.yekan14.copyWith(color: AppColor.textColor)),
                    Text(
                      item.hatching?.chickenBreed?? 'N/A',
                      style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                    ),

                    SizedBox(width: 2),

                    Text(
                      ' سن${ item.hatching?.chickenAge}',

                      style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                    ),
                  ],
                ),

                Text(
                  ' دوره جوجه ریزی:${ item.hatching?.period}',
                  style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                ),
              ],
            ),
          ),

          buildRow(title: 'شماره مجوز جوجه ریزی', value: item.hatching?.licenceNumber ?? 'N/A'),
          buildRow(
            title: 'حجم جوجه ریزی',
            value: item.hatching?.quantity.separatedByComma ?? 'N/A',
            valueStyle: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
          ),
          buildRow(title: 'مانده در سالن', value: item.hatching?.leftOver.separatedByComma ?? 'N/A'),
          buildRow(title: 'تلفات', value: item.hatching?.losses.separatedByComma ?? 'N/A'),
          buildRow(
            title: 'دامپزشک فارم',
            value: '${item.hatching?.vetFarm?.vetFarmFullname}(${item.hatching?.vetFarm?.vetFarmMobile})',
          ),
          buildRow(
            title: 'شرح بازرسی',
            value: 'تکمیل شده',
            titleStyle: AppFonts.yekan14.copyWith(
              color:  AppColor.greenNormal
            ),
            valueStyle: AppFonts.yekan14.copyWith(
              color:  AppColor.greenNormal
            ),
          ),

          SizedBox(
            height: 140.h,
            child: GridView.builder(
              shrinkWrap: true,
              itemCount: item.image?.length ?? 0,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 10,
                crossAxisSpacing: 10,
              ),
              itemBuilder: (context, index) => Container(
                height: 138.h,
                clipBehavior: Clip.hardEdge,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.r),
                  image: DecorationImage(
                    image: NetworkImage(item.image?[index] ?? ''),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget itemListWidget(HatchingModel 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.poultry?.user?.fullname ?? 'N/A',
                textAlign: TextAlign.start,
                style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal),
              ),
              Text(
                item.poultry?.user?.mobile ?? '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: [
              Text(
                item.poultry?.unitName ?? 'N/Aaq',
                textAlign: TextAlign.start,
                style: AppFonts.yekan12.copyWith(color: AppColor.bgDark),
              ),
              Text(
                item.poultry?.licenceNumber ?? 'N/A',
                textAlign: TextAlign.left,
                style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 1,
          child: Assets.vec.scanSvg.svg(
            width: 32.w,
            height: 32.h,
            colorFilter: ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
          ),
        ),
      ],
    );
  }

  Row itemListWidgetReport(HatchingReport 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.hatching?.poultry?.fullname ?? 'N/A',
                textAlign: TextAlign.start,
                style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal),
              ),
              Text(
                item.hatching?.poultry?.mobile ?? '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: [
              Text(
                item.hatching?.poultry?.unitName ?? 'N/Aaq',
                textAlign: TextAlign.start,
                style: AppFonts.yekan12.copyWith(color: AppColor.bgDark),
              ),
              Text(
                item.hatching?.licenceNumber ?? 'N/A',
                textAlign: TextAlign.left,
                style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 1,
          child: Assets.vec.scanSvg.svg(
            width: 32.w,
            height: 32.h,
            colorFilter: ColorFilter.mode(AppColor.blueNormal, BlendMode.srcIn),
          ),
        ),
      ],
    );
  }
}
