import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/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/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/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/my_appointments/appointment_via_region_viewmodel.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/triage_response_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.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/emergency_services/nearest_er_page.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/widgets/condition_card.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/widgets/triage_level_card.dart';
import 'package:hmg_patient_app_new/services/dialog_service.dart';
import 'package:hmg_patient_app_new/services/navigation_service.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/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:provider/provider.dart';

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

  @override
  State<PossibleConditionsPage> createState() => _PossibleConditionsPageState();
}

class _PossibleConditionsPageState extends State<PossibleConditionsPage> {
  late SymptomsCheckerViewModel symptomsCheckerViewModel;
  late BookAppointmentsViewModel bookAppointmentsViewModel;
  late AppointmentViaRegionViewmodel regionalViewModel;
  late AppState appState;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      symptomsCheckerViewModel = context.read<SymptomsCheckerViewModel>();

      // Call GetTriage API to fetch triage level
      _fetchTriageLevel();

      // NOTE: Do NOT clear selections here - we need the evidence for getExplanations API
      // The evidence (symptoms, risk factors, suggestions) is needed when user taps "Explain, Why?" on condition cards
      // symptomsCheckerViewModel.clearSelectionsForPossibleConditions();
    });
  }

  void _fetchTriageLevel() {
    // Build evidence from all selections
    List<Map<String, dynamic>> evidence = [];

    // Get all evidence with proper sources
    final allEvidence = symptomsCheckerViewModel.getAllEvidenceWithSources();

    // Convert to simple format (id + choice_id)
    for (var item in allEvidence) {
      evidence.add({
        "id": item["id"] ?? "",
        "choice_id": "present",
      });
    }

    // Call Triage API
    symptomsCheckerViewModel.fetchTriageLevel(
      evidence: evidence,
      onSuccess: (response) {
        // Triage level data is now stored in ViewModel
        // UI will update automatically via Consumer
      },
      onError: (error) {
        // Silently fail - show conditions without triage card
        debugPrint("Error fetching triage level: $error");
      },
    );
  }

  Widget _buildLoadingShimmer() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Triage Level Card Shimmer

        // Condition Cards Shimmer
        ...List.generate(5, (index) {
          return Container(
            width: double.infinity,
            margin: EdgeInsets.only(left: 24.w, right: 24.w, bottom: 16.h),
            padding: EdgeInsets.all(20.w),
            decoration: BoxDecoration(
              color: AppColors.whiteColor,
              borderRadius: BorderRadius.circular(24.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.08),
                  blurRadius: 10.r,
                  offset: Offset(0, 2.h),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Condition name shimmer
                Container(
                  height: 20.h,
                  width: 220.w,
                  decoration: BoxDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                ).toShimmer2(isShow: true, radius: 8.r),
                SizedBox(height: 8.h),

                Container(
                  height: 20.h,
                  width: 200.w,
                  decoration: BoxDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                ).toShimmer2(isShow: true, radius: 8.r),
                SizedBox(height: 8.h),

                // Probability percentage shimmer
                Container(
                  height: 16.h,
                  width: 100.w,
                  decoration: BoxDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                ).toShimmer2(isShow: true, radius: 8.r),
                SizedBox(height: 30.h),
                // Action buttons shimmer
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        height: 40.h,
                        decoration: BoxDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                      ).toShimmer2(isShow: true, radius: 12.r),
                    ),
                  ],
                ),
              ],
            ),
          );
        }),
      ],
    );
  }

  Widget _buildPredictionsList(BuildContext context, List<TriageCondition> conditions, List<String> symptoms) {
    if (conditions.isEmpty) {
      return Center(
        child: Padding(
          padding: EdgeInsets.all(24.h),
          child: Text(
            LocaleKeys.noPredictionsAvailable.tr(context: context),
            style: TextStyle(
              fontSize: 16.h,
              color: AppColors.greyTextColor,
            ),
          ),
        ),
      );
    }

    final dialogService = getIt<DialogService>();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Triage Level Card at the top (if available)
        if (symptomsCheckerViewModel.triageLevelResponse?.dataDetails != null)
          TriageLevelCard(
            triageLevelData: symptomsCheckerViewModel.triageLevelResponse!.dataDetails!,
          ),

        SizedBox(height: 16.h),
        ListView.separated(
          padding: EdgeInsets.zero,
          itemCount: conditions.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          separatorBuilder: (context, index) => SizedBox(height: 16.h),
          itemBuilder: (context, index) {
            final condition = conditions[index];
            // Create temporary card to access severity enum
            final conditionCard = ConditionCard(
              condition: condition,
              symptoms: symptoms,
            );

            return ConditionCard(
              condition: condition,
              symptoms: symptoms,
              onActionPressed: () {
                // Check if condition is Emergency - redirect to Nearest ER page
                if (conditionCard.severityEnum == PossibleConditionsSeverityEnum.emergency) {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => NearestErPage(),
                    ),
                  );
                  return;
                }

                // For non-emergency cases, continue with normal booking flow
                LoaderBottomSheet.showLoader();
                symptomsCheckerViewModel.getClinicConditionsFromCategory(
                  categoryName: (condition.conditionDetails!.category!.name) ?? "Other",
                  onSuccess: (value) {
                    LoaderBottomSheet.hideLoader();
                    debugPrint("isBookingFromSymptomsChecker:: ${symptomsCheckerViewModel.isBookingFromSymptomsChecker}");
                    debugPrint(symptomsCheckerViewModel.clinicDetailsList.first.clinicID.toString());
                    initiateBookAppointmentFlow(context);
                  },
                  onError: (err) {
                    LoaderBottomSheet.hideLoader();
                    dialogService.showErrorBottomSheet(
                      message: err.toString(),
                    );
                  },
                );
              },
            );
          },
        ).paddingSymmetrical(24.w, 0),
        SizedBox(height: 24.h),
      ],
    );
  }

  _buildConfirmationBottomSheet({required BuildContext context, required VoidCallback onConfirm}) {
    return showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.notice.tr(context: context),
      context,
      child: Utils.getWarningWidget(
        loadingText: LocaleKeys.areYouSureYouWantToExitProgress.tr(context: context),
        isShowActionButtons: true,
        onCancelTap: () => Navigator.pop(context),
        onConfirmTap: () {
          // Clear all evidence before exiting
          symptomsCheckerViewModel.clearSelectionsForPossibleConditions();
          onConfirm();
        },
      ),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  Widget _buildInfoTile({required PossibleConditionsSeverityEnum severityEnum, required BuildContext context}) {
    String title;
    String description;
    Color dotColor;

    switch (severityEnum) {
      case PossibleConditionsSeverityEnum.monitorOnly:
        title = LocaleKeys.monitor.tr(context: context);
        description = LocaleKeys.monitorDescription.tr(context: context);
        dotColor = AppColors.chipColorMonitor;
        break;
      case PossibleConditionsSeverityEnum.seekMedicalAdvice:
        title = LocaleKeys.seekMedicalAdvice.tr(context: context);
        description = LocaleKeys.seekMedicalAdviceDescription.tr(context: context);
        dotColor = AppColors.chipColorSeekMedicalAdvice;
        break;
      case PossibleConditionsSeverityEnum.emergency:
        title = LocaleKeys.emergency.tr(context: context);
        description = LocaleKeys.emergencyDescription.tr(context: context);
        dotColor = AppColors.chipColorEmergency;
        break;
    }

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: 14.h,
          width: 14.w,
          decoration: BoxDecoration(shape: BoxShape.circle, color: dotColor),
        ).paddingOnly(top: 3.h),
        SizedBox(width: 8.w),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              title.toText14(isBold: true, color: AppColors.textColor),
              SizedBox(height: 4.h),
              description.toText12(isBold: true, color: AppColors.greyTextColor),
            ],
          ),
        ),
      ],
    );
  }

  _buildSeverityDetailsBottomsheet({required BuildContext context}) {
    return showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.colorScience.tr(context: context),
      context,
      child: Container(
        padding: EdgeInsets.all(16.w),
        width: double.infinity,
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true),
        child: Column(
          children: [
            _buildInfoTile(severityEnum: PossibleConditionsSeverityEnum.monitorOnly, context: context),
            Divider(color: AppColors.bottomNAVBorder, height: 24.h, thickness: 1),
            _buildInfoTile(severityEnum: PossibleConditionsSeverityEnum.seekMedicalAdvice, context: context),
            Divider(color: AppColors.bottomNAVBorder, height: 24.h, thickness: 1),
            _buildInfoTile(severityEnum: PossibleConditionsSeverityEnum.emergency, context: context),
          ],
        ),
      ),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  _buildTrailingSection(BuildContext context) {
    return Container(
      height: 40.h,
      padding: EdgeInsets.all(8.w),
      child: Center(
        child: Utils.buildSvgWithAssets(
          icon: AppAssets.coloredDotsIcon,
          height: 20.h,
          width: 20.w,
        ),
      ),
    ).onPress(() => _buildSeverityDetailsBottomsheet(context: context));
  }

  @override
  Widget build(BuildContext context) {
    symptomsCheckerViewModel = context.read<SymptomsCheckerViewModel>();
    bookAppointmentsViewModel = context.read<BookAppointmentsViewModel>();
    regionalViewModel = context.read<AppointmentViaRegionViewmodel>();
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.possibleConditions.tr(context: context),
        leadingCallback: () => _buildConfirmationBottomSheet(
          context: context,
          onConfirm: () {
            context.pop();
            symptomsCheckerViewModel.reset(); // Clear all symptoms checker data
            final navigationService = getIt.get<NavigationService>();
            // navigationService.replaceAllRoutesAndNavigateToLanding();
            navigationService.replaceAllRoutesAndNavigateToLandingAuth();
          },
        ),
        trailing: _buildTrailingSection(context),
        child: Consumer<SymptomsCheckerViewModel>(
          builder: (context, symptomsCheckerViewModel, child) {
            // Show shimmer while loading triage level or conditions
            if (symptomsCheckerViewModel.isPossibleConditionsLoading ||
                symptomsCheckerViewModel.isTriageDiagnosisLoading ||
                symptomsCheckerViewModel.isTriageLevelLoading) {
              return _buildLoadingShimmer();
            }
            // Get conditions directly from ViewModel
            final conditions = symptomsCheckerViewModel.currentConditions ?? [];
            // Get selected symptoms names for display
            final symptoms = symptomsCheckerViewModel
                .getAllSelectedSymptoms()
                .map((s) => (appState.isArabic() ? s.commonNameAr ?? s.nameAr ?? '' : s.commonName ?? s.name ?? ''))
                .where((name) => name.isNotEmpty)
                .take(3)
                .toList();
            return _buildPredictionsList(context, conditions, symptoms);
          },
        ),
      ),
    );
  }

  initiateBookAppointmentFlow(BuildContext context) {
    // Set flag to indicate booking is from symptoms checker
    symptomsCheckerViewModel.setBookingFromSymptomsChecker(true);
    // Check if clinicDetailsList is not empty before accessing
    if (symptomsCheckerViewModel.clinicDetailsList.isEmpty) {
      // Show error if no clinic details available
      final dialogService = getIt<DialogService>();
      dialogService.showErrorBottomSheet(
        message: appState.isArabic() ? "لا توجد تفاصيل عيادة متاحة" : "No clinic details available",
      );
      return;
    }

    // bookAppointmentsViewModel.getLocation();
    bookAppointmentsViewModel.setSelectedClinic(GetClinicsListResponseModel(
      clinicID: symptomsCheckerViewModel.clinicDetailsList.first.clinicID,
      clinicDescription: symptomsCheckerViewModel.clinicDetailsList.first.category,
      clinicDescriptionN: symptomsCheckerViewModel.clinicDetailsList.first.categoryAR,
    ));
    bookAppointmentsViewModel.setIsDoctorsListLoading(true);

    var bottomSheetType = RegionBottomSheetType.FOR_CLINIIC;
    openRegionListBottomSheet(context, bottomSheetType);
  }

  getTitle(AppointmentViaRegionViewmodel data, BuildContext context) {
    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();
        // Reset flag if user goes back during symptoms checker booking
        if (symptomsCheckerViewModel.isBookingFromSymptomsChecker) {
          symptomsCheckerViewModel.setBookingFromSymptomsChecker(false);
        }
      });
    }
  }

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

    regionalViewModel.flush();
    regionalViewModel.setBottomSheetType(type);
    // AppointmentViaRegionViewmodel? viewmodel = null;
    showCommonBottomSheetWithoutHeight(context,
        title: "",
        titleWidget: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) => getTitle(data, context)),
        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);
            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);
            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) {
        // Check if hospitalList is not empty before accessing first
        if (regionalViewModel.selectedHospital?.hospitalList != null && regionalViewModel.selectedHospital!.hospitalList.isNotEmpty) {
          id = regionalViewModel.selectedHospital!.hospitalList.first.iD?.toString() ?? "";
        }
      } else {
        // Check if patientDoctorAppointmentList is not empty before accessing first
        if (regionalViewModel.selectedHospital?.patientDoctorAppointmentList != null &&
            regionalViewModel.selectedHospital!.patientDoctorAppointmentList!.isNotEmpty) {
          id = regionalViewModel.selectedHospital!.patientDoctorAppointmentList!.first.projectID?.toString() ?? "";
        }
      }
      bookAppointmentsViewModel.setProjectID(id);
      return SizedBox.shrink();
    } else {
      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: () {
          regionVM.setSortByLocation(false);
          locationUtils.onFailureDilouge();
        },
        onLocationDeniedForever: () {
          regionVM.setSortByLocation(false);
        },
      );
    } else {
      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();
  }
}
