import 'dart:async';

import 'package:clarity_flutter/clarity_flutter.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.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/app_state.dart';
import 'package:hmg_patient_app_new/core/cache_consts.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/utils.dart';
import 'package:hmg_patient_app_new/extensions/route_extensions.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/authentication/authentication_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/doctors_list_response_model.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/appointment_via_region_viewmodel.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/appointments/my_doctors_page.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/faculity_selection/facility_type_selection_widget.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/region_bottomsheet/region_list_widget.dart' show RegionBottomSheetBody;
import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_profile_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/immediate_livecare_pending_request_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/select_immediate_livecare_clinic_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/search_doctor_by_name.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/select_clinic_page.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' show showCommonBottomSheetWithoutHeight;
import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import '../appointments/widgets/hospital_bottom_sheet/hospital_bottom_sheet_body.dart';
// import 'package:hmg_patient_app_new/presentation/emergency_services/call_ambulance/widgets/HospitalBottomSheetBody.dart';

class BookAppointmentPage extends StatefulWidget {
  const BookAppointmentPage({super.key});

  @override
  State<BookAppointmentPage> createState() => _BookAppointmentPageState();
}

class _BookAppointmentPageState extends State<BookAppointmentPage> {
  late AppState appState;
  late AppointmentViaRegionViewmodel regionalViewModel;
  late BookAppointmentsViewModel bookAppointmentsViewModel;
  late ImmediateLiveCareViewModel immediateLiveCareViewModel;
  late final AuthenticationViewModel authVM;

  @override
  void initState() {
    Clarity.setCurrentScreenName('Book Appointment Page');
    authVM = context.read<AuthenticationViewModel>();
    scheduleMicrotask(() {
      // bookAppointmentsViewModel.selectedTabIndex = 0;
      bookAppointmentsViewModel.initBookAppointmentViewModel();
      // bookAppointmentsViewModel.getLocation();
      immediateLiveCareViewModel.initImmediateLiveCare();
      if (appState.isAuthenticated) {
        getIt.get<MyAppointmentsViewModel>().getPatientMyDoctors(isTop8: true);
        // getIt.get<MyAppointmentsViewModel>().getPatientFavouriteDoctors();
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (bookAppointmentsViewModel.selectedTabIndex == 1) {
        if (appState.isAuthenticated) {
          getIt.get<MyAppointmentsViewModel>().getPatientMyDoctors(isTop8: true);
          getIt.get<MyAppointmentsViewModel>().getPatientFavouriteDoctors();
          showUnKnownClinicBottomSheet();
        }
      } else {
        showUnKnownClinicBottomSheet();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    immediateLiveCareViewModel = Provider.of<ImmediateLiveCareViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    regionalViewModel = Provider.of<AppointmentViaRegionViewmodel>(context, listen: true);
    getSelectedTabData(bookAppointmentsViewModel.selectedTabIndex);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.bookAppo.tr(context: context),
              isLeading: true,
              child: SingleChildScrollView(
                child: Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 16.h),
                      CustomTabBar(
                        activeTextColor: Color(0xffED1C2B),
                        activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1),
                        initialIndex: bookAppointmentsVM.selectedTabIndex,
                        tabs: [
                          CustomTabBarModel(null, LocaleKeys.general.tr(context: context)),
                          CustomTabBarModel(null, LocaleKeys.liveCare.tr(context: context)),
                        ],
                        onTabChange: (index) {
                          bookAppointmentsVM.onTabChanged(index);
                        },
                      ).paddingSymmetrical(24.h, 0.h),
                      SizedBox(height: 24.h),
                      getSelectedTabData(bookAppointmentsVM.selectedTabIndex),
                      SizedBox(height: 24.h),
                      if (appState.isAuthenticated && bookAppointmentsVM.selectedTabIndex == 0) ...[
                        Consumer<MyAppointmentsViewModel>(builder: (context, myAppointmentsVM, child) {
                          return myAppointmentsVM.isPatientMyDoctorsLoading
                              ? SizedBox(
                                  height: 110.h,
                                  child: ListView.separated(
                                    scrollDirection: Axis.horizontal,
                                    itemCount: 5,
                                    shrinkWrap: true,
                                    padding: EdgeInsets.only(left: 24.w, right: 24.w),
                                    itemBuilder: (context, index) {
                                      return Column(
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: [
                                          Utils.buildImgWithNetwork(
                                            url: "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png",
                                            iconColor: AppColors.transparent,
                                            width: 64.h,
                                            height: 64.h,
                                            fit: BoxFit.cover,
                                          ).circle(100).toShimmer2(isShow: true, radius: 50.r),
                                          SizedBox(height: 8.h),
                                          ("Dr. John").toString().toText12(isBold: true, isCenter: true, maxLine: 2).toShimmer2(isShow: true),
                                        ],
                                      );
                                    },
                                    separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 16.h),
                                  ),
                                )
                              : myAppointmentsVM.patientMyDoctorsList.isEmpty
                                  ? SizedBox()
                                  : Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        if (appState.isAuthenticated) ...[],
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            LocaleKeys.recentVisits.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.w, 0.h),
                                            Row(
                                              children: [
                                                LocaleKeys.viewAll.tr(context: context).toText14(color: AppColors.primaryRedColor, isBold: true),
                                                SizedBox(width: 2.h),
                                                Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 14.h),
                                              ],
                                            ).paddingSymmetrical(24.h, 0.h).onPress(() {
                                              myAppointmentsVM.setIsMyDoctorsDataToBeLoaded(true);
                                              Navigator.of(context).push(
                                                CustomPageRoute(
                                                  page: MyDoctorsPage(),
                                                ),
                                              );
                                            }),
                                          ],
                                        ),
                                        SizedBox(height: 16.h),
                                        SizedBox(
                                          height: 115.h,
                                          child: ListView.separated(
                                            scrollDirection: Axis.horizontal,
                                            itemCount: myAppointmentsVM.patientMyDoctorsList.length,
                                            shrinkWrap: true,
                                            padding: EdgeInsets.only(left: 24.w, right: 24.w),
                                            itemBuilder: (context, index) {
                                              return AnimationConfiguration.staggeredList(
                                                position: index,
                                                duration: const Duration(milliseconds: 1000),
                                                child: SlideAnimation(
                                                  horizontalOffset: 100.0,
                                                  child: FadeInAnimation(
                                                    child: SizedBox(
                                                      // width: 80.w,
                                                      child: Column(
                                                        crossAxisAlignment: CrossAxisAlignment.center,
                                                        children: [
                                                          Utils.buildImgWithNetwork(
                                                            url: myAppointmentsVM.patientMyDoctorsList[index].doctorImageURL!,
                                                            iconColor: AppColors.transparent,
                                                            width: 64.h,
                                                            height: 64.h,
                                                            fit: BoxFit.cover,
                                                          ).circle(100).toShimmer2(isShow: false, radius: 50.r),
                                                          SizedBox(height: 8.h),
                                                          SizedBox(
                                                            width: 80.w,
                                                            child: (myAppointmentsVM.patientMyDoctorsList[index].doctorName)
                                                                .toString()
                                                                .toText12(isBold: true, isCenter: true, maxLine: 2)
                                                                .toShimmer2(isShow: false),
                                                          ),
                                                        ],
                                                      ),
                                                    ).onPress(() async {
                                                      bookAppointmentsViewModel.setSelectedDoctor(DoctorsListResponseModel(
                                                        clinicID: myAppointmentsVM.patientMyDoctorsList[index].clinicID,
                                                        projectID: myAppointmentsVM.patientMyDoctorsList[index].projectID,
                                                        doctorID: myAppointmentsVM.patientMyDoctorsList[index].doctorID,
                                                      ));
                                                      LoaderBottomSheet.showLoader();
                                                      await bookAppointmentsViewModel.getDoctorProfile(onSuccess: (dynamic respData) {
                                                        LoaderBottomSheet.hideLoader();
                                                        Navigator.of(context).push(
                                                          CustomPageRoute(
                                                            page: DoctorProfilePage(isDoctorAllowedToBook: !(myAppointmentsVM.patientMyDoctorsList[index].isLiveCareClinic ?? false)),
                                                          ),
                                                        );
                                                      }, onError: (err) {
                                                        LoaderBottomSheet.hideLoader();
                                                        showCommonBottomSheetWithoutHeight(
                                                          context,
                                                          child: Utils.getErrorWidget(loadingText: err),
                                                          callBackFunc: () {},
                                                          isFullScreen: false,
                                                          isCloseButtonVisible: true,
                                                        );
                                                      });
                                                    }),
                                                  ),
                                                ),
                                              );
                                            },
                                            separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 8.h),
                                          ),
                                        ),
                                      ],
                                    );
                        }),
                        // Favorite Doctors Section
                        Consumer<MyAppointmentsViewModel>(builder: (context, myAppointmentsVM, child) {
                          // Show shimmer loading state
                          if (myAppointmentsVM.isPatientFavouriteDoctorsLoading) {
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height: 24.h),
                                LocaleKeys.favouriteList.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.w, 0.h),
                                SizedBox(height: 16.h),
                                SizedBox(
                                  height: 110.h,
                                  child: ListView.separated(
                                    scrollDirection: Axis.horizontal,
                                    itemCount: 3,
                                    // Show 3 shimmer items
                                    shrinkWrap: true,
                                    padding: EdgeInsets.only(left: 24.w, right: 24.w),
                                    itemBuilder: (context, index) {
                                      return SizedBox(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.center,
                                          children: [
                                            Container(
                                              width: 64.h,
                                              height: 64.h,
                                              decoration: BoxDecoration(
                                                color: Colors.grey[300],
                                                shape: BoxShape.circle,
                                              ),
                                            ).toShimmer2(isShow: true, radius: 50.r),
                                            SizedBox(height: 8.h),
                                            SizedBox(
                                              width: 80.w,
                                              child: Container(
                                                height: 12.h,
                                                decoration: BoxDecoration(
                                                  color: Colors.grey[300],
                                                  borderRadius: BorderRadius.circular(4.r),
                                                ),
                                              ).toShimmer2(isShow: true),
                                            ),
                                          ],
                                        ),
                                      );
                                    },
                                    separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 8.h),
                                  ),
                                ),
                              ],
                            );
                          }

                          // Show empty state or actual list
                          return myAppointmentsVM.patientFavouriteDoctorsList.isEmpty
                              ? Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(height: 16.h),
                                    LocaleKeys.favouriteList.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.w, 0.h),
                                    SizedBox(height: 16.h),
                                    Container(
                                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                        color: AppColors.whiteColor,
                                        borderRadius: 20.h,
                                        hasShadow: false,
                                      ),
                                      padding: EdgeInsets.all(16.h),
                                      child: Column(
                                        children: [
                                          Center(
                                            child: LocaleKeys.noFavouriteDoctors.tr(context: context).toText14(color: AppColors.greyTextColor, isBold: true),
                                          ),
                                          SizedBox(height: 12.h),
                                          CustomButton(
                                            text: LocaleKeys.add.tr(context: context),
                                            onPressed: () {
                                              Navigator.of(context).push(CustomPageRoute(page: SearchDoctorByName()));
                                            },
                                            backgroundColor: Color(0xffFEE9EA),
                                            borderColor: Color(0xffFEE9EA),
                                            textColor: Color(0xffED1C2B),
                                            fontSize: 14.f,
                                            isBold: true,
                                            padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0),
                                            icon: AppAssets.add_icon,
                                            iconColor: AppColors.primaryRedColor,
                                            height: 40.h,
                                          ),
                                        ],
                                      ),
                                    ).paddingSymmetrical(24.w, 0.h),
                                    SizedBox(height: 24.h),
                                  ],
                                )
                              : Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(height: 24.h),
                                    LocaleKeys.favourites.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.w, 0.h),
                                    SizedBox(height: 16.h),
                                    SizedBox(
                                      height: 110.h,
                                      child: ListView.separated(
                                        scrollDirection: Axis.horizontal,
                                        itemCount: myAppointmentsVM.patientFavouriteDoctorsList.length + 1,
                                        shrinkWrap: true,
                                        padding: EdgeInsets.only(left: 24.w, right: 24.w),
                                        itemBuilder: (context, index) {
                                          // Last item: static "Add" button
                                          if (index == myAppointmentsVM.patientFavouriteDoctorsList.length) {
                                            return Column(
                                              crossAxisAlignment: CrossAxisAlignment.center,
                                              children: [
                                                Utils.buildSvgWithAssets(icon: AppAssets.add_new_family_icon, height: 64.h, width: 64.h, applyThemeColor: false),
                                                SizedBox(
                                                  width: 80.w,
                                                  child: LocaleKeys.add
                                                      .tr(context: context)
                                                      .toText12(
                                                        color: AppColors.textColor,
                                                        isBold: true,
                                                        isCenter: true,
                                                      )
                                                      .paddingOnly(top: 4.h),
                                                ),
                                              ],
                                            ).onPress(() {
                                              Navigator.of(context).push(CustomPageRoute(page: SearchDoctorByName()));
                                            });
                                          }
                                          return AnimationConfiguration.staggeredList(
                                            position: index,
                                            duration: const Duration(milliseconds: 1000),
                                            child: SlideAnimation(
                                              horizontalOffset: 100.0,
                                              child: FadeInAnimation(
                                                child: SizedBox(
                                                  child: Column(
                                                    crossAxisAlignment: CrossAxisAlignment.center,
                                                    children: [
                                                      Utils.buildImgWithNetwork(
                                                        url: myAppointmentsVM.patientFavouriteDoctorsList[index].doctorImageUrl!,
                                                        iconColor: AppColors.transparent,
                                                        width: 64.h,
                                                        height: 64.h,
                                                        fit: BoxFit.cover,
                                                      ).circle(100).toShimmer2(isShow: false, radius: 50.r),
                                                      SizedBox(height: 8.h),
                                                      SizedBox(
                                                        width: 80.w,
                                                        child: (myAppointmentsVM.patientFavouriteDoctorsList[index].doctorName)
                                                            .toString()
                                                            .toText12(isBold: true, isCenter: true, maxLine: 2)
                                                            .toShimmer2(isShow: false),
                                                      ),
                                                    ],
                                                  ),
                                                ).onPress(() async {
                                                  bookAppointmentsViewModel.setSelectedDoctor(DoctorsListResponseModel(
                                                    clinicID: myAppointmentsVM.patientFavouriteDoctorsList[index].clinicId,
                                                    projectID: myAppointmentsVM.patientFavouriteDoctorsList[index].projectId,
                                                    doctorID: myAppointmentsVM.patientFavouriteDoctorsList[index].doctorId,
                                                  ));
                                                  LoaderBottomSheet.showLoader();
                                                  await bookAppointmentsViewModel.getDoctorProfile(onSuccess: (dynamic respData) {
                                                    LoaderBottomSheet.hideLoader();
                                                    Navigator.of(context).push(
                                                      CustomPageRoute(
                                                        page: DoctorProfilePage(isDoctorAllowedToBook: true),
                                                      ),
                                                    );
                                                  }, onError: (err) {
                                                    LoaderBottomSheet.hideLoader();
                                                    showCommonBottomSheetWithoutHeight(
                                                      context,
                                                      child: Utils.getErrorWidget(loadingText: err),
                                                      callBackFunc: () {},
                                                      isFullScreen: false,
                                                      isCloseButtonVisible: true,
                                                    );
                                                  });
                                                }),
                                              ),
                                            ),
                                          );
                                        },
                                        separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 8.h),
                                      ),
                                    ),
                                  ],
                                );
                        }),
                      ],
                    ],
                  );
                }),
              ),
            ),
          ),
          Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
            return _buildSymptomsBottomCard();
          }),
        ],
      ),
    );
  }

  Widget getSelectedTabData(int index) {
    switch (index) {
      case 0:
        return Column(
          children: [
            Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 24.h,
                hasShadow: false,
              ),
              child: Padding(
                padding: EdgeInsets.all(16.h),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.search_by_clinic_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                            SizedBox(width: 12.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                LocaleKeys.searchByClinic.tr(context: context).toText14(color: AppColors.textColor, isBold: true),
                                LocaleKeys.tapToSelect.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                              ],
                            ),
                          ],
                        ),
                        Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)),
                      ],
                    ).onPress(() {
                      bookAppointmentsViewModel.setIsClinicsListLoading(true);
                      bookAppointmentsViewModel.setLoadSpecificClinic(false);
                      bookAppointmentsViewModel.setIsLiveCareSchedule(false);
                      bookAppointmentsViewModel.setProjectID(null);
                      Navigator.of(context).push(
                        CustomPageRoute(
                          page: SelectClinicPage(),
                        ),
                      );
                    }),
                    SizedBox(height: 16.h),
                    Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                    SizedBox(height: 16.h),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.search_by_doctor_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                            SizedBox(width: 12.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                LocaleKeys.searchByDoctor.tr(context: context).toText14(color: AppColors.textColor, isBold: true),
                                LocaleKeys.tapToSelect.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                              ],
                            ),
                          ],
                        ),
                        Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)),
                      ],
                    ).onPress(() {
                      bookAppointmentsViewModel.setIsDoctorSearchByNameStarted(false);
                      bookAppointmentsViewModel.setProjectID(null);
                      Navigator.of(context).push(
                        CustomPageRoute(
                          page: SearchDoctorByName(),
                        ),
                      );
                    }),
                    SizedBox(height: 16.h),
                    Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                    SizedBox(height: 16.h),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.search_by_region_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                            SizedBox(width: 12.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                LocaleKeys.searchByRegion.tr(context: context).toText14(color: AppColors.textColor, isBold: true),
                                LocaleKeys.tapToSelect.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                              ],
                            ),
                          ],
                        ),
                        Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)),
                      ],
                    ).onPress(() {
                      Clarity.sendCustomEvent('Select_Region_Page');
                      bookAppointmentsViewModel.setProjectID(null);
                      openRegionListBottomSheet(context, RegionBottomSheetType.FOR_REGION);
                    }),
                  ],
                ),
              ),
            ),
          ],
        ).paddingSymmetrical(24.h, 0.h);
      case 1:
        //TODO: Get LiveCare type Select UI from Hussain
        return appState.isAuthenticated
            ? Column(
                children: [
                  Container(
                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                      color: AppColors.whiteColor,
                      borderRadius: 24.h,
                      hasShadow: false,
                    ),
                    child: Padding(
                      padding: EdgeInsets.all(16.h),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Utils.buildSvgWithAssets(icon: AppAssets.search_by_clinic_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                                  SizedBox(width: 12.h),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      LocaleKeys.immediateConsultation.tr(context: context).toText14(color: AppColors.textColor, isBold: true),
                                      LocaleKeys.tapToSelectClinic.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                                    ],
                                  ),
                                ],
                              ),
                              Transform.flip(
                                  flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)),
                            ],
                          ).onPress(() async {
                            //TODO Implement API to check for existing LiveCare Requests

                            LoaderBottomSheet.showLoader();
                            await immediateLiveCareViewModel.getPatientLiveCareHistory();
                            LoaderBottomSheet.hideLoader();

                            if (immediateLiveCareViewModel.patientHasPendingLiveCareRequest) {
                              Navigator.of(context).push(
                                CustomPageRoute(
                                  page: ImmediateLiveCarePendingRequestPage(),
                                ),
                              );
                            } else {
                              Navigator.of(context).push(
                                CustomPageRoute(
                                  page: SelectImmediateLiveCareClinicPage(),
                                ),
                              );
                            }
                          }),
                          SizedBox(height: 16.h),
                          Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                          SizedBox(height: 16.h),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Utils.buildSvgWithAssets(icon: AppAssets.search_by_doctor_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                                  SizedBox(width: 12.h),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      LocaleKeys.scheduledConsultation.tr(context: context).toText14(color: AppColors.textColor, isBold: true),
                                      LocaleKeys.tapToSelectClinic.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                                    ],
                                  ),
                                ],
                              ),
                              Transform.flip(
                                  flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)),
                            ],
                          ).onPress(() {
                            bookAppointmentsViewModel.setIsClinicsListLoading(true);
                            bookAppointmentsViewModel.setIsLiveCareSchedule(true);
                            Navigator.of(context).push(
                              CustomPageRoute(
                                page: SelectClinicPage(),
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  ),
                ],
              ).paddingSymmetrical(24.h, 0.h)
            : getLiveCareNotLoggedInUI();
      default:
        SizedBox.shrink();
    }
    return Container();
  }

  Widget _buildSymptomsBottomCard() {
    return bookAppointmentsViewModel.checkLiveCareSymptomCheckerStatus()
        ? Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
            child: Row(
              children: [
                Expanded(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      LocaleKeys.notSureHelpMeChooseClinic.tr(context: context).toText16(isBold: true, color: AppColors.textColor),
                      SizedBox(height: 8.h),
                      LocaleKeys.checkYourSymptomsWithScale.tr(context: context).toText12(
                            isBold: true,
                            color: AppColors.greyTextColor,
                          ),
                    ],
                  ),
                ),
                SizedBox(width: 16.w),
                CustomButton(
                  height: 42.h,
                  width: 42.w,
                  text: "",
                  onPressed: () => context.navigateWithName(AppRoutes.userInfoSelection),
                  icon: getIt.get<AppState>().isArabic() ? AppAssets.arrow_back : AppAssets.arrow_forward,
                )
              ],
            ).paddingAll(24.w),
          )
        : SizedBox.shrink();
  }

  void openRegionListBottomSheet(BuildContext context, RegionBottomSheetType type) {
    regionalViewModel.flush();
    regionalViewModel.setBottomSheetType(type);
    // AppointmentViaRegionViewmodel? viewmodel = null;
    showCommonBottomSheetWithoutHeight(context, title: "", titleWidget: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) => getTitle(data)), isDismissible: false,
        child: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) {
      return getRegionalSelectionWidget(data);
    }), callBackFunc: () {});
  }

  Widget getRegionalSelectionWidget(AppointmentViaRegionViewmodel data) {
    if (data.bottomSheetState == AppointmentViaRegionState.REGION_SELECTION) {
      return RegionBottomSheetBody();
    }
    if (data.bottomSheetState == AppointmentViaRegionState.TYPE_SELECTION) {
      bookAppointmentsViewModel.resetFilterList();
      return FacilityTypeSelectionWidget(
        selectedRegion: data.selectedRegionId ?? "",
      );
    }
    if (data.bottomSheetState == AppointmentViaRegionState.HOSPITAL_SELECTION) {
      return HospitalBottomSheetBody(
        searchText: data.searchController,
        displayList: data.displayList,
        onFacilityClicked: (value) {
          data.setSelectedFacility(value);
          data.getDisplayList();
        },
        onHospitalClicked: (hospital) {
          regionalViewModel.setHospitalModel(hospital);
          if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_REGION) {
            regionalViewModel.setBottomSheetState(AppointmentViaRegionState.CLINIC_SELECTION);
            regionalViewModel.handleLastStepForRegion();
          } else if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_CLINIIC) {
            regionalViewModel.setBottomSheetState(AppointmentViaRegionState.DOCTOR_SELECTION);
            regionalViewModel.handleLastStepForClinic();
          } else if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER) {
            var appointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context);
            regionalViewModel.setBottomSheetState(AppointmentViaRegionState.DOCTOR_SELECTION);
            regionalViewModel.handleLastStepForClinicForDentalAndLaser(appointmentsViewModel.selectedClinic.clinicID ?? -1);
          }
        },
        onHospitalSearch: (value) {
          data.searchHospitals(value);
        },
        selectedFacility: data.selectedFacility,
        hmcCount: data.hmcCount,
        hmgCount: data.hmgCount,
        sortByLocation: data.sortByLocation,
        onSortByLocationToggle: (value) => _handleSortByLocationToggle(value, data),
      );
    }
    if (data.bottomSheetState == AppointmentViaRegionState.CLINIC_SELECTION) {
      // Navigator.of(context).pop();
      bookAppointmentsViewModel.setIsClinicsListLoading(true);
      bookAppointmentsViewModel.setLoadSpecificClinic(true);
      bookAppointmentsViewModel.setProjectID(regionalViewModel.selectedHospital!.hospitalList.first!.mainProjectID.toString());
    } else {
      SizedBox.shrink();
    }
    return SizedBox.shrink();
  }

  void _handleSortByLocationToggle(bool value, AppointmentViaRegionViewmodel regionVM) {
    if (value) {
      final locationUtils = getIt.get<LocationUtils>();
      locationUtils.getLocation(
        isShowConfirmDialog: true,
        onSuccess: (latLng) {
          regionVM.setSortByLocation(true);
          _refreshHospitalListAfterApi(regionVM);
        },
        onFailure: () {
          showCommonBottomSheetWithoutHeight(
            title: LocaleKeys.notice.tr(context: context),
            context,
            child: Utils.getWarningWidget(
                loadingText: LocaleKeys.giveLocationPermissionForNearestList.tr(context: context),
                isShowActionButtons: true,
                onCancelTap: () {
                  Navigator.of(context).pop();
                },
                onConfirmTap: () async {
                  Navigator.of(context).pop();
                  openAppSettings();
                }),
            callBackFunc: () {},
            isFullScreen: false,
            isCloseButtonVisible: true,
          );
          regionVM.setSortByLocation(false);
        },
        onLocationDeniedForever: () {
          showCommonBottomSheetWithoutHeight(
            title: LocaleKeys.notice.tr(context: context),
            context,
            child: Utils.getWarningWidget(
                loadingText: LocaleKeys.giveLocationPermissionForNearestList.tr(context: context),
                isShowActionButtons: true,
                onCancelTap: () {
                  Navigator.of(context).pop();
                },
                onConfirmTap: () async {
                  Navigator.of(context).pop();
                  openAppSettings();
                }),
            callBackFunc: () {},
            isFullScreen: false,
            isCloseButtonVisible: true,
          );
          regionVM.setSortByLocation(false);
        },
      );
    } else {
      final appState = getIt.get<AppState>();
      appState.resetLocation();
      regionVM.setSortByLocation(false);
      _refreshHospitalListAfterApi(regionVM);
    }
  }

  void _refreshHospitalListAfterApi(AppointmentViaRegionViewmodel regionVM) {
    void listener() {
      if (!bookAppointmentsViewModel.isRegionListLoading) {
        bookAppointmentsViewModel.removeListener(listener);
        final selectedRegion = regionVM.selectedRegionId;
        if (selectedRegion != null && bookAppointmentsViewModel.hospitalList?.registeredDoctorMap?[selectedRegion] != null) {
          regionVM.setDisplayListAndRegionHospitalList(bookAppointmentsViewModel.hospitalList!.registeredDoctorMap![selectedRegion]);
        }
      }
    }

    bookAppointmentsViewModel.addListener(listener);
    bookAppointmentsViewModel.getRegionMappedProjectList();
  }

  getTitle(AppointmentViaRegionViewmodel data) {
    if (data.selectedRegionId == null) {
      return LocaleKeys.selectRegion.tr(context: context).toText20(isBold: true);
    } else {
      return Transform.flip(
        flipX: data.isArabic ? true : false,
        child: Utils.buildSvgWithAssets(
          icon: AppAssets.arrow_back,
          iconColor: Color(0xff2B353E),
          fit: BoxFit.contain,
        ),
      ).onPress(() {
        data.handleBackPress();
      });
    }
  }

  Widget getLiveCareNotLoggedInUI() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            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.immediateService.tr(context: context).toText18(color: AppColors.textColor, isBold: true),
                  LocaleKeys.noNeedToWaitGetMedicalConsultation.tr(context: context).toText14(color: AppColors.greyTextColor, isBold: true),
                ],
              ),
            ),
          ],
        ),
        SizedBox(height: 24.h),
        Row(
          children: [
            Utils.buildSvgWithAssets(icon: AppAssets.no_visit_icon, width: 58.h, height: 58.h),
            SizedBox(width: 18.h),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  LocaleKeys.noVisitRequired.tr(context: context).toText18(color: AppColors.textColor, isBold: true),
                  LocaleKeys.livecarePoint5.tr(context: context).toText14(color: AppColors.greyTextColor, isBold: true),
                ],
              ),
            ),
          ],
        ),
        SizedBox(height: 24.h),
        Row(
          children: [
            Utils.buildSvgWithAssets(icon: AppAssets.doctor_contact_icon, width: 58.h, height: 58.h),
            SizedBox(width: 18.h),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  LocaleKeys.doctorWillContact.tr(context: context).toText18(color: AppColors.textColor, isBold: true),
                  LocaleKeys.specialisedDoctorWillContactYou.tr(context: context).toText14(color: AppColors.greyTextColor, isBold: true),
                ],
              ),
            ),
          ],
        ),
        SizedBox(height: 24.h),
        Row(
          children: [
            Utils.buildSvgWithAssets(icon: AppAssets.free_med_delivery_icon, width: 58.h, height: 58.h),
            SizedBox(width: 18.h),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  LocaleKeys.freeMedicineDelivery.tr(context: context).toText18(color: AppColors.textColor, isBold: true),
                  LocaleKeys.offersFreeMedicineDelivery.tr(context: context).toText14(color: AppColors.greyTextColor, isBold: true),
                ],
              ),
            ),
          ],
        ),
        SizedBox(height: 36.h),
        CustomButton(
          text: LocaleKeys.loginToUseServiceLiveCare.tr(),
          onPressed: () async {
            await authVM.onLoginPressed();
          },
          backgroundColor: AppColors.primaryRedColor,
          borderColor: AppColors.primaryRedColor,
          textColor: AppColors.whiteColor,
          fontSize: 16.f,
          isBold: true,
          borderRadius: 12.r,
          padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
          height: 50.h,
          icon: AppAssets.login1,
          iconColor: AppColors.whiteColor,
          iconSize: 24.h,
        ),
      ],
    ).paddingSymmetrical(24.h, 0.h);
  }

  void showUnKnownClinicBottomSheet() async {
    if (await Utils.getBoolFromPrefs(CacheConst.isShowSymptomCheckerBottomSheet)) {
      showCommonBottomSheetWithoutHeight(
        context,
        title: "",
        isDismissible: true,
        isCloseButtonVisible: false,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            LocaleKeys.notSureHelpMeChooseClinic.tr(context: context).toText28(color: AppColors.textColor, isBold: true, height: 1.5),
            SizedBox(height: 4.h),
            LocaleKeys.mentionYourSymptomsAndFindDoctors.tr(context: context).toText12(
                  color: AppColors.greyTextColor,
                  isBold: true,
                ),
            SizedBox(height: 24.h),
            CustomButton(
              text: LocaleKeys.yesPleaseINeedHelp.tr(context: context),
              onPressed: () {
                context.pop();
                context.navigateWithName(AppRoutes.userInfoSelection);
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: AppColors.whiteColor,
              fontSize: 16.f,
              isBold: true,
              borderRadius: 12.r,
              // padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 56.h,
            ),
            SizedBox(height: 8.h),
            CustomButton(
              text: LocaleKeys.noThanksIKnowTheClinic.tr(context: context),
              onPressed: () {
                Utils.saveBoolFromPrefs(CacheConst.isShowSymptomCheckerBottomSheet, false);
                context.pop();
              },
              backgroundColor: AppColors.chipSecondaryLightRedColor,
              borderColor: AppColors.chipSecondaryLightRedColor,
              textColor: AppColors.primaryRedColor,
              fontSize: 16.f,
              isBold: true,
              borderRadius: 12.r,
              // padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 56.h,
            ),
          ],
        ).paddingSymmetrical(24.w, 20.h),
        callBackFunc: () {},
      );
    }
  }
}
