import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rasadyar_core/core.dart';
import 'package:rasadyar_inspection/data/model/response/hatching_details/hatching_details.dart';
import 'package:rasadyar_inspection/data/model/response/poultry_location/poultry_location_model.dart';

import 'logic.dart';

class MapPage extends GetView<MapLogic> {
  const MapPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Stack(
        fit: StackFit.expand,
        children: [
          ObxValue((currentLocation) {
            return FlutterMap(
              mapController: controller.animatedMapController.mapController,
              options: MapOptions(
                initialCenter: currentLocation.value,
                interactionOptions: const InteractionOptions(
                  flags: InteractiveFlag.all & ~InteractiveFlag.rotate,
                ),
                initialZoom: 15,
                onPositionChanged: (camera, hasGesture) {
                  controller.currentZoom.value = camera.zoom;
                  /* controller.debouncedUpdateVisibleMarkers(
                    center: camera.center,
                    zoom: camera.zoom,
                  );*/
                },
              ),

              children: [
                TileLayer(
                  urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
                  userAgentPackageName: 'ir.mnpc.rasadyar',
                ),

                ObxValue((markers) {
                  return MarkerClusterLayerWidget(
                    options: MarkerClusterLayerOptions(
                      maxClusterRadius: 80,
                      size: const Size(40, 40),
                      alignment: Alignment.center,
                      padding: const EdgeInsets.all(50),
                      maxZoom: 18,
                      markers: buildMarkers(markers.value.data ?? []),
                      builder: (context, clusterMarkers) {
                        return Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            color: Colors.blue,
                          ),
                          child: Center(
                            child: Text(
                              clusterMarkers.length.toString(),
                              style: const TextStyle(color: Colors.white),
                            ),
                          ),
                        );
                      },
                    ),
                  );
                }, controller.markerLocations),
              ],
            );
          }, controller.currentLocation),

          // Uncomment the following lines to enable the search widget
          /* Positioned(
              top: 10,
              left: 20,
              right: 20,
              child: ObxValue((data) {
                if (data.value) {
                  return SearchWidget(
                    onSearchChanged: (data) {
                      controller.baseLogic.searchValue.value = data;
                    },
                  );
                } else {
                  return SizedBox.shrink();
                }
              }, controller.baseLogic.isSearchSelected),
            ),*/
        ],
      ),
    );
  }

  Widget _buildGpsButton() {
    return ObxValue((data) {
      return RFab(
        backgroundColor: AppColor.greenNormal,
        isLoading: data.value,
        icon: Assets.vec.gpsSvg.svg(width: 40.w, height: 40.h),
        onPressed: () async => await controller.determineCurrentPosition(),
      );
    }, controller.isLoading);
  }

  List<Marker> buildMarkers(List<PoultryLocationModel> markers) {
    final visibleBounds = controller.animatedMapController.mapController.camera.visibleBounds;
    final isZoomedIn = controller.currentZoom > 17;

    final updatedMarkers = markers.map((location) {
      final point = LatLng(location.lat ?? 0, location.long ?? 0);
      final isVisible = controller.isInVisibleBounds(point, visibleBounds);

      if (isZoomedIn && isVisible) {
        return buildMarkerWithHatching(point, location);
      } else {
        return buildMarkerWithOutHatching(point, location);
      }
    }).toList();

    return updatedMarkers;
  }

  Marker buildMarkerWithHatching(LatLng point, PoultryLocationModel location) {
    return Marker(
      point: point,
      width: 180.w,
      height: 50.h,
      child: GestureDetector(
        onTap: () {
          bool hasHatching = location.hatching != null && location.hatching!.isNotEmpty;
          Get.bottomSheet(
            detailsBottomSheet(hasHatching, location),
            isScrollControlled: true,
            isDismissible: true,
          ).then((_) => controller.cleanDataAfterBottomSheet());
        },
        child: Container(
          height: 30.h,
          padding: EdgeInsets.all(5.r),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(15.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.1),
                blurRadius: 5,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            spacing: 8,
            children: [
              Assets.vec.chickenMapMarkerSvg.svg(width: 24.w, height: 24.h),
              Text(location.user?.fullname ?? '', style: AppFonts.yekan12),
            ],
          ),
        ),
      ),
    );
  }

  Marker buildMarkerWithOutHatching(LatLng point, PoultryLocationModel location) {
    return Marker(
      point: point,
      width: 40.h,
      height: 50.h,
      child: GestureDetector(
        onTap: () {
          bool hasHatching = location.hatching != null && location.hatching!.isNotEmpty;
          Get.bottomSheet(
            detailsBottomSheet(hasHatching, location),
            isScrollControlled: true,
            isDismissible: true,
          ).then((_) => controller.cleanDataAfterBottomSheet());
        },
        child: Assets.vec.chickenMapMarkerSvg.svg(width: 24.w, height: 24.h),
      ),
    );
  }

  Widget detailsBottomSheet(bool hasHatching, PoultryLocationModel location) {
    return ObxValue((data) {
      return BaseBottomSheet(
        height: data.value
            ? hasHatching
                  ? 550.h
                  : 400.h
            : 150.h,
        child: Column(
          spacing: 12,
          children: [
            ListItemWithOutCounter(
              secondChild: Column(
                spacing: 8,
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 12.w),
                    child: Column(
                      spacing: 8,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              location.unitName ?? 'N/A',
                              textAlign: TextAlign.center,
                              style: AppFonts.yekan16.copyWith(color: AppColor.greenDark),
                            ),
                          ],
                        ),
                        Container(
                          height: 32.h,
                          padding: EdgeInsets.symmetric(horizontal: 8),
                          decoration: ShapeDecoration(
                            color: AppColor.blueLight,
                            shape: RoundedRectangleBorder(
                              side: BorderSide(width: 1.w, color: AppColor.blueLightHover),
                              borderRadius: BorderRadius.circular(8),
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            spacing: 3,
                            children: [
                              Text(
                                'جوجه ریزی فعال',
                                style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                              ),

                              Text(
                                hasHatching ? 'دارد' : 'ندارد',
                                style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                              ),
                            ],
                          ),
                        ),
                        buildRow(title: 'مشخصات مرغدار', value: location.user?.fullname ?? 'N/A'),

                        buildRow(
                          title: 'تلفن مرغدار',
                          value: location.user?.mobile ?? 'N/A',
                          valueStyle: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                        ),

                        Visibility(
                          visible: location.address?.city?.name != null,
                          child: buildRow(
                            title: 'شهر',
                            value: location.address?.city?.name ?? 'N/A',
                          ),
                        ),
                        Visibility(
                          visible: location.address?.address != null,
                          child: buildRow(title: 'آردس', value: location.address?.address ?? 'N/A'),
                        ),

                        buildRow(title: 'شناسه یکتا', value: location.breedingUniqueId ?? 'N/A'),
                      ],
                    ),
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.center,
                          spacing: 7,
                          children: [
                            RElevated(
                              width: 40.h,
                              height: 38.h,
                              backgroundColor: AppColor.greenNormal,
                              child: Assets.vec.messageAddSvg.svg(
                                width: 24.w,
                                height: 24.h,
                                colorFilter: ColorFilter.mode(Colors.white, BlendMode.srcIn),
                              ),
                              onPressed: () {},
                            ),
                            RElevated(
                              width: 150.w,
                              height: 40.h,
                              backgroundColor: AppColor.blueNormal,
                              onPressed: () {
                                if (controller.hatchingDetails.value.status !=
                                    ResourceStatus.success) {
                                  controller.getFullDetailsLocation(location);
                                }
                                Get.bottomSheet(
                                  fullDetailsBottomSheet(location),
                                  isScrollControlled: true,
                                  isDismissible: true,
                                  ignoreSafeArea: false,
                                );
                              },
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                spacing: 8,
                                children: [
                                  Assets.vec.mapSvg.svg(
                                    width: 24.w,
                                    height: 24.h,
                                    colorFilter: ColorFilter.mode(Colors.white, BlendMode.srcIn),
                                  ),
                                  Text(
                                    'جزییات کامل',
                                    style: AppFonts.yekan14Bold.copyWith(color: Colors.white),
                                  ),
                                ],
                              ),
                            ),
                            ROutlinedElevated(
                              width: 150.w,
                              height: 40.h,
                              onPressed: () {
                                // buildDeleteDialog(onConfirm: () async {}, onRefresh: () async {});
                              },
                              borderColor: AppColor.bgIcon,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                spacing: 8,
                                children: [
                                  Assets.vec.securityTimeSvg.svg(
                                    width: 24.w,
                                    height: 24.h,
                                    colorFilter: ColorFilter.mode(AppColor.bgIcon, BlendMode.srcIn),
                                  ),
                                  Text(
                                    'سوابق بازرسی',
                                    style: AppFonts.yekan14Bold.copyWith(color: AppColor.bgIcon),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              labelColor: AppColor.blueLight,
              labelIcon: Assets.vec.cowSvg.path,
              labelIconColor: AppColor.bgIcon,
              onTap: () => data.value = !data.value,
              selected: data.value,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        location.unitName ?? 'N/A',
                        style: AppFonts.yekan10.copyWith(color: AppColor.blueNormal),
                      ),
                      Text(
                        location.user?.fullname ?? '',
                        style: AppFonts.yekan12.copyWith(color: AppColor.darkGreyDarkHover),
                      ),
                    ],
                  ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        'جوجه ریزی فعال',
                        style: AppFonts.yekan10.copyWith(color: AppColor.blueNormal),
                      ),
                      Text(
                        (location.hatching != null && location.hatching!.isNotEmpty)
                            ? 'دارد'
                            : 'ندراد',
                        style: AppFonts.yekan12.copyWith(color: AppColor.darkGreyDarkHover),
                      ),
                    ],
                  ),
                  Assets.vec.scanBarcodeSvg.svg(),
                ],
              ),
            ),

            if (hasHatching) ...{hatchingWidget(location)},
          ],
        ),
      );
    }, controller.isSelectedDetailsLocation);
  }

  Container hatchingWidget(PoultryLocationModel location) {
    return Container(
      width: Get.width,
      margin: const EdgeInsets.fromLTRB(0, 0, 10, 0),
      padding: EdgeInsets.all(8.r),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(width: 1, color: AppColor.lightGreyNormalHover),
      ),
      child: Column(
        spacing: 8.h,
        children: [
          Container(
            height: 32.h,
            padding: EdgeInsets.symmetric(horizontal: 8),
            decoration: ShapeDecoration(
              color: AppColor.blueLight,
              shape: RoundedRectangleBorder(
                side: BorderSide(width: 1.w, color: AppColor.blueLightHover),
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              spacing: 3,
              children: [
                Text('تاریخ', style: AppFonts.yekan14.copyWith(color: AppColor.textColor)),

                Text(
                  location.hatching?.first.date?.formattedJalaliDate ?? 'N/A',
                  style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                ),
              ],
            ),
          ),
          buildRow(
            title: 'باقیمانده',
            value: '${location.hatching?.first.leftOver.separatedByCommaFa ?? 'N/A'} عدد',
          ),
          buildRow(
            title: 'سن جوجه ریزی',
            value: '${location.hatching?.first.chickenAge ?? 'N/A'} روز',
          ),
          buildRow(
            title: 'شماره مجوز جوجه ریزی',
            value: location.hatching?.first.licenceNumber.toString() ?? 'N/A',
          ),
        ],
      ),
    );
  }

  Widget fullDetailsBottomSheet(PoultryLocationModel location) {
    return BaseBottomSheet(
      height: 550.h,
      child: ObxValue((state) {
        switch (state.value.status) {
          case ResourceStatus.initial:
          case ResourceStatus.loading:
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [CupertinoActivityIndicator(), Text('در حال دریافت اطلاعات ...')],
            );

          case ResourceStatus.success:
            return widgetFullDetailsBottomSheet();
          case ResourceStatus.error:
            return ErrorWidget(state.value.message ?? 'خطا در دریافت اطلاعات');
          case ResourceStatus.empty:
            return EmptyWidget();
        }
      }, controller.hatchingDetails),
    );
  }

  Container widgetFullDetailsBottomSheet() => Container(
    padding: EdgeInsets.all(8.r),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(8.r),
      border: Border.all(width: 1.w, color: AppColor.lightGreyNormalHover),
    ),
    child: ObxValue((data) {
      final HatchingDetails? hatchingDetails = data.value.data?.first;
      return Column(
        spacing: 6.h,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            height: 32.h,
            padding: EdgeInsets.symmetric(horizontal: 8),
            decoration: ShapeDecoration(
              color: AppColor.blueLight,
              shape: RoundedRectangleBorder(
                side: BorderSide(width: 1.w, color: AppColor.blueLightHover),
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              spacing: 3,
              children: [
                Text(
                  'تاریخ جوجه ریزی',
                  style: AppFonts.yekan14.copyWith(color: AppColor.textColor),
                ),

                Text(
                  hatchingDetails?.date.toString().formattedJalaliDate ?? 'N/A',
                  style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                ),
              ],
            ),
          ),

          buildRow(
            title: 'مشخصات مرغدار',
            value: hatchingDetails?.vetFarm?.vetFarmFullName ?? 'N/A',
          ),

          buildRow(
            title: 'تلفن مرغدار',
            value: hatchingDetails?.vetFarm?.vetFarmMobile ?? 'N/A',
            valueStyle: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
          ),
          buildRow(
            title: 'جوجه ریزی فعال',
            value: (hatchingDetails?.archive ?? false) ? 'ندارد' : 'دارد',
          ),
          buildRow(title: 'دوره', value: hatchingDetails?.period.toString() ?? 'N/A'),

          buildRow(
            title: 'تعداد جوجه ریزی',
            value: hatchingDetails?.quantity.separatedByCommaFa.addCountEXT ?? 'N/A',
          ),

          buildRow(
            title: 'تلفات کل',
            value: hatchingDetails?.totalLosses.separatedByCommaFa.addCountEXT ?? 'N/A',
          ),
          buildRow(
            title: 'تلفات دامپزشکی',
            value: hatchingDetails?.losses.separatedByCommaFa.addCountEXT ?? 'N/A',
          ),

          buildRow(
            title: 'باقیمانده در سالن',
            value: hatchingDetails?.leftOver.separatedByCommaFa.addCountEXT ?? 'N/A',
          ),

          buildRow(title: 'نژاد', value: hatchingDetails?.chickenBreed ?? 'N/A'),

          buildRow(title: 'شماره مجوز جوجه ریزی', value: hatchingDetails?.licenceNumber ?? 'N/A'),

          buildRow(
            title: 'سن جوجه',
            value: ((hatchingDetails?.archive ?? false) == true)
                ? hatchingDetails?.nowAge.toString().addDayEXT ?? 'N/A'
                : hatchingDetails?.chickenAge.toString().addDayEXT ?? 'N/A',
          ),

          buildRow(
            title: 'تعداد کشتار',
            value: hatchingDetails?.killedQuantity.separatedByCommaFa.addCountEXT ?? 'N/A',
          ),

          buildRow(
            title: 'میانگین وزن کشتار',
            value: hatchingDetails?.totalAverageKilledWeight.toString().addKgEXT ?? 'N/A',
          ),

          buildRow(
            title: 'وزن کشتار',
            value: hatchingDetails?.totalKilledWeight.separatedByCommaFa.addKgEXT ?? 'N/A',
          ),
        ],
      );
    }, controller.hatchingDetails),
  );
}
