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/location/location_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
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/buttons/custom_button.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';

/// screen to be used to get the location desired by the user
/// to place the values in the request.
/// [confirmButtonString] button text that will be displayed on the button
/// [titleString] bottom sheet title
/// [subTitleString] bottom sheet subtitle for details
/// [onCrossClicked] if something has to be done if the user close the screen
/// [isGmsAvailable] shows if the device that is running the application is GMS or HMS
///
/// it results [true] if the user clicks on the submit button
/// and [false] if the user closes the screen without giving the consent to proceed for the request
class MapUtilityScreen extends StatelessWidget {
  final String confirmButtonString;
  final String titleString;
  final String subTitleString;
  final bool isGmsAvailable;
  final VoidCallback? onCrossClicked;
  final VoidCallback? onSubmitted;

  const MapUtilityScreen({
    super.key,
    required this.confirmButtonString,
    required this.titleString,
    required this.subTitleString,
    required this.isGmsAvailable,
    this.onCrossClicked,
    this.onSubmitted,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // floatingActionButton: 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<LocationViewModel>().moveToCurrentLocation();
      //     }),
      //   ),
      // ),
      bottomSheet: FixedBottomSheet(context),
      body: Stack(
        children: [
          if (isGmsAvailable)
            GMSMap(
              currentLocation: context.read<LocationViewModel>().getGMSLocation(),
              onCameraMoved: (value) => context.read<LocationViewModel>().handleGMSMapCameraMoved(value),
              onCameraIdle: context.read<LocationViewModel>().handleOnCameraIdle,
              myLocationEnabled: true,
              inputController: context.read<LocationViewModel>().gmsController,
              showCenterMarker: true,
              bottomPaddingHeight: 300.h,
            )
          else
            HMSMap(
              currentLocation: context.read<LocationViewModel>().getHMSLocation(),
              onCameraMoved: (value) => context.read<LocationViewModel>().handleHMSMapCameraMoved(value),
              onCameraIdle: context.read<LocationViewModel>().handleOnCameraIdle,
              myLocationEnabled: false,
              inputController: context.read<LocationViewModel>().hmsController,
              showCenterMarker: true,
            ),
          Align(
            alignment: AlignmentDirectional.topStart,
            child: Utils.buildSvgWithAssets(icon: AppAssets.closeBottomNav, width: 32.h, height: 32.h, applyThemeColor: false).onPress(() {
              onCrossClicked?.call();
              // context
              //     .read<EmergencyServicesViewModel>()
              //     .flushPickupInformation();

              Navigator.pop(context, false);
            }),
          ).paddingOnly(top: 51.h, left: 24.h),
        ],
      ),
    );
  }

  Widget FixedBottomSheet(BuildContext context) {
    return GestureDetector(
      onVerticalDragUpdate: (details) {},
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            spacing: 24.h,
            children: [
              inputFields(context).paddingSymmetrical(16.h, 0.h),
              SizedBox(
                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(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        spacing: 4.h,
                        children: [
                          titleString.toText21(
                            weight: FontWeight.w600,
                            color: AppColors.textColor,
                          ),
                          subTitleString.toText12(
                            isBold: true,
                            color: AppColors.greyTextColor,
                          )
                        ],
                      ),
                      CustomButton(
                        text: confirmButtonString,
                        onPressed: () {
                          if (onSubmitted != null) {
                            onSubmitted!();
                          } else {
                            Navigator.pop(context, true);
                          }
                        },
                      )
                    ],
                  ).paddingOnly(top: 24.h, bottom: 32.h, left: 24.h, right: 24.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),
    );
  }

  textPlaceInput(context) {
    return Consumer<LocationViewModel>(builder: (_, vm, __) {
      return SizedBox(
        width: MediaQuery.sizeOf(context).width,
        child: TextInputWidget(
          labelText: LocaleKeys.enterPickupLocationManually.tr(context: context),
          hintText: "" ,
          // 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,
          ),
        ).onPress(() {
          openLocationInputBottomSheet(context);
        }),
      );
    });
  }

  ///decide which field to show first based on the selected calling place
  Widget inputFields(BuildContext context) {
    return textPlaceInput(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<LocationViewModel>().moveController(location) ,
        ),
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {},
    );
  }
}
