import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/AmbulanceCallingPlace.dart';
import 'package:hmg_patient_app_new/features/location/GeocodeResponse.dart';
import 'package:hmg_patient_app_new/features/location/PlaceDetails.dart';
import 'package:hmg_patient_app_new/features/location/PlacePrediction.dart';
import 'package:hmg_patient_app_new/features/location/location_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/appointment_doctor_card.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/call_ambulance/widgets/HospitalBottomSheetBody.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/call_ambulance/widgets/appointment_bottom_sheet.dart' show AppointmentBottomSheet;
import 'package:hmg_patient_app_new/presentation/emergency_services/widgets/location_input_bottom_sheet.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/CustomSwitch.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/expandable_bottom_sheet/ExpandableBottomSheet.dart';
import 'package:hmg_patient_app_new/widgets/expandable_bottom_sheet/model/BottomSheetType.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/map/HMSMap.dart';
import 'package:hmg_patient_app_new/widgets/map/gms_map.dart';
import 'package:provider/provider.dart';

import '../../../widgets/common_bottom_sheet.dart';
import 'widgets/AddressItem.dart';

class CallAmbulancePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // floatingActionButton: Visibility(
      //   visible: context.watch<EmergencyServicesViewModel>().bottomSheetType == BottomSheetType.FIXED,
      //   child: Padding(
      //     padding: EdgeInsetsDirectional.only(end: 8.h, bottom: 68.h),
      //     child: DecoratedBox(
      //       decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.h),
      //       child: Utils.buildSvgWithAssets(icon: AppAssets.locate_me, width: 24.h, height: 24.h).paddingAll(12.h).onPress(() {
      //         context.read<EmergencyServicesViewModel>().moveToCurrentLocation();
      //       }),
      //     ),
      //   ),
      // ),
      bottomSheet: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ExpandableBottomSheet(
            bottomSheetType: context.watch<EmergencyServicesViewModel>().bottomSheetType,
            children: {
              BottomSheetType.EXPANDED: ExpandedBottomSheet(context),
              BottomSheetType.FIXED: pickUpDetailAndAppointementSection(context),
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          if (context.read<EmergencyServicesViewModel>().isGMSAvailable)
            GMSMap(
              currentLocation: context.read<EmergencyServicesViewModel>().getGMSLocation(),
              onCameraMoved: (value) => context.read<LocationViewModel>().handleGMSMapCameraMoved(value),
              onCameraIdle: context.read<LocationViewModel>().handleOnCameraIdle,
              myLocationEnabled: true,
              inputController: context.read<EmergencyServicesViewModel>().gmsController,
              showCenterMarker: true,
              bottomPaddingHeight: 400.h,
            )
          else
            HMSMap(
              currentLocation: context.read<EmergencyServicesViewModel>().getHMSLocation(),
              onCameraMoved: (value) => context.read<LocationViewModel>().handleHMSMapCameraMoved(value),
              onCameraIdle: context.read<LocationViewModel>().handleOnCameraIdle,
              myLocationEnabled: false,
              inputController: context.read<EmergencyServicesViewModel>().hmsController,
              showCenterMarker: true,
            ),
          Align(
            alignment: AlignmentDirectional.topStart,
            child: Utils.buildSvgWithAssets(icon: AppAssets.closeBottomNav, width: 32.h, height: 32.h, applyThemeColor: false).onPress(() {
              context.read<EmergencyServicesViewModel>().flushPickupInformation();
              Navigator.pop(context);
            }),
          ).paddingOnly(top: 51.h, left: 24.h),
        ],
      ),
    );
  }

  Widget ExpandedBottomSheet(BuildContext context) {
    return GestureDetector(
      onVerticalDragUpdate: (details) {
        // if(details.delta.dy<0){
        //
        //   context.read<EmergencyServicesViewModel>().updateBottomSheetState(BottomSheetType.EXPANDED);
        // }
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.end,
          //   children: [
          //      Padding(
          //
          //        padding:  EdgeInsetsDirectional.only(end:24.h, bottom: 24.h),
          //       child: DecoratedBox(
          //         decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          //             color: AppColors.whiteColor, borderRadius: 12.h),
          //         child: Utils.buildSvgWithAssets(
          //             icon: AppAssets.locate_me, width: 24.h, height: 24.h)
          //             .paddingAll(12.h).onPress((){
          //           context.read<EmergencyServicesViewModel>().moveToCurrentLocation();
          //         }),
          //       ),
          //     ),
          //   ],
          // ),
          // PositionedDirectional(
          //   end: 1,
          //   child: Padding(
          //     padding:  EdgeInsetsDirectional.only(end:24.h, bottom: 24.h),
          //     child: DecoratedBox(
          //       decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          //           color: AppColors.whiteColor, borderRadius: 12.h),
          //       child: Utils.buildSvgWithAssets(
          //               icon: AppAssets.locate_me, width: 24.h, height: 24.h)
          //           .paddingAll(12.h),
          //     ),
          //   ),
          // ),
          // .paddingOnly(right: 24.h, bottom: 24.h),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            spacing: 24.h,
            children: [
              inputFields(context),
              SizedBox(
                height: 200.h,
                child: DecoratedBox(
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.scaffoldBgColor,
                    customBorder: BorderRadius.only(
                      topLeft: Radius.circular(24.h),
                      topRight: Radius.circular(24.h),
                    ),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    spacing: 24.h,
                    children: [
                      Column(
                        spacing: 4.h,
                        children: [
                          LocaleKeys.selectPickupDetails.tr(context: context).toText21(
                                weight: FontWeight.w600,
                                color: AppColors.textColor,
                              ),
                          LocaleKeys.pleaseSelectDetailsOfPickup.tr(context: context).toText12(
                                fontWeight: FontWeight.w500,
                                color: AppColors.greyTextColor,
                              )
                        ],
                      ),
                      CustomButton(
                          text: LocaleKeys.selectDetails.tr(context: context),
                          onPressed: () {
                            LocationViewModel locationViewModel = context.read<LocationViewModel>();
                            GeocodeResponse? response = locationViewModel.geocodeResponse;
                            PlaceDetails? placeDetails = locationViewModel.placeDetails;
                            PlacePrediction? placePrediction = locationViewModel.selectedPrediction;
                            context.read<EmergencyServicesViewModel>().submitAmbulanceRequest(response?.results.first, placeDetails, placePrediction);
                          })
                    ],
                  ).paddingOnly(top: 24.h, bottom: 32.h, left: 24.h, right: 24.h),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget pickUpDetailAndAppointementSection(BuildContext context) {
    return GestureDetector(
      onVerticalDragUpdate: (details) {
        if (details.delta.dy > 0) {
          context.read<EmergencyServicesViewModel>().updateBottomSheetState(BottomSheetType.FIXED);
        }
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          DecoratedBox(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.scaffoldBgColor,
              customBorder: BorderRadius.only(
                topLeft: Radius.circular(24.h),
                topRight: Radius.circular(24.h),
              ),
            ),
            child: Column(
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  spacing: 16.h,
                  children: [
                    hospitalAndPickUpSection(context),
                    if (context.read<EmergencyServicesViewModel>().appointment != null)
                      AppointmentDoctorCard(
                        renderWidgetForERDisplay: true,
                        patientAppointmentHistoryResponseModel: context.read<EmergencyServicesViewModel>().appointment!,
                        onAskDoctorTap: () {},
                        onCancelTap: () async {},
                        onRescheduleTap: () async {},
                      ).onPress(() {
                        openAppointmentList(context);
                      })
                  ],
                ).paddingOnly(top: 24.h, bottom: 32.h, left: 24.h, right: 24.h),
                bottomPriceContent(context)
              ],
            ),
          ),
        ],
      ),
    );
  }

  locationsSections(BuildContext context) {
    return DecoratedBox(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
      ),
      child: Column(mainAxisSize: MainAxisSize.min, children: [
        ListView.separated(
            separatorBuilder: (_, __) => Column(
                  children: [
                    SizedBox(height: 16.h),
                    Divider(
                      color: AppColors.bottomNAVBorder,
                      height: 1,
                      thickness: 1,
                    ),
                    SizedBox(height: 16.h),
                  ],
                ),
            shrinkWrap: true,
            itemCount: 3,
            itemBuilder: (__, index) {
              if (index == 2) // todo means the end of the list so handle as per the viewmodel
              {
                return CustomButton(
                    height: 40.h,
                    backgroundColor: AppColors.lightRedButtonColor,
                    borderColor: Colors.transparent,
                    text: LocaleKeys.addNewAddress.tr(context: context),
                    textColor: AppColors.primaryRedColor,
                    iconColor: AppColors.primaryRedColor,
                    onPressed: () {},
                    icon: AppAssets.add_icon);
              } else {
                return AddressItem(
                  isSelected: index == 0,
                  address: "Flat No 301, Building No 12, Palm Spring Apartment, Sector 45, Gurugram, Haryana 122003",
                  title: index == 0 ? LocaleKeys.home.tr(context: context) : LocaleKeys.work.tr(context: context),
                  onTap: () {},
                );
              }
            })
      ]).paddingAll(16.h),
    );
  }

  hospitalAndPickUpSection(BuildContext context) {
    return DecoratedBox(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 16.h,
        children: [
          // Row(
          //   children: [
          //     hospitalAndPickUpItemContent(
          //       title: "Select Hospital".needTranslation,
          //       subTitle: "hospital".needTranslation,
          //       leadingIcon: AppAssets.hospital,
          //     ),
          //     Utils.buildSvgWithAssets(icon: AppAssets.down_cheveron,
          //             width: 24.h, height: 24.h)
          //         .paddingAll(16.h)
          //   ],
          // ).onPress((){
          //   showHospitalBottomSheet(context);
          // }),
          // SizedBox(height: 16.h),
          // Divider(
          //   color: AppColors.bottomNAVBorder,
          //   height: 1,
          //   thickness: 1,
          // ),
          // SizedBox(height: 16.h),

          Row(
            children: [
              hospitalAndPickUpItemContent(
                title: LocaleKeys.pick.tr(context: context),
                subTitle: LocaleKeys.insideTheHome.tr(context: context),
                leadingIcon: AppAssets.pickup_bed,
              ),
              CustomSwitch(
                value: context.watch<EmergencyServicesViewModel>().pickupFromInsideTheLocation,
                onChanged: (value) {
                  context.read<EmergencyServicesViewModel>().updateThePickupPlaceFromLocation(value);
                },
              )
            ],
          ),
          if(AmbulanceCallingPlace.TO_HOSPITAL == context.read<EmergencyServicesViewModel>().callingPlace)
            Row(
              children: [
                hospitalAndPickUpItemContent(
                  title: LocaleKeys.appointment.tr(context: context),
                  subTitle: LocaleKeys.haveAnyAppointment.tr(context: context),
                  leadingIcon: AppAssets.appointment_calendar_icon,
                ),
                CustomSwitch(
                  value: context.watch<EmergencyServicesViewModel>().haveAnAppointment,
                  onChanged: (value) async {
                    // if (value) {
                    //   openAppointmentList(context);
                    // }
                    await context.read<EmergencyServicesViewModel>().updateAppointment(value);
                    if (context.read<EmergencyServicesViewModel>().appointments?.isNotEmpty == true) {
                      openAppointmentList(context);
                    }
                  },
                )
              ],
            ),


          // Visibility(
          //   visible: ,
          //   child:
          // ),
        ],
      ).paddingAll(16.h),
    );
  }

  leadingIcon(String leadingIcon) {
    return Container(
      height: 40.h,
      width: 40.h,
      margin: EdgeInsets.only(right: 10.h),
      padding: EdgeInsets.all(8.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        borderRadius: 12.h,
        color: AppColors.greyColor,
      ),
      child: Utils.buildSvgWithAssets(icon: leadingIcon, iconColor: AppColors.greyTextColor),
    );
  }

  hospitalAndPickUpItemContent({
    required String title,
    required String subTitle,
    required String leadingIcon,
  }) {
    return Expanded(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          this.leadingIcon(leadingIcon),
          Expanded(
            child: Column(
              mainAxisSize: MainAxisSize.max,
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Visibility(
                  visible: title.isNotEmpty,
                  child: Column(
                    children: [
                      title.toText12(
                        color: AppColors.greyTextColor,
                        isBold: true,
                      ),
                      SizedBox(height: 2.h),
                    ],
                  ),
                ),
                subTitle.toText14(
                  color: AppColors.textColor,
                  weight: FontWeight.w600,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  bottomPriceContent(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        DecoratedBox(
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.scaffoldBgColor,
              customBorder: BorderRadius.only(
                topLeft: Radius.circular(24.h),
                topRight: Radius.circular(24.h),
              ),
              hasShadow: true),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            spacing: 12.h,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      spacing: 4.h,
                      children: [
                        LocaleKeys.totalAmountToPay.tr(context: context).toText18(
                              weight: FontWeight.w600,
                              color: AppColors.textColor,
                            ),
                        Row(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.warning, height: 18.h, width: 18.h),
                            SizedBox(
                              width: 4.h,
                            ),
                            LocaleKeys.amountPaidAtHospital.tr(context: context).toText12(
                                  isBold: true,
                                  color: AppColors.greyTextColor,
                                ),
                          ],
                        )
                      ],
                    ),
                  ),
                  Utils.getPaymentAmountWithSymbol(
                      (Utils.formatNumberToInternationalFormat(context.read<EmergencyServicesViewModel>().getTotalPrice() ?? 0))
                          .toText24(isBold: true, color: AppColors.textColor, letterSpacing: -2),
                      AppColors.blackColor,
                      17.h)

                  // Utils.getPaymentAmountWithSymbol2(context.read<EmergencyServicesViewModel>().selectedTransportOption?.priceTotal??"0", letterSpacing: -2)
                ],
              ),
              CustomButton(
                  text: LocaleKeys.submitRequest.tr(context: context),
                  onPressed: () {
                    context.read<EmergencyServicesViewModel>().updateBottomSheetState(BottomSheetType.EXPANDED);
                    })
            ],
          ).paddingOnly(top: 24.h, bottom: 12.h, left: 24.h, right: 24.h),
        ),
      ],
    );
  }

  showHospitalBottomSheet(BuildContext context) {
    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.selectHospital.tr(),
      context,
      child: Consumer<EmergencyServicesViewModel>(
        builder: (_, vm, __) => HospitalBottomSheetBody(
          searchText: vm.searchController,
          displayList: vm.displayList,
          onFacilityClicked: (value) {
            vm.setSelectedFacility(value);
            vm.getDisplayList();
          },
          onHospitalClicked: (hospital) {
            Navigator.pop(context);
            vm.setSelectedHospital(hospital);
          },
          onHospitalSearch: (value) {
            vm.searchHospitals(value ?? "");
          },
          selectedFacility: vm.selectedFacility,
          hmcCount: vm.hmcCount,
          hmgCount: vm.hmgCount,
        ),
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {
        context.read<EmergencyServicesViewModel>().clearSearchText();
      },
    );
  }

  ///it will show the places field first and then hospital field
  PlaceFirstThanHospitalField(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 16.h,
      children: [
        textPlaceInput(context),
        hospitalField(context),
      ],
    ).paddingOnly(right: 24.h, left: 24.h);
  }

  HospitalFieldFirstThanPlaces(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 16.h,
      children: [hospitalField(context), textPlaceInput(context)],
    ).paddingOnly(right: 24.h, left: 24.h);
  }

  textPlaceInput(context) {
    return Consumer<LocationViewModel>(builder: (_, vm, __) {
      // print("the data is ${vm.geocodeResponse?.results.first.formattedAddress ?? vm.selectedPrediction?.description}");
      return SizedBox(
        width: MediaQuery.sizeOf(context).width,
        child: TextInputWidget(
          labelText: LocaleKeys.enterPickupLocationManually.tr(context: context),
          hintText: LocaleKeys.enterPickupLocation.tr(context: context),
          controller: TextEditingController(
            text: vm.geocodeResponse?.results.first.formattedAddress ?? vm.selectedPrediction?.description,
          ),
          leadingIcon: AppAssets.location_pickup,
          isAllowLeadingIcon: true,
          isEnable: false,
          prefix: null,
          autoFocus: false,
          isBorderAllowed: false,
          keyboardType: TextInputType.text,
          padding: EdgeInsets.symmetric(
            vertical: ResponsiveExtension(10).h,
            horizontal: ResponsiveExtension(15).h,
          ),
          fontFamily: "Poppins",
        ).onPress(() {
          openLocationInputBottomSheet(context);
        }),
      );
    });
  }

  ///decide which field to show first based on the selected calling place
  inputFields(BuildContext context) {
    return context.read<EmergencyServicesViewModel>().callingPlace == AmbulanceCallingPlace.FROM_HOSPITAL
        ? HospitalFieldFirstThanPlaces(context)
        : PlaceFirstThanHospitalField(context);
  }

  openLocationInputBottomSheet(BuildContext context) {
    // context.read<LocationViewModel>().flushSearchPredictions();
    showCommonBottomSheetWithoutHeight(
      title: "",
      context,
      child: SizedBox(
        height: MediaQuery.sizeOf(context).height * .8,
        child: LocationInputBottomSheet(
          moveCameraController:(location) => context.read<EmergencyServicesViewModel>().moveController(location) ,
        ),
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {},
    );
  }

  hospitalField(BuildContext context) {
    return Visibility(
      visible: false == context.watch<EmergencyServicesViewModel>().haveAnAppointment,
      child: DecoratedBox(
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.h),
        child: Row(
          children: [
            hospitalAndPickUpItemContent(
              title: LocaleKeys.selectHospital.tr(context: context),
              subTitle: context.read<EmergencyServicesViewModel>().getSelectedHospitalName() ?? LocaleKeys.selectHospital.tr(context: context),
              leadingIcon: AppAssets.hospital,
            ),
            Utils.buildSvgWithAssets(icon: AppAssets.down_cheveron, width: 24.h, height: 24.h).paddingAll(16.h)
          ],
        ).onPress(() {
          showHospitalBottomSheet(context);
        }).paddingSymmetrical(
          10.w, 12.h),
      ),
    );
  }

  void openAppointmentList(BuildContext context) {
    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.selectAppointment.tr(context: context),
      context,
      child: SizedBox(
        height: MediaQuery.sizeOf(context).height * .5,
        child: AppointmentBottomSheet(
            list: context.read<EmergencyServicesViewModel>().appointments!,
            onAppointmentSelection: (appointment) {
              Navigator.pop(context);
              context.read<EmergencyServicesViewModel>().setSelectedAppointment(appointment);
            }),
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {
        context.read<EmergencyServicesViewModel>().checkHasAppointment();
      },
    );
    // );
  }
}
