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_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.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/features/book_appointments/models/resp_models/get_clinic_list_response_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/get_livecare_clinics_response_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/models/facility_selection.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/doctor_list_api_response.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.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/hospital_bottom_sheet/hospital_bottom_sheet_body.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/region_bottomsheet/region_list_widget.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/dental_chief_complaints_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/laser/laser_appointment.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/select_doctor_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/select_livecare_clinic_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/clinic_card.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.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/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/chip/custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.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:provider/provider.dart';

class SelectClinicPage extends StatefulWidget {
  bool isFromRegionFlow;
  HealthCalculatorsTypeEnum? calculatorType;
  dynamic calculatedResult;

  SelectClinicPage({super.key, this.isFromRegionFlow = false, this.calculatorType, this.calculatedResult});

  @override
  State<SelectClinicPage> createState() => _SelectClinicPageState();
}

class _SelectClinicPageState extends State<SelectClinicPage> {
  TextEditingController searchEditingController = TextEditingController();
  FocusNode textFocusNode = FocusNode();
  late AppointmentViaRegionViewmodel regionalViewModel;
  late AppState appState;
  late BookAppointmentsViewModel bookAppointmentsViewModel;
  late String name;

  @override
  void initState() {
    Clarity.setCurrentScreenName('Select Clinic Page');
    scheduleMicrotask(() {
      bookAppointmentsViewModel.getClinics();
    });

    name = (widget.calculatorType?.name.toLowerCase() == "bmi" ? widget.calculatorType?.name.toUpperCase() : widget.calculatorType?.name.toCamelCase) ?? "";
    super.initState();
  }

  @override
  void dispose() {
    textFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    regionalViewModel = Provider.of<AppointmentViaRegionViewmodel>(context, listen: true);
    appState = getIt.get<AppState>();
    if (widget.calculatorType != null) {
      return CollapsingListView(
        title: appState.isArabic() ? widget.calculatorType!.displayName.toCamelCase : widget.calculatorType!.displayName.toCamelCase,
        bottomChild: Container(
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.only(topLeft: Radius.circular(24.r), topRight: Radius.circular(24.r))),
          padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 20.h),
          child: CustomButton(
            text: LocaleKeys.bookAppo.tr(context: context),
            onPressed: () {
              if (widget.calculatedResult["clinicId"] == null) {
                bookAppointmentsViewModel.setIsDoctorsListLoading(true);
                bookAppointmentsViewModel.isGetDocForHealthCal = true;
                bookAppointmentsViewModel.calculationID = widget.calculatedResult["calculationID"];
                Navigator.push(context, CustomPageRoute(page: SelectDoctorPage()));
              } else {
                onClinicSelected(GetClinicsListResponseModel(clinicID: widget.calculatedResult["clinicId"], clinicDescription: "asdfds", clinicDescriptionN: "asdfds"));
              }
            },
            icon: null,
            fontSize: 16.f,
            backgroundColor: AppColors.primaryRedColor,
            borderColor: AppColors.primaryRedColor,
            borderRadius: 12.r,
            fontWeight: FontWeight.w600,
          ),
        ),
        child: getCalculatorResultWidget(type: widget.calculatorType!, calculatedResult: widget.calculatedResult).paddingSymmetrical(18.w, 24.h),
      );
    } else {
      return Scaffold(
        backgroundColor: AppColors.bgScaffoldColor,
        body: CollapsingListView(
          title: bookAppointmentsViewModel.isLiveCareSchedule ? LocaleKeys.selectLiveCareClinic.tr(context: context) : LocaleKeys.selectClinic.tr(context: context),
          child: SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 24.h),
              child: Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
                return Column(
                  children: [
                    SizedBox(height: 16.h),
                    TextInputWidget(
                      labelText: LocaleKeys.search.tr(context: context),
                      hintText: LocaleKeys.clinicName.tr(context: context),
                      controller: searchEditingController,
                      isEnable: true,
                      prefix: null,
                      autoFocus: false,
                      isBorderAllowed: false,
                      keyboardType: TextInputType.text,
                      focusNode: textFocusNode,
                      suffix: searchEditingController.text.isNotEmpty
                          ? GestureDetector(
                              onTap: () {
                                searchEditingController.clear();
                                bookAppointmentsViewModel.filterClinics("");
                                textFocusNode.unfocus();
                              },
                              child: Utils.buildSvgWithAssets(icon: AppAssets.close_bottom_sheet_icon, width: 20.h, height: 20.h, fit: BoxFit.scaleDown),
                            )
                          : null,
                      onChange: (value) {
                        bookAppointmentsViewModel.filterClinics(value!);
                      },
                      padding: EdgeInsets.symmetric(
                        vertical: ResponsiveExtension(10).h,
                        horizontal: ResponsiveExtension(15).h,
                      ),
                    ),
                    bookAppointmentsVM.isLiveCareSchedule
                        ? ListView.separated(
                            padding: EdgeInsets.only(top: 24.h),
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            itemCount: bookAppointmentsVM.isClinicsListLoading
                                ? 5
                                : bookAppointmentsVM.liveCareClinicsList.isNotEmpty
                                    ? bookAppointmentsVM.liveCareClinicsList.length
                                    : 1,

                            // bookAppointmentsVM.isClinicsListLoading ? 5 : bookAppointmentsVM.liveCareClinicsList.length,

                            itemBuilder: (context, index) {
                              return bookAppointmentsVM.isClinicsListLoading
                                  ? ClinicCard(
                                      bookAppointmentsVM: bookAppointmentsVM,
                                      liveCareClinicsResponseModel: GetLiveCareClinicsResponseModel(),
                                      clinicsListResponseModel: GetClinicsListResponseModel(),
                                      isLoading: bookAppointmentsVM.isClinicsListLoading,
                                    )
                                  : AnimationConfiguration.staggeredList(
                                      position: index,
                                      duration: const Duration(milliseconds: 500),
                                      child: SlideAnimation(
                                        verticalOffset: 100.0,
                                        child: FadeInAnimation(
                                          child: AnimatedContainer(
                                            duration: Duration(milliseconds: 300),
                                            curve: Curves.easeInOut,
                                            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
                                            child: bookAppointmentsVM.liveCareClinicsList.isNotEmpty
                                                ? ClinicCard(
                                                    bookAppointmentsVM: bookAppointmentsVM,
                                                    liveCareClinicsResponseModel: bookAppointmentsVM.liveCareClinicsList[index],
                                                    clinicsListResponseModel: GetClinicsListResponseModel(),
                                                    isLoading: bookAppointmentsVM.isClinicsListLoading,
                                                  ).onPress(() {
                                                    onLiveCareClinicSelected(bookAppointmentsVM.liveCareClinicsList[index]);
                                                  })
                                                : Utils.getNoDataWidget(context),
                                          ),
                                        ),
                                      ),
                                    );
                            },
                            separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                          )
                        : ListView.separated(
                            padding: EdgeInsets.only(top: 24.h),
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            itemCount: bookAppointmentsVM.isClinicsListLoading ? 5 : bookAppointmentsVM.filteredClinicsList.length,
                            itemBuilder: (context, index) {
                              return bookAppointmentsVM.isClinicsListLoading
                                  ? ClinicCard(
                                      bookAppointmentsVM: bookAppointmentsVM,
                                      liveCareClinicsResponseModel: GetLiveCareClinicsResponseModel(),
                                      clinicsListResponseModel: GetClinicsListResponseModel(),
                                      isLoading: bookAppointmentsVM.isClinicsListLoading,
                                    )
                                  : AnimationConfiguration.staggeredList(
                                      position: index,
                                      duration: const Duration(milliseconds: 500),
                                      child: SlideAnimation(
                                        verticalOffset: 100.0,
                                        child: FadeInAnimation(
                                          child: AnimatedContainer(
                                            duration: Duration(milliseconds: 300),
                                            curve: Curves.easeInOut,
                                            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
                                            child: ClinicCard(
                                              bookAppointmentsVM: bookAppointmentsVM,
                                              liveCareClinicsResponseModel: GetLiveCareClinicsResponseModel(),
                                              clinicsListResponseModel: bookAppointmentsVM.filteredClinicsList[index],
                                              isLoading: bookAppointmentsVM.isClinicsListLoading,
                                            ).onPress(() {
                                              onClinicSelected(bookAppointmentsVM.filteredClinicsList[index]);
                                            }),
                                          ),
                                        ),
                                      ),
                                    );
                            },
                            separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                          ),
                  ],
                );
              }),
            ),
          ),
        ),
      );
    }
  }

  Widget getCalculatorResultWidget({required HealthCalculatorsTypeEnum type, dynamic calculatedResult}) {
    switch (widget.calculatorType!) {
      case HealthCalculatorsTypeEnum.bmi:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.calories:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.bmr:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.idealBodyWeight:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.bodyFat:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.crabsProteinFat:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.ovulation:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.deliveryDueDate:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.bloodSugar:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.bloodCholesterol:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
      case HealthCalculatorsTypeEnum.triglycerides:
        return resultWidget(type: widget.calculatorType!, calculatedResult: calculatedResult);
    }
  }

  Widget resultWidget({required HealthCalculatorsTypeEnum type, dynamic calculatedResult}) {
    AppState appState = getIt<AppState>();
    return Column(
      children: [
        if (type == HealthCalculatorsTypeEnum.bmi) ...[
          if (calculatedResult["bmiCategory"] == "Normal") ...[
            calorieWidget(
              title: calculatedResult["bmiCategory"],
              calories: calculatedResult["bmiResult"],
              description: LocaleKeys.bmiNormalDescription.tr(),
              color: Colors.green,
              icon: Icons.scale,
              hide: true,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["bmiCategory"] == "Underweight") ...[
            calorieWidget(
              title: calculatedResult["bmiCategory"],
              calories: calculatedResult["bmiResult"],
              description: LocaleKeys.bmiUnderweightDescription.tr(),
              color: Colors.orange,
              hide: true,
              icon: Icons.trending_down,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["bmiCategory"] == "Overweight") ...[
            calorieWidget(
              title: calculatedResult["bmiCategory"],
              calories: calculatedResult["bmiResult"],
              description: LocaleKeys.bmiOverweightDescription.tr(),
              color: Colors.red,
              hide: true,
              icon: Icons.warning_rounded,
            ),
          ]
        ] else if (type == HealthCalculatorsTypeEnum.calories) ...[
          if (calculatedResult["calorieRange"] == "Normal") ...[
            calorieWidget(
              title: calculatedResult["calorieRange"],
              calories: calculatedResult["calories"],
              description: LocaleKeys.caloriesMaintenanceDescription.tr(),
              color: Colors.green,
              icon: Icons.scale,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["calorieRange"] == "Low") ...[
            calorieWidget(
              title: calculatedResult["calorieRange"],
              calories: calculatedResult["calories"],
              description: LocaleKeys.caloriesModerateDeficitDescription.tr(),
              color: Colors.orange,
              icon: Icons.trending_down,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["calorieRange"] == "High") ...[
            calorieWidget(
              title: calculatedResult["calorieRange"],
              calories: calculatedResult["calories"],
              description: LocaleKeys.caloriesAggressiveDeficitDescription.tr(),
              color: Colors.red,
              icon: Icons.warning_rounded,
            ),
          ]
        ] else if (type == HealthCalculatorsTypeEnum.bodyFat) ...[
          if (calculatedResult["fatCategory"] == "Essential Fat" || calculatedResult["fatCategory"] == "Athletes") ...[
            calorieWidget(
              title: calculatedResult["fatCategory"],
              calories: calculatedResult["fatPercentage"],
              description: LocaleKeys.bodyFatEssentialDescription.tr(),
              color: Colors.green,
              hide: true,
              icon: Icons.fitness_center,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["fatCategory"] == "Fitness") ...[
            calorieWidget(
              title: calculatedResult["fatCategory"],
              calories: calculatedResult["fatPercentage"],
              description: LocaleKeys.bodyFatFitnessDescription.tr(),
              color: Colors.green,
              hide: true,
              icon: Icons.fitness_center,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["fatCategory"] == "Average" || calculatedResult["fatCategory"] == "Acceptable") ...[
            calorieWidget(
              title: calculatedResult["fatCategory"],
              calories: calculatedResult["fatPercentage"],
              description: LocaleKeys.bodyFatAverageDescription.tr(),
              color: Colors.orange,
              hide: true,
              icon: Icons.accessibility_new,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["fatCategory"] == "Obese" || calculatedResult["fatCategory"] == "Overweight") ...[
            calorieWidget(
              title: calculatedResult["fatCategory"],
              calories: calculatedResult["fatPercentage"],
              description: LocaleKeys.bodyFatObeseDescription.tr(),
              color: Colors.red,
              hide: true,
              icon: Icons.warning_rounded,
            ),
            SizedBox(height: 16.h),
          ]
        ] else if (type == HealthCalculatorsTypeEnum.bmr) ...[
          if (calculatedResult["bmrRange"] == "Normal") ...[
            calorieWidget(
              title: calculatedResult["bmrRange"],
              calories: calculatedResult["bmr"],
              description: LocaleKeys.bmrNormalDescription.tr(),
              color: Colors.green,
              hide: true,
              icon: Icons.scale,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["bmrRange"] == "Low") ...[
            calorieWidget(
              title: calculatedResult["bmrRange"],
              calories: calculatedResult["bmr"],
              description: LocaleKeys.low.tr(),
              color: Colors.orange,
              hide: true,
              icon: Icons.trending_down,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["bmrRange"] == "High") ...[
            calorieWidget(
              title: calculatedResult["bmrRange"],
              calories: calculatedResult["bmr"],
              description: LocaleKeys.bmrHighDescription.tr(),
              color: Colors.red,
              hide: true,
              icon: Icons.warning_rounded,
            ),
          ]
        ] else if (type == HealthCalculatorsTypeEnum.idealBodyWeight) ...[
          if (calculatedResult["status"] == "Normal") ...[
            calorieWidget(
              title: calculatedResult["status"],
              calories: calculatedResult["ibw"],
              hide: true,
              description: (() {
                final diff = calculatedResult["difference"];
                if (diff is num) {
                  if (diff == 0) {
                    return 'Your weight is at the ideal target. Maintain your current habits — balanced diet and regular activity — to keep this.';
                  } else if (diff > 0) {
                    return 'You are below the ideal weight by ${diff.toStringAsFixed(1)} kg. Aim to gradually increase weight with a modest calorie surplus, nutrient-dense foods, and resistance training.';
                  } else {
                    return 'You are above the ideal weight by ${diff.abs().toStringAsFixed(1)} kg. Aim for a gradual, sustainable weight reduction through a moderate calorie deficit, increased activity, and balanced nutrition.';
                  }
                }
                return 'Your weight is close to the ideal range. Maintain a balanced diet and regular activity; follow personalized advice from a healthcare professional if needed.';
              })(),
              color: Colors.green,
              icon: Icons.scale,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["status"] == "Underweight") ...[
            calorieWidget(
              title: calculatedResult["status"],
              calories: calculatedResult["ibw"],
              hide: true,
              description: (() {
                final diff = calculatedResult["difference"];
                if (diff is num) {
                  return 'You are below the ideal weight by ${diff.toStringAsFixed(1)} kg. Focus on increasing calorie intake with nutrient-dense foods, prioritize protein and resistance training to build healthy mass, and consider consulting a healthcare professional.';
                }
                return 'You appear underweight compared to the ideal. Consider increasing calorie intake with nutrient-dense foods and resistance training; seek professional guidance if needed.';
              })(),
              color: Colors.orange,
              icon: Icons.trending_down,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["status"] == "Overweight") ...[
            calorieWidget(
              title: calculatedResult["status"],
              calories: calculatedResult["ibw"],
              hide: true,
              description: (() {
                final diff = calculatedResult["difference"];
                if (diff is num) {
                  return 'You are above the ideal weight by ${diff.abs().toStringAsFixed(1)} kg. Aim for a gradual, sustainable weight loss strategy — moderate calorie deficit, regular physical activity, and balanced nutrition. Consult a professional before major changes.';
                }
                return 'You appear above the ideal weight. Consider a gradual, sustainable calorie deficit combined with activity and balanced nutrition; consult a professional if needed.';
              })(),
              color: Colors.red,
              icon: Icons.warning_rounded,
            ),
          ]
        ] else if (type == HealthCalculatorsTypeEnum.crabsProteinFat) ...[
          if (calculatedResult["dietType"] == "Very Low Crabs") ...[
            calorieWidget(
              title: calculatedResult["dietType"].toString(),
              calories: calculatedResult["totalCalories"],
              description: (() {
                final total = calculatedResult["totalCalories"];
                final carbsG = calculatedResult["carbsGrams"];
                final carbsC = calculatedResult["carbsCalories"];
                final protG = calculatedResult["proteinGrams"];
                final protC = calculatedResult["proteinCalories"];
                final fatG = calculatedResult["fatGrams"];
                final fatC = calculatedResult["fatCalories"];
                final base =
                    'Very low‑carb (ketogenic) approach: minimal carbohydrates, higher fat and moderate protein. May support rapid weight loss and improved blood sugar control for some, but can be hard to sustain and may cause nutrient gaps. Monitor hydration/electrolytes and consult a professional for long‑term use.';
                // if (total is num) {
                //   return '$base\n\nTotal: ${total.toStringAsFixed(0)} kcal.\n\nBreakdown: Carbs ${carbsG is num ? carbsG.toStringAsFixed(0) + " g" : "N/A"} (${carbsC is num ? carbsC.toStringAsFixed(0) + " kcal" : "N/A"}),\nProtein ${protG is num ? protG.toStringAsFixed(0) + " g" : "N/A"} (${protC is num ? protC.toStringAsFixed(0) + " kcal" : "N/A"}),\nFat ${fatG is num ? fatG.toStringAsFixed(1) + " g" : "N/A"} (${fatC is num ? fatC.toStringAsFixed(0) + " kcal" : "N/A"}).';
                // }
                return base;
              })(),
              chipsItems: [
                ('Carbohydrates: ' + calculatedResult["carbsGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["carbsCalories"].toStringAsFixed(0) + ' kcal'),
                ('Protein: ' + calculatedResult["proteinGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["proteinCalories"].toStringAsFixed(0) + ' kcal'),
                ('Fat: ' + calculatedResult["fatGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["fatCalories"].toStringAsFixed(0) + ' kcal'),
              ],
              color: Colors.orange,
              hide: true,
              icon: Icons.trending_down,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["dietType"] == "Low Crabs") ...[
            calorieWidget(
              title: calculatedResult["dietType"].toString(),
              calories: calculatedResult["totalCalories"],
              description: (() {
                final total = calculatedResult["totalCalories"];
                final carbsG = calculatedResult["carbsGrams"];
                final carbsC = calculatedResult["carbsCalories"];
                final protG = calculatedResult["proteinGrams"];
                final protC = calculatedResult["proteinCalories"];
                final fatG = calculatedResult["fatGrams"];
                final fatC = calculatedResult["fatCalories"];
                final base =
                    'Low‑carb, higher‑protein plan: reduced carbohydrates with increased protein to support satiety and muscle maintenance. Helpful for weight management and glycemic control when balanced with vegetables and healthy fats. Ensure adequate fiber and micronutrients.';
                // if (total is num) {
                //   return '$base\n\nTotal: ${total.toStringAsFixed(0)} kcal.\n\nBreakdown:\nCarbs ${carbsG is num ? carbsG.toStringAsFixed(0) + " g" : "N/A"} (${carbsC is num ? carbsC.toStringAsFixed(0) + " kcal" : "N/A"}),\nProtein ${protG is num ? protG.toStringAsFixed(0) + " g" : "N/A"} (${protC is num ? protC.toStringAsFixed(0) + " kcal" : "N/A"}),\nFat ${fatG is num ? fatG.toStringAsFixed(1) + " g" : "N/A"} (${fatC is num ? fatC.toStringAsFixed(0) + " kcal" : "N/A"}).';
                // }
                return base;
              })(),
              chipsItems: [
                ('Carbohydrates: ' + calculatedResult["carbsGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["carbsCalories"].toStringAsFixed(0) + ' kcal'),
                ('Protein: ' + calculatedResult["proteinGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["proteinCalories"].toStringAsFixed(0) + ' kcal'),
                ('Fat: ' + calculatedResult["fatGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["fatCalories"].toStringAsFixed(0) + ' kcal'),
              ],
              color: Colors.orange,
              hide: true,
              icon: Icons.trending_down,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["dietType"] == "Moderate Crabs") ...[
            calorieWidget(
              title: calculatedResult["dietType"].toString(),
              calories: calculatedResult["totalCalories"],
              description: (() {
                final total = calculatedResult["totalCalories"];
                final carbsG = calculatedResult["carbsGrams"];
                final carbsC = calculatedResult["carbsCalories"];
                final protG = calculatedResult["proteinGrams"];
                final protC = calculatedResult["proteinCalories"];
                final fatG = calculatedResult["fatGrams"];
                final fatC = calculatedResult["fatCalories"];
                final base =
                    'Moderate carbohydrate intake with balanced protein and fats: provides steady energy for daily activity and exercise while allowing flexibility. Suitable for many people aiming for sustainable weight management and performance.';
                // if (total is num) {
                //   return '$base\n\nTotal: ${total.toStringAsFixed(0)} kcal.\n\nBreakdown:\nCarbs ${carbsG is num ? carbsG.toStringAsFixed(0) + " g" : "N/A"} (${carbsC is num ? carbsC.toStringAsFixed(0) + " kcal" : "N/A"}),\nProtein ${protG is num ? protG.toStringAsFixed(0) + " g" : "N/A"} (${protC is num ? protC.toStringAsFixed(0) + " kcal" : "N/A"}),\nFat ${fatG is num ? fatG.toStringAsFixed(1) + " g" : "N/A"} (${fatC is num ? fatC.toStringAsFixed(0) + " kcal" : "N/A"}).';
                // }
                return base;
              })(),
              chipsItems: [
                ('Carbohydrates: ' + calculatedResult["carbsGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["carbsCalories"].toStringAsFixed(0) + ' kcal'),
                ('Protein: ' + calculatedResult["proteinGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["proteinCalories"].toStringAsFixed(0) + ' kcal'),
                ('Fat: ' + calculatedResult["fatGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["fatCalories"].toStringAsFixed(0) + ' kcal'),
              ],
              color: Colors.green,
              hide: true,
              icon: Icons.scale,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["dietType"] == "USDA Guidelines ") ...[
            calorieWidget(
              title: calculatedResult["dietType"].toString(),
              calories: calculatedResult["totalCalories"],
              description: (() {
                final total = calculatedResult["totalCalories"];
                final carbsG = calculatedResult["carbsGrams"];
                final carbsC = calculatedResult["carbsCalories"];
                final protG = calculatedResult["proteinGrams"];
                final protC = calculatedResult["proteinCalories"];
                final fatG = calculatedResult["fatGrams"];
                final fatC = calculatedResult["fatCalories"];
                final base =
                    'USDA‑based balanced pattern: emphasizes fruits, vegetables, whole grains, lean proteins, and limited added sugars and saturated fats. Evidence‑based framework for general health, nutrient adequacy, and chronic disease prevention.';
                // if (total is num) {
                //   return '$base\n\nTotal: ${total.toStringAsFixed(0)} kcal.\n\nBreakdown:\nCarbs ${carbsG is num ? carbsG.toStringAsFixed(0) + " g" : "N/A"} (${carbsC is num ? carbsC.toStringAsFixed(0) + " kcal" : "N/A"}),\nProtein ${protG is num ? protG.toStringAsFixed(0) + " g" : "N/A"} (${protC is num ? protC.toStringAsFixed(0) + " kcal" : "N/A"}),\nFat ${fatG is num ? fatG.toStringAsFixed(1) + " g" : "N/A"} (${fatC is num ? fatC.toStringAsFixed(0) + " kcal" : "N/A"}).';
                // }

                return base;
              })(),
              chipsItems: [
                ('Carbohydrates: ' + calculatedResult["carbsGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["carbsCalories"].toStringAsFixed(0) + ' kcal'),
                ('Protein: ' + calculatedResult["proteinGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["proteinCalories"].toStringAsFixed(0) + ' kcal'),
                ('Fat: ' + calculatedResult["fatGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["fatCalories"].toStringAsFixed(0) + ' kcal'),
              ],
              color: Colors.green,
              hide: true,
              icon: Icons.scale,
            ),
            SizedBox(height: 16.h),
          ] else if (calculatedResult["dietType"] == "Zone Diet") ...[
            calorieWidget(
              title: calculatedResult["dietType"].toString(),
              calories: calculatedResult["totalCalories"],
              description: (() {
                final total = calculatedResult["totalCalories"];
                final carbsG = calculatedResult["carbsGrams"];
                final carbsC = calculatedResult["carbsCalories"];
                final protG = calculatedResult["proteinGrams"];
                final protC = calculatedResult["proteinCalories"];
                final fatG = calculatedResult["fatGrams"];
                final fatC = calculatedResult["fatCalories"];
                final base =
                    'Zone Diet (~40% carbs / 30% protein / 30% fat): emphasizes hormonal balance and portion control. May improve body composition and energy for some, but requires planning; personalize with a nutrition professional.';
                // if (total is num) {
                //   return '$base\n\nTotal: ${total.toStringAsFixed(0)} kcal.\n\nBreakdown:\nCarbs ${carbsG is num ? carbsG.toStringAsFixed(0) + " g" : "N/A"} (${carbsC is num ? carbsC.toStringAsFixed(0) + " kcal" : "N/A"}),\nProtein ${protG is num ? protG.toStringAsFixed(0) + " g" : "N/A"} (${protC is num ? protC.toStringAsFixed(0) + " kcal" : "N/A"}),\nFat ${fatG is num ? fatG.toStringAsFixed(1) + " g" : "N/A"} (${fatC is num ? fatC.toStringAsFixed(0) + " kcal" : "N/A"}).';
                // }
                return base;
              })(),
              chipsItems: [
                ('Carbohydrates: ' + calculatedResult["carbsGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["carbsCalories"].toStringAsFixed(0) + ' kcal'),
                ('Protein: ' + calculatedResult["proteinGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["proteinCalories"].toStringAsFixed(0) + ' kcal'),
                ('Fat: ' + calculatedResult["fatGrams"].toStringAsFixed(0) + 'g = ' + calculatedResult["fatCalories"].toStringAsFixed(0) + ' kcal'),
              ],
              color: Colors.orange,
              hide: true,
              icon: Icons.warning_rounded,
            ),
          ]
        ] else if (type == HealthCalculatorsTypeEnum.ovulation) ...[
          Column(
            children: [
              Container(
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.all(Radius.circular(24.r))),
                padding: EdgeInsets.all(16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Row(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.nextPeriodAccordion, width: 30.h, height: 30.h),
                            SizedBox(
                              width: 8.w,
                            ),
                            calculatedResult["lastPeriodDate"].toString().toText16(color: AppColors.successColor, isBold: true),
                          ],
                        ),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    CustomChipWidget(
                        height: 30.h,
                        chipType: ChipTypeEnum.alert,
                        backgroundColor: AppColors.lightGrayBGColor,
                        chipText: calculatedResult["lastPeriodDay"].toString(),
                        iconAsset: null,
                        isShowBorder: false,
                        borderRadius: 8.h,
                        textColor: AppColors.textColor),
                    SizedBox(height: 16.h),
                    Row(
                      children: [
                        Utils.buildSvgWithAssets(icon: AppAssets.ovulationAccordion, width: 30.h, height: 30.h),
                        SizedBox(
                          width: 8.w,
                        ),
                        calculatedResult["ovulationDate"].toString().toText16(color: AppColors.successColor, isBold: true),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    CustomChipWidget(
                        height: 30.h,
                        chipType: ChipTypeEnum.alert,
                        backgroundColor: AppColors.lightGrayBGColor,
                        chipText: calculatedResult["ovulationDay"].toString(),
                        iconAsset: null,
                        isShowBorder: false,
                        borderRadius: 8.h,
                        textColor: AppColors.textColor),
                    SizedBox(height: 16.h),
                    appState.isArabic() ? "فترة الخصوبة".toText16(color: AppColors.textColor, isBold: true) : "Fertility Window".toText16(color: AppColors.textColor, isBold: true),
                    SizedBox(height: 8.h),
                    Row(
                      children: [
                        Utils.buildSvgWithAssets(icon: AppAssets.fertileAccordion, width: 30.h, height: 30.h),
                        SizedBox(
                          width: 8.w,
                        ),
                        calculatedResult["fertileWindowStart"].toString().toText13(color: AppColors.successColor, isBold: true),
                        SizedBox(
                          width: 4.w,
                        ),
                        "-".toText16(isBold: true, color: AppColors.successColor),
                        SizedBox(
                          width: 4.w,
                        ),
                        calculatedResult["fertileWindowEnd"].toString().toText13(color: AppColors.successColor, isBold: true),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    appState.isArabic()
                        ? "هذه هي فترة خصوبتك. يساعد الحفاظ على نطاق صحي من السعرات الحرارية في دعم جسمك خلال هذه الفترة، مع مراعاة معدل الأيض الأساسي ومستوى نشاطك. مؤشر كتلة جسمك ضمن النطاق الصحي."
                            .toText12(height: 1.5, color: AppColors.textColorLight, isBold: true)
                        : "This is your fertile window. Maintaining a healthy calorie range supports your body during this period, considering your Basal Metabolic Rate and activity. Your Body Mass Index is within the healthy range."
                            .toText12(height: 1.5, color: AppColors.textColorLight, isBold: true)
                  ],
                ),
              ),
              SizedBox(
                height: 16.h,
              ),
              Container(
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.all(Radius.circular(24.r))),
                padding: EdgeInsets.all(16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Utils.buildSvgWithAssets(icon: AppAssets.bulb),
                        SizedBox(
                          width: 8.w,
                        ),
                        Row(
                          children: [
                            appState.isArabic() ? "نصائح هامة".toText16(color: AppColors.textColor, isBold: true) : "Tips to keep in mind".toText16(color: AppColors.textColor, isBold: true),
                          ],
                        ),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    Column(
                      children: [
                        _buildTipRow(appState.isArabic() ? "اشربي الماء قبل الشعور بالعطش" : "Drink before you feel thirsty."),
                        SizedBox(height: 4.h),
                        _buildTipRow(appState.isArabic() ? "احتفظي بزجاجة ماء قابلة لإعادة التعبئة بجانبك" : "Keep a refillable bottle next to you."),
                        SizedBox(height: 4.h),
                        _buildTipRow(appState.isArabic() ? "تابعي استهلاكك اليومي للحفاظ على حماسك" : "Track your daily intake to stay motivated."),
                        SizedBox(height: 4.h),
                        _buildTipRow(appState.isArabic() ? "اختاري المياه الفوارة بدلاً من المشروبات الغازية" : "Choose sparkling water instead of soda."),
                      ],
                    ).paddingOnly(left: 4.w, right: 4.w)
                  ],
                ),
              ),
            ],
          )
        ] else if (type == HealthCalculatorsTypeEnum.deliveryDueDate) ...[
          Column(
            children: [
              Container(
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.all(Radius.circular(24.r))),
                padding: EdgeInsets.all(16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.pregnancyDueDateAccordion, width: 30.h, height: 30.h),
                            SizedBox(width: 8.w),
                            calculatedResult["dueDate"].toString().toText16(color: AppColors.successColor, isBold: true),
                          ],
                        ),
                        Expanded(child: SizedBox(width: 8.w)),
                        CustomChipWidget(
                            height: 30.h,
                            chipType: ChipTypeEnum.alert,
                            backgroundColor: AppColors.lightGrayBGColor,
                            chipText: calculatedResult["dueDateDay"].toString(),
                            iconAsset: null,
                            isShowBorder: false,
                            borderRadius: 8.h,
                            textColor: AppColors.textColor),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(height: 16.h),
              Container(
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.all(Radius.circular(24.r))),
                padding: EdgeInsets.all(16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        "First Trimester".toText16(color: AppColors.textColor, isBold: true),
                        Expanded(child: SizedBox(width: 8.h)),
                        CustomChipWidget(
                            height: 30.h,
                            chipType: ChipTypeEnum.alert,
                            backgroundColor: AppColors.lightGrayBGColor,
                            chipText: "${calculatedResult["firstTrimester"]["weeks"]} Weeks",
                            iconAsset: null,
                            isShowBorder: false,
                            borderRadius: 8.h,
                            textColor: AppColors.textColor),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    Row(
                      children: [
                        Utils.buildSvgWithAssets(icon: AppAssets.fertileAccordion, width: 30.h, height: 30.h),
                        SizedBox(
                          width: 8.w,
                        ),
                        calculatedResult["firstTrimester"]["start"].toString().toText13(color: AppColors.successColor, isBold: true),
                        SizedBox(
                          width: 4.w,
                        ),
                        "-".toText16(isBold: true, color: AppColors.successColor),
                        SizedBox(
                          width: 4.w,
                        ),
                        calculatedResult["firstTrimester"]["end"].toString().toText13(color: AppColors.successColor, isBold: true),
                      ],
                    ),
                    SizedBox(height: 8.h),
                  ],
                ),
              ),
              SizedBox(height: 16.h),
              Container(
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.all(Radius.circular(24.r))),
                padding: EdgeInsets.all(16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        "Second Trimester".toText16(color: AppColors.textColor, isBold: true),
                        Expanded(child: SizedBox(width: 8.h)),
                        CustomChipWidget(
                            height: 30.h,
                            chipType: ChipTypeEnum.alert,
                            backgroundColor: AppColors.lightGrayBGColor,
                            chipText: "${calculatedResult["secondTrimester"]["weeks"]} Weeks",
                            iconAsset: null,
                            isShowBorder: false,
                            borderRadius: 8.h,
                            textColor: AppColors.textColor),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    Row(
                      children: [
                        Utils.buildSvgWithAssets(icon: AppAssets.ovulationAccordion, width: 30.h, height: 30.h),
                        SizedBox(
                          width: 8.w,
                        ),
                        calculatedResult["secondTrimester"]["start"].toString().toText13(color: AppColors.successColor, isBold: true),
                        SizedBox(
                          width: 4.w,
                        ),
                        "-".toText16(isBold: true, color: AppColors.successColor),
                        SizedBox(
                          width: 4.w,
                        ),
                        calculatedResult["secondTrimester"]["end"].toString().toText13(color: AppColors.successColor, isBold: true),
                      ],
                    ),
                    SizedBox(height: 8.h),
                  ],
                ),
              ),
              SizedBox(height: 16.h),
              Container(
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.all(Radius.circular(24.r))),
                padding: EdgeInsets.all(16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        "Third Trimester".toText16(color: AppColors.textColor, isBold: true),
                        Expanded(child: SizedBox(width: 8.h)),
                        CustomChipWidget(
                            height: 30.h,
                            chipType: ChipTypeEnum.alert,
                            backgroundColor: AppColors.lightGrayBGColor,
                            chipText: "${calculatedResult["thirdTrimester"]["weeks"]} Weeks",
                            iconAsset: null,
                            isShowBorder: false,
                            borderRadius: 8.h,
                            textColor: AppColors.textColor),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    Row(
                      children: [
                        Utils.buildSvgWithAssets(icon: AppAssets.pregnancyDayAccordion, width: 30.h, height: 30.h),
                        SizedBox(
                          width: 8.w,
                        ),
                        calculatedResult["thirdTrimester"]["start"].toString().toText13(color: AppColors.successColor, isBold: true),
                        SizedBox(
                          width: 4.w,
                        ),
                        "-".toText16(isBold: true, color: AppColors.successColor),
                        SizedBox(
                          width: 4.w,
                        ),
                        calculatedResult["thirdTrimester"]["end"].toString().toText13(color: AppColors.successColor, isBold: true),
                      ],
                    ),
                    SizedBox(height: 8.h),
                  ],
                ),
              ),
            ],
          )
        ],
      ],
    );
  }

  Widget _buildTipRow(String text) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.only(top: 6.h, right: 8.w),
          child: CircleAvatar(
            radius: 3.r,
            backgroundColor: AppColors.textColorLight,
          ),
        ),
        Expanded(
          child: text.toText12(color: AppColors.textColorLight, isBold: true, height: 1.2.h),
        ),
      ],
    );
  }

  Widget calorieWidget({required String title, required dynamic calories, required String description, required Color color, required IconData icon, bool hide = false, List<String>? chipsItems}) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.all(Radius.circular(24.r))),
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  ('${calories.toStringAsFixed(0)}').toText32(color: getTextColor(title), isBold: true),
                  SizedBox(width: 10.w),
                  hide ? SizedBox() : 'kcal/day'.toText12(color: AppColors.inputLabelTextColor, isBold: true)
                ],
              ),
              _buildStatusIcon(title)
            ],
          ),
          SizedBox(height: 16.h),
          if (chipsItems != null && chipsItems.isNotEmpty) ...[
            Wrap(
              spacing: 8.0, // Horizontal space between chips
              runSpacing: 4.0, // Vertical space between rows of chips
              children: chipsItems.map((item) {
                return CustomChipWidget(
                        height: 30.h,
                        chipType: ChipTypeEnum.alert,
                        backgroundColor: AppColors.lightGrayBGColor,
                        chipText: item,
                        iconAsset: null,
                        isShowBorder: false,
                        borderRadius: 8.h,
                        textColor: AppColors.textColor)
                    .paddingOnly(bottom: 4.h);
              }).toList(),
            ),
            SizedBox(height: 8.h),
          ],
          title.toText16(color: AppColors.textColor, isBold: true),
          SizedBox(height: 8.h),
          description.toText12(height: 1.2.h, color: AppColors.textColorLight, isBold: true)
        ],
      ),
    );
  }

  Widget _buildStatusIcon(String title) {
    final key = title.trim();
    if (key == 'Maintenance Calories' ||
        key == 'Normal' ||
        key == 'Ideal Weight' ||
        key == 'Moderate Crabs' ||
        key == 'USDA Guidelines' ||
        key == 'Essential Fat' ||
        key == 'Athletes' ||
        key == 'Fitness') {
      return Utils.buildSvgWithAssets(icon: AppAssets.checkmark_icon, width: 24.w, height: 24.h);
    } else if (key == 'Moderate Deficit' || key == 'Low' || key == 'Underweight' || key == 'Very Low Crabs' || key == 'Low Crabs' || key == 'Zone Diet' || key == 'Average' || key == 'Acceptable') {
      return Utils.buildSvgWithAssets(icon: AppAssets.trade_down_yellow, width: 24.w, height: 24.h);
    } else if (key == 'Aggressive Deficit' || key == 'High' || key == 'Overweight' || key == "Obese") {
      return Utils.buildSvgWithAssets(icon: AppAssets.trade_down_red, width: 24.w, height: 24.h);
    } else {
      return SizedBox();
    }
  }

  Color getTextColor(String title) {
    final key = title.trim();
    if (key == 'Maintenance Calories' ||
        key == 'Normal' ||
        key == 'Ideal Weight' ||
        key == 'Moderate Crabs' ||
        key == 'USDA Guidelines' ||
        key == 'Essential Fat' ||
        key == 'Athletes' ||
        key == 'Fitness') {
      return AppColors.successColor;
    } else if (key == 'Moderate Deficit' || key == 'Low' || key == 'Underweight' || key == 'Very Low Crabs' || key == 'Low Crabs' || key == 'Zone Diet' || key == 'Average' || key == 'Acceptable') {
      return AppColors.warningColor;
    } else if (key == 'Aggressive Deficit' || key == 'High' || key == 'Overweight' || key == "Obese") {
      return AppColors.errorColor;
    } else {
      return Colors.black;
    }
  }

  void onLiveCareClinicSelected(GetLiveCareClinicsResponseModel clinic) {
    bookAppointmentsViewModel.setLiveCareSelectedClinic(clinic);
    bookAppointmentsViewModel.setIsLiveCareDoctorsListLoading(true);
    Navigator.of(context).push(
      CustomPageRoute(
        page: SelectDoctorPage(),
      ),
    );
  }

  void onClinicSelected(GetClinicsListResponseModel clinic) {
    bookAppointmentsViewModel.setSelectedClinic(clinic);
    bookAppointmentsViewModel.setIsDoctorsListLoading(true);
    searchEditingController.text = "";
    if (clinic.isLiveCareClinicAndOnline ?? false) {
      Navigator.of(context).push(
        CustomPageRoute(
          page: SelectLivecareClinicPage(
            onNegativeClicked: () {
              handleDoctorScreen(clinic);
            },
            selectedClinic: clinic,
          ),
        ),
      );
    } else {
      handleDoctorScreen(clinic);
    }
  }

  //17 and 235
  void handleDoctorScreen(GetClinicsListResponseModel clinic) async {
    regionalViewModel.flush();
    if (widget.isFromRegionFlow) {
      //Dental Clinic Flow
      if (clinic.clinicID == 17) {
        if (appState.isAuthenticated) {
          initDentalAppointmentBookingFlow(int.parse(bookAppointmentsViewModel.currentlySelectedHospitalFromRegionFlow ?? "0"));
          return;
        } else {
          bookAppointmentsViewModel.setIsChiefComplaintsListLoading(true);
          Navigator.of(context).push(
            CustomPageRoute(
              page: DentalChiefComplaintsPage(),
            ),
          );
          return;
        }
      } else if (clinic.clinicID == 253) {
        bookAppointmentsViewModel.resetLaserData();
        bookAppointmentsViewModel.getLaserClinic();
        Navigator.push(
          context,
          CustomPageRoute(
            page: LaserAppointment(),
          ),
        );
        return;
      } else {
        Navigator.push(
          context,
          CustomPageRoute(
            page: SelectDoctorPage(),
          ),
        );
      }
    } else {
      // if (clinic.clinicID == 253) {
      //   LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr(context: context));
      //   await bookAppointmentsViewModel.getLaserHospitals(
      //     onSuccess: (_) {
      //       LoaderBottomSheet.hideLoader();
      //       _showLaserHospitalBottomSheet();
      //     },
      //     onError: (err) {
      //       LoaderBottomSheet.hideLoader();
      //     },
      //   );
      //   return;
      // }
      var bottomSheetType = RegionBottomSheetType.FOR_CLINIIC;
      if (clinic.clinicID == 17) {
        // regionalViewModel.setBottomSheetState(AppointmentViaRegionState.HOSPITAL_SELECTION);
        // bottomSheetType = RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER;
        bottomSheetType = RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER;
      }
      // if (clinic.clinicID == 253) {
      //   bottomSheetType = RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER;
      // }
      openRegionListBottomSheet(context, bottomSheetType);
    }
  }

  void openRegionListBottomSheet(BuildContext context, RegionBottomSheetType type) {
    bookAppointmentsViewModel.setProjectID(null);

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

  Widget getRegionalSelectionWidget(AppointmentViaRegionViewmodel data, BuildContext context) {
    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);
            var appointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
            if (appointmentsViewModel.selectedClinic.clinicID == 253) {
              appointmentsViewModel.setProjectID(regionalViewModel.selectedHospital?.patientDoctorAppointmentList!.first.iD?.toString() ?? "");
              appointmentsViewModel.resetLaserData();
              appointmentsViewModel.getLaserClinic();
              regionalViewModel.handleLastStepForClinicForDentalAndLaser(appointmentsViewModel.selectedClinic.clinicID ?? -1);
            } else {
              regionalViewModel.handleLastStepForClinic();
            }
          } else if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER) {
            var appointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
            regionalViewModel.setBottomSheetState(AppointmentViaRegionState.DOCTOR_SELECTION);
            appointmentsViewModel.setProjectID(regionalViewModel.selectedHospital?.hospitalList.first.iD?.toString() ?? "");
            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.DOCTOR_SELECTION) {
      //if the region screen is opened for the dental clinic then the project id will be in the hospital list as the list is formed form the get project api
      var id = "";
      if (data.regionBottomSheetType == RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER) {
        id = regionalViewModel.selectedHospital?.hospitalList.first.iD?.toString() ?? "";
      } else {
        id = regionalViewModel.selectedHospital?.patientDoctorAppointmentList?.first.projectID?.toString() ?? "";
      }
      if (bookAppointmentsViewModel.selectedClinic.clinicID == 17) {
        bookAppointmentsViewModel.setProjectID(id);
        if (appState.isAuthenticated) {
          initDentalAppointment();
          return SizedBox.shrink();
        } else {
          bookAppointmentsViewModel.setIsChiefComplaintsListLoading(true);
        }
      }

      // if (bookAppointmentsViewModel.selectedClinic.clinicID == 253) {
      //   // {
      //     // bookAppointmentsViewModel.resetLaserData();
      //     // bookAppointmentsViewModel.getLaserClinic();
      //     // Navigator.push(
      //     //   context,
      //     //   CustomPageRoute(
      //     //     page: LaserAppointment(),
      //     //   ),
      //     // );
      //   // }
      // }
      bookAppointmentsViewModel.setProjectID(id);
      return SizedBox.shrink();
    } else {
      return SizedBox.shrink();
    }
    return SizedBox.shrink();
  }

  getTitle(AppointmentViaRegionViewmodel data) {
    if (data.selectedRegionId == null) {
      return Expanded(
        child: "${LocaleKeys.selectRegion.tr(context: context)} ${LocaleKeys.forText.tr(context: context)} '${bookAppointmentsViewModel.selectedClinic.clinicDescription}'".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();
      });
    }
  }

  void initDentalAppointmentBookingFlow(int projectID) async {
    bookAppointmentsViewModel.setProjectID(projectID.toString());
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingForExistingDentalPlan.tr(context: context));
    await bookAppointmentsViewModel.getPatientDentalEstimation(projectID: projectID).then((value) {
      LoaderBottomSheet.hideLoader();
      if (bookAppointmentsViewModel.patientDentalPlanEstimationList.isNotEmpty) {
        showCommonBottomSheetWithoutHeight(
          // title: LocaleKeys.notice.tr(context: context),
          title: LocaleKeys.dentalTreatmentPlan.tr(context: context),
          context,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              LocaleKeys.youHaveExistingTreatmentPlan.tr(context: context).toText14(isBold: true),
              SizedBox(height: 8.h),
              Container(
                width: double.infinity,
                padding: EdgeInsets.all(16.h),
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                  color: AppColors.whiteColor,
                  borderRadius: 20.h,
                  hasShadow: true,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ListView.separated(
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: bookAppointmentsViewModel.patientDentalPlanEstimationList.length,
                      separatorBuilder: (_, __) {
                        return Column(
                          children: [
                            SizedBox(height: 8.h),
                            Divider(height: 1, color: AppColors.greyColor),
                            SizedBox(height: 8.h),
                          ],
                        );
                      },
                      itemBuilder: (context, index) {
                        return Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            bookAppointmentsViewModel.patientDentalPlanEstimationList[index].procedureName!.toText12(isBold: true),
                            AppCustomChipWidget(
                                icon: AppAssets.appointment_time_icon, labelText: "${bookAppointmentsViewModel.totalTimeNeededForDentalProcedure} ${LocaleKeys.mins.tr(context: context)}"),
                          ],
                        );
                      },
                    ),
                    SizedBox(
                      height: 16.h,
                    ),
                    Divider(height: 1, color: AppColors.greyColor),
                    SizedBox(
                      height: 8.h,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        LocaleKeys.totalTimeRequired.tr(context: context).toText14(isBold: true),
                        AppCustomChipWidget(icon: AppAssets.appointment_time_icon, labelText: "30 ${LocaleKeys.mins.tr(context: context)}"),
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(height: 16.h),
              LocaleKeys.wouldYouLikeToContinue.tr(context: context).toText14(isBold: true),
              SizedBox(height: 16.h),
              Row(
                children: [
                  Expanded(
                    child: CustomButton(
                      text: LocaleKeys.cancel.tr(context: context),
                      onPressed: () {
                        bookAppointmentsViewModel.setIsContinueDentalPlan(false);
                        bookAppointmentsViewModel.setIsChiefComplaintsListLoading(true);
                        Navigator.of(context).pop();
                        Navigator.of(context).push(
                          CustomPageRoute(
                            page: DentalChiefComplaintsPage(),
                          ),
                        );
                      },
                      backgroundColor: AppColors.primaryRedColor,
                      borderColor: AppColors.primaryRedColor,
                      textColor: AppColors.whiteColor,
                      icon: AppAssets.cancel,
                      iconColor: AppColors.whiteColor,
                    ),
                  ),
                  SizedBox(width: 8.h),
                  Expanded(
                    child: CustomButton(
                      text: LocaleKeys.confirm.tr(context: context),
                      onPressed: () async {
                        bookAppointmentsViewModel.setIsContinueDentalPlan(true);
                        Navigator.of(context).pop();
                        Navigator.of(context).push(
                          CustomPageRoute(page: SelectDoctorPage()),
                        );
                      },
                      backgroundColor: AppColors.bgGreenColor,
                      borderColor: AppColors.bgGreenColor,
                      textColor: Colors.white,
                      icon: AppAssets.confirm,
                    ),
                  ),
                ],
              )
            ],
          ),
          callBackFunc: () {},
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      } else {
        bookAppointmentsViewModel.setIsChiefComplaintsListLoading(true);
        Navigator.of(context).push(
          CustomPageRoute(
            page: DentalChiefComplaintsPage(),
          ),
        );
      }
    });
  }

  void initDentalAppointment() async {
    await Future.delayed(Duration(milliseconds: 300));
    initDentalAppointmentBookingFlow(int.parse(bookAppointmentsViewModel.currentlySelectedHospitalFromRegionFlow ?? "0"));
    return;
  }

  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: () {
          regionVM.setSortByLocation(false);
          locationUtils.onFailureDilouge();
        },
        onLocationDeniedForever: () {
          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);

    if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_REGION || regionalViewModel.regionBottomSheetType == RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER) {
      bookAppointmentsViewModel.getRegionMappedProjectList();
    } else if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_CLINIIC) {
      bookAppointmentsViewModel.getMappedDoctors();
    }

    // bookAppointmentsViewModel.getRegionMappedProjectList();
  }

  void _showLaserHospitalBottomSheet() {
    final TextEditingController laserHospitalSearchController = TextEditingController();
    List<PatientDoctorAppointmentList> filteredList = List.from(bookAppointmentsViewModel.laserHospitalsList);

    showCommonBottomSheetWithoutHeight(
      context,
      title: LocaleKeys.selectHospital.tr(context: context),
      isDismissible: true,
      isCloseButtonVisible: true,
      child: StatefulBuilder(
        builder: (context, setModalState) {
          return HospitalBottomSheetBody(
            searchText: laserHospitalSearchController,
            displayList: filteredList,
            selectedFacility: FacilitySelection.ALL,
            hmcCount: bookAppointmentsViewModel.laserHospitalHmcCount,
            hmgCount: bookAppointmentsViewModel.laserHospitalHmgCount,
            sortByLocation: false,
            onFacilityClicked: (facility) {
              setModalState(() {
                if (facility == FacilitySelection.ALL) {
                  filteredList = List.from(bookAppointmentsViewModel.laserHospitalsList);
                } else if (facility == FacilitySelection.HMG) {
                  filteredList = bookAppointmentsViewModel.laserHospitalsList.where((h) => h.isHMC != true).toList();
                } else {
                  filteredList = bookAppointmentsViewModel.laserHospitalsList.where((h) => h.isHMC == true).toList();
                }
              });
            },
            onHospitalClicked: (hospital) {
              Navigator.of(context).pop(); // close bottom sheet
              final projectID = hospital.hospitalList.isNotEmpty ? hospital.hospitalList.first.iD?.toString() : hospital.patientDoctorAppointmentList?.first.projectID?.toString();
              bookAppointmentsViewModel.setProjectID(projectID);
              bookAppointmentsViewModel.resetLaserData();
              bookAppointmentsViewModel.getLaserClinic();
              Navigator.push(
                context,
                CustomPageRoute(page: LaserAppointment()),
              );
            },
            onHospitalSearch: (value) {
              setModalState(() {
                if (value.isEmpty) {
                  filteredList = List.from(bookAppointmentsViewModel.laserHospitalsList);
                } else {
                  filteredList = bookAppointmentsViewModel.laserHospitalsList.where((h) => h.filterName != null && h.filterName!.toLowerCase().contains(value.toLowerCase())).toList();
                }
              });
            },
          );
        },
      ),
      callBackFunc: () {},
    );
  }
}
