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/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/emergency_services/emergency_services_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.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';
import 'package:provider/provider.dart';

import '../call_ambulance/widgets/HospitalBottomSheetBody.dart';

class ErOnlineCheckinHome extends StatelessWidget {
  ErOnlineCheckinHome({super.key});

  late EmergencyServicesViewModel emergencyServicesViewModel;
  late MyAppointmentsViewModel myAppointmentsViewModel;
  bool _supportsNFC = false;

  @override
  Widget build(BuildContext context) {
    emergencyServicesViewModel = Provider.of<EmergencyServicesViewModel>(context, listen: false);
    myAppointmentsViewModel = Provider.of<MyAppointmentsViewModel>(context, listen: false);
    FlutterNfcKit.nfcAvailability.then((value) {
      _supportsNFC = (value == NFCAvailability.available);
    });
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.emergencyCheckIn.tr(context: context),
              child: SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.all(24.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Utils.getNoDataWidget(context)
                          // Utils.buildSvgWithAssets(icon: AppAssets.immediate_service_icon, width: 58.h, height: 58.h),
                          // SizedBox(width: 18.h),
                          // Expanded(
                          //   child: Column(
                          //     crossAxisAlignment: CrossAxisAlignment.start,
                          //     children: [
                          //       LocaleKeys.onlineCheckIn.tr().toText18(color: AppColors.textColor, isBold: true),
                          //       LocaleKeys.erOnlineCheckInDescription.tr().toText14(color: AppColors.greyTextColor, isBold: true),
                          //     ],
                          //   ),
                          // ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          CustomButton(
            text: emergencyServicesViewModel.patientHasAdvanceERBalance ? LocaleKeys.checkinOption.tr() : LocaleKeys.bookAppo.tr(),
            onPressed: () async {
              if (emergencyServicesViewModel.patientHasAdvanceERBalance) {
                Future.delayed(const Duration(milliseconds: 500), () {
                  showNfcReader(context, onNcfScan: (String nfcId) {
                    Future.delayed(const Duration(milliseconds: 100), () async {
                      print(nfcId);
                      LoaderBottomSheet.showLoader(loadingText: LocaleKeys.processingCheckIn.tr());
                      await emergencyServicesViewModel.getProjectIDFromNFC(
                          nfcCode: nfcId,
                          onSuccess: (value) async {
                            await emergencyServicesViewModel.autoGenerateInvoiceERClinic(
                                projectID: value,
                                onSuccess: (value) {
                                  myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true);
                                  myAppointmentsViewModel.initAppointmentsViewModel();
                                  myAppointmentsViewModel.getPatientAppointments(true, false);
                                  LoaderBottomSheet.hideLoader();
                                  showCommonBottomSheetWithoutHeight(context,
                                      title: LocaleKeys.onlineCheckIn.tr(),
                                      child: Utils.getSuccessWidget(loadingText: LocaleKeys.erOnlineCheckInSuccess.tr()),
                                      callBackFunc: () {
                                    Navigator.pushAndRemoveUntil(
                                        context,
                                        CustomPageRoute(
                                          page: LandingNavigation(),
                                        ),
                                        (r) => false);
                                  }, isFullScreen: false);
                                },
                                onError: (errMessage) {
                                  LoaderBottomSheet.hideLoader();
                                  showCommonBottomSheetWithoutHeight(
                                    context,
                                    child: Utils.getErrorWidget(loadingText: LocaleKeys.erOnlineCheckInError.tr()),
                                    callBackFunc: () {},
                                    isFullScreen: false,
                                    isCloseButtonVisible: true,
                                  );
                                });
                          },
                          onError: (err) {
                            LoaderBottomSheet.hideLoader();
                          });
                    });
                  }, onCancel: () {});
                });
                // showCommonBottomSheetWithoutHeight(context,
                //     title: LocaleKeys.onlineCheckIn.tr(),
                //     child: ErOnlineCheckinSelectCheckinBottomSheet(
                //       projectID: 15,
                //     ),
                //     callBackFunc: () {},
                //     isFullScreen: false);
              } else {
                LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingHospitalsList.tr());
                await context.read<EmergencyServicesViewModel>().getProjects();
                LoaderBottomSheet.hideLoader();
                //Project Selection Dropdown
                showHospitalBottomSheet(context);
              }
            },
            backgroundColor: emergencyServicesViewModel.patientHasAdvanceERBalance ? AppColors.alertColor : AppColors.primaryRedColor,
            borderColor: emergencyServicesViewModel.patientHasAdvanceERBalance ? AppColors.alertColor : AppColors.primaryRedColor,
            textColor: AppColors.whiteColor,
            fontSize: 16.f,
            isBold: true,
            borderRadius: 10.r,
            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
            height: 50.h,
            icon: emergencyServicesViewModel.patientHasAdvanceERBalance ? AppAssets.appointment_checkin_icon : AppAssets.bookAppoBottom,
            iconColor: AppColors.whiteColor,
            iconSize: 18.h,
          ).paddingSymmetrical(24.h, 24.h),
        ],
      ),
    );
  }

  showHospitalBottomSheet(BuildContext context) {
    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.selectHospital.tr(),
      context,
      child: Consumer<EmergencyServicesViewModel>(
        builder: (_, vm, __) => HospitalBottomSheetBody(
          displayList: vm.displayList,
          onFacilityClicked: (value) {
            vm.setSelectedFacility(value);
            vm.getDisplayList();
          },
          onHospitalClicked: (hospital) async {
            Navigator.pop(context);
            vm.setSelectedHospital(hospital);
            LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPaymentInformation.tr(context: context));
            await vm.getPatientERPaymentInformation(onSuccess: (response) {
              LoaderBottomSheet.hideLoader();
              vm.navigateToEROnlineCheckInPaymentPage();
            }, onError: (err) {
              LoaderBottomSheet.hideLoader();
              showCommonBottomSheetWithoutHeight(
                context,
                child: Utils.getErrorWidget(loadingText: err.toString()),
                callBackFunc: () {},
                isFullScreen: false,
                isCloseButtonVisible: true,
              );
            });
          },
          onHospitalSearch: (value) {
            vm.searchHospitals(value ?? "");
          },
          selectedFacility: vm.selectedFacility,
          hmcCount: vm.hmcCount,
          hmgCount: vm.hmgCount,
          searchText: vm.searchController,
        ),
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {},
    );
  }
}
