import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nfc_kit/flutter_nfc_kit.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/common_models/privilege/ProjectDetailListModel.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/location_util.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.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/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/review_appointment_page.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/nfc/nfc_reader_sheet.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';

class WaitingAppointmentOnlineCheckinSheet extends StatelessWidget {
  WaitingAppointmentOnlineCheckinSheet({super.key, required this.bookAppointmentsViewModel});

  BookAppointmentsViewModel bookAppointmentsViewModel;

  bool _supportsNFC = false;

  late LocationUtils locationUtils;
  late AppState appState;
  ProjectDetailListModel projectDetailListModel = ProjectDetailListModel();

  @override
  Widget build(BuildContext context) {
    appState = getIt.get<AppState>();
    locationUtils = getIt.get<LocationUtils>();
    locationUtils.isShowConfirmDialog = true;
    FlutterNfcKit.nfcAvailability.then((value) {
      _supportsNFC = (value == NFCAvailability.available);
    });
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        checkInOptionCard(
          AppAssets.checkin_location_icon,
          LocaleKeys.liveLocation.tr(),
          LocaleKeys.verifyYourLocationAtHospital.tr(),
        ).onPress(() {
          locationUtils.getCurrentLocation(onSuccess: (value) {
            projectDetailListModel = Utils.getProjectDetailObj(appState, bookAppointmentsViewModel.waitingAppointmentProjectID);
            double dist = Utils.distance(value.latitude, value.longitude, double.parse(projectDetailListModel.latitude!), double.parse(projectDetailListModel.longitude!)).ceilToDouble() * 1000;
            print(dist);
            if (dist <= projectDetailListModel.geofenceRadius!) {
              checkScannedNFCAndQRCode(projectDetailListModel.checkInQrCode!, context);
            } else {
              showCommonBottomSheetWithoutHeight(context,
                  title: LocaleKeys.error.tr(),
                  child: Utils.getErrorWidget(loadingText: LocaleKeys.ensureWithinHospitalLocation.tr()), callBackFunc: () {
                Navigator.of(context).pop();
              }, isFullScreen: false);
            }
          });
        }),
        SizedBox(height: 16.h),
        // checkInOptionCard(
        //   AppAssets.checkin_nfc_icon,
        //   LocaleKeys.nfcNearFieldCommunication.tr(),
        //   LocaleKeys.scanPhoneViaNFC.tr(),
        // ).onPress(() {
        //   Future.delayed(const Duration(milliseconds: 500), () {
        //     showNfcReader(context, onNcfScan: (String nfcId) {
        //       Future.delayed(const Duration(milliseconds: 100), () {
        //         checkScannedNFCAndQRCode(nfcId, context);
        //       });
        //     }, onCancel: () {});
        //   });
        // }),
        // SizedBox(height: 16.h),
        checkInOptionCard(
          AppAssets.checkin_qr_icon,
          LocaleKeys.qrCode.tr(),
            LocaleKeys.scanQRCodeToCheckIn.tr()
        ).onPress(() async {
          String onlineCheckInQRCode = (await BarcodeScanner.scan().then((value) => value.rawContent));
          if (onlineCheckInQRCode != "") {
            checkScannedNFCAndQRCode(onlineCheckInQRCode, context);
          } else {}
        }),
      ],
    );
  }

  Widget checkInOptionCard(String icon, String title, String subTitle) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 20.h,
        hasShadow: false,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Utils.buildSvgWithAssets(icon: icon, width: 40.h, height: 40.h, fit: BoxFit.fill),
          SizedBox(height: 16.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    title.toText16(isBold: true, color: AppColors.textColor),
                    subTitle.toText12(isBold: true, color: AppColors.greyTextColor),
                  ],
                ),
              ),
              Transform.flip(
                flipX: appState.isArabic(),
                child: Utils.buildSvgWithAssets(
                  icon: AppAssets.forward_arrow_icon_small,
                  iconColor: AppColors.blackColor,
                  width: 18.h,
                  height: 13.h,
                  fit: BoxFit.contain,
                ),
              ),
            ],
          ),
        ],
      ).paddingAll(16.h),
    );
  }

  void checkScannedNFCAndQRCode(String scannedCode, BuildContext context) async {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.processingCheckIn.tr());
    bookAppointmentsViewModel.checkScannedNFCAndQRCode(
      scannedCode,
      bookAppointmentsViewModel.waitingAppointmentProjectID,
      onSuccess: (value) {
        LoaderBottomSheet.hideLoader();
        bookAppointmentsViewModel.getAppointmentNearestGate(projectID: bookAppointmentsViewModel.waitingAppointmentProjectID, clinicID: bookAppointmentsViewModel.waitingAppointmentDoctor!.clinicID!);
        bookAppointmentsViewModel.setIsWaitingAppointmentSelected(true);
        Navigator.of(context).push(
          CustomPageRoute(
            page: ReviewAppointmentPage(),
          ),
        );
      },
      onError: (err) {
        LoaderBottomSheet.hideLoader();
        showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.error.tr(), child: Utils.getErrorWidget(loadingText: err), callBackFunc: () {
          // Navigator.of(context).pop();
        }, isFullScreen: false);
      },
    );
  }
}
