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/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.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/symptoms_checker/widgets/custom_progress_bar.dart';
import 'package:hmg_patient_app_new/services/dialog_service.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/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:provider/provider.dart';

class ConditionCard extends StatelessWidget {
  final TriageCondition condition;
  final List<String> symptoms;
  final VoidCallback? onActionPressed;

  const ConditionCard({
    super.key,
    required this.condition,
    required this.symptoms,
    this.onActionPressed,
  });

  /// Get title from condition (localized)
  String get title {
    final appState = getIt<AppState>();
    return condition.getDisplayName(isArabic: appState.isArabic());
  }

  /// Get percentage from probability (0-1 to 0-100)
  int get percentage => ((condition.probability ?? 0) * 100).toInt();

  /// Get clinic name from category
  String get clinic => condition.conditionDetails?.category?.name ?? '';

  /// Get description from hint
  String get description => condition.conditionDetails?.hint ?? '';

  /// Get severity enum based on triage level
  PossibleConditionsSeverityEnum get severityEnum {
    final triageLevel = condition.conditionDetails?.triageLevel;
    if (triageLevel != null) {
      switch (triageLevel) {
        case TriageLevelEnum.emergencyAmbulance:
        case TriageLevelEnum.emergency:
          return PossibleConditionsSeverityEnum.emergency;
        case TriageLevelEnum.consultation24:
        case TriageLevelEnum.consultation:
          return PossibleConditionsSeverityEnum.seekMedicalAdvice;
        case TriageLevelEnum.selfCare:
          return PossibleConditionsSeverityEnum.monitorOnly;
      }
    }
    // Default based on probability
    if (percentage >= 70) {
      return PossibleConditionsSeverityEnum.seekMedicalAdvice;
    } else {
      return PossibleConditionsSeverityEnum.monitorOnly;
    }
  }

  /// Get tag text based on triage level
  String getTagText(BuildContext context) {
    final triageLevel = condition.conditionDetails?.triageLevel;
    if (triageLevel != null) {
      switch (triageLevel) {
        case TriageLevelEnum.emergencyAmbulance:
        case TriageLevelEnum.emergency:
          return LocaleKeys.emergency.tr(context: context);
        case TriageLevelEnum.consultation24:
        case TriageLevelEnum.consultation:
          return LocaleKeys.seekMedicalAdvice.tr(context: context);
        case TriageLevelEnum.selfCare:
          return LocaleKeys.monitor.tr(context: context);
      }
    }
    // Default based on probability
    if (percentage >= 70) {
      return LocaleKeys.seekMedicalAdvice.tr(context: context);
    } else {
      return LocaleKeys.monitor.tr(context: context);
    }
  }

  /// Get monitor note if applicable
  String? getMonitorNote(BuildContext context) {
    if (severityEnum == PossibleConditionsSeverityEnum.monitorOnly) {
      return LocaleKeys.noNeedToVisitDoctor.tr(context: context);
    }
    return null;
  }

  /// Get icon based on category name from API
  IconData get icon {
    final categoryName = condition.conditionDetails?.category?.name?.toLowerCase() ?? '';

    if (categoryName.contains('cardio') || categoryName.contains('heart')) {
      return Icons.favorite;
    } else if (categoryName.contains('neuro') || categoryName.contains('brain')) {
      return Icons.psychology_alt;
    } else if (categoryName.contains('psychiatr') || categoryName.contains('mental')) {
      return Icons.psychology;
    } else if (categoryName.contains('eye') || categoryName.contains('ophthalmo')) {
      return Icons.remove_red_eye;
    } else if (categoryName.contains('ent') || categoryName.contains('ear')) {
      return Icons.hearing;
    } else if (categoryName.contains('derma') || categoryName.contains('skin')) {
      return Icons.face;
    } else if (categoryName.contains('ortho') || categoryName.contains('bone')) {
      return Icons.accessibility_new;
    } else if (categoryName.contains('gyneco') || categoryName.contains('obstet')) {
      return Icons.pregnant_woman;
    } else if (categoryName.contains('pediatr') || categoryName.contains('child')) {
      return Icons.child_care;
    } else if (categoryName.contains('surg')) {
      return Icons.local_hospital;
    } else if (categoryName.contains('pulmo') || categoryName.contains('lung') || categoryName.contains('respiratory')) {
      return Icons.air;
    } else if (categoryName.contains('gastro') || categoryName.contains('digest')) {
      return Icons.restaurant;
    } else if (categoryName.contains('nephro') || categoryName.contains('kidney')) {
      return Icons.water_drop;
    } else if (categoryName.contains('hemato') || categoryName.contains('blood')) {
      return Icons.bloodtype;
    } else if (categoryName.contains('infect') || categoryName.contains('virus')) {
      return Icons.coronavirus;
    } else if (categoryName.contains('emergency')) {
      return Icons.emergency;
    } else if (categoryName.contains('geriatr') || categoryName.contains('elder')) {
      return Icons.elderly;
    } else if (categoryName.contains('internal')) {
      return Icons.medical_services;
    }

    return Icons.medical_services;
  }

  Color getChipColorBySeverityEnum(PossibleConditionsSeverityEnum possibleConditionsSeverityEnum) {
    switch (possibleConditionsSeverityEnum) {
      case PossibleConditionsSeverityEnum.seekMedicalAdvice:
        return AppColors.chipColorSeekMedicalAdvice;
      case PossibleConditionsSeverityEnum.monitorOnly:
        return AppColors.chipColorMonitor;
      case PossibleConditionsSeverityEnum.emergency:
        return AppColors.chipColorEmergency;
    }
  }

  Color getChipTextColorBySeverityEnum(PossibleConditionsSeverityEnum possibleConditionsSeverityEnum) {
    switch (possibleConditionsSeverityEnum) {
      case PossibleConditionsSeverityEnum.seekMedicalAdvice:
        return AppColors.chipTextColorSeekMedicalAdvice;
      case PossibleConditionsSeverityEnum.monitorOnly:
        return AppColors.chipColorMonitor;
      case PossibleConditionsSeverityEnum.emergency:
        return AppColors.chipColorEmergency;
    }
  }

  _buildSymptomsRow() {
    return Wrap(
      spacing: 6.w,
      crossAxisAlignment: WrapCrossAlignment.center,
      children: [
        for (int i = 0; i < symptoms.length; i++) ...[
          "● ${symptoms[i]}".toText12(isBold: true, color: AppColors.greyTextColor, isEnglishOnly: true),
          if (i != symptoms.length - 1)
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 2.w),
              child: Icon(Icons.circle, size: 7, color: AppColors.textColor),
            ),
        ],
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    // final monitorNote = getMonitorNote(context);
    final tagText = getTagText(context);

    return Container(
      width: double.infinity,
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 32.w,
                height: 32.w,
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                  color: getChipColorBySeverityEnum(severityEnum).withValues(alpha: 0.2),
                  borderRadius: 8.r,
                  hasShadow: false,
                ),
                child: Icon(icon, color: getChipTextColorBySeverityEnum(severityEnum), size: 16.f),
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: title.toText18(isBold: true, color: AppColors.textColor),
                        ),
                        AppCustomChipWidget(
                          labelText: tagText,
                          backgroundColor: getChipColorBySeverityEnum(severityEnum).withValues(alpha: 0.2),
                          textColor: getChipTextColorBySeverityEnum(severityEnum),
                        ),
                      ],
                    ),
                    CustomRoundedProgressBar(
                      percentage: percentage,
                      height: 6.h,
                      color: getChipColorBySeverityEnum(severityEnum),
                      backgroundColor: AppColors.scaffoldBgColor,
                      titleWidget: Row(
                        children: [
                          "$percentage%".toText12(fontWeight: FontWeight.bold, color: getChipColorBySeverityEnum(severityEnum), isEnglishOnly: true),
                        ],
                      ).paddingSymmetrical(0, 4.h),
                    ),
                  ],
                ),
              ),
            ],
          ).paddingAll(16.w),
          Divider(color: AppColors.bottomNAVBorder, height: 1, thickness: 1),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              LocaleKeys.commonSymptom.tr(context: context).toText14(isBold: true, color: AppColors.textColor),
              _buildSymptomsRow(),
              SizedBox(height: 16.h),
              LocaleKeys.description.tr(context: context).toText14(weight: FontWeight.bold, color: AppColors.textColor),
              SizedBox(height: 2.h),
              description.toText12(isBold: true, color: AppColors.greyTextColor),
              SizedBox(height: 8.h),
              GestureDetector(
                onTap: () => _showExplanationBottomSheet(context),
                child: LocaleKeys.explainWhy.tr(context: context).toText12(
                      isBold: true,
                      color: AppColors.primaryRedColor,
                      isUnderLine: true,
                      decorationColor: AppColors.primaryRedColor,
                    ),
              ),
              if (severityEnum != PossibleConditionsSeverityEnum.monitorOnly)
                CustomButton(
                  text: LocaleKeys.bookAppointment.tr(context: context),
                  onPressed: () {
                    if (onActionPressed != null) {
                      onActionPressed!();
                    }
                  },
                  backgroundColor: AppColors.primaryRedColor,
                  borderColor: Colors.transparent,
                  textColor: AppColors.whiteColor,
                  fontSize: 14.f,
                  fontWeight: FontWeight.w600,
                  padding: EdgeInsets.symmetric(horizontal: 10.w),
                  icon: AppAssets.add_icon,
                  height: 48.h,
                  iconColor: AppColors.whiteColor,
                ).paddingOnly(top: 16.w),

              // if (monitorNote != null)
              //   Container(
              //     margin: EdgeInsets.only(top: 12.h),
              //     child: AppCustomChipWidget(
              //       labelText: monitorNote,
              //       backgroundColor: AppColors.whiteColor,
              //       textColor: AppColors.textColor,
              //       padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 8.h),
              //       shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
              //     ),
              //   ),
            ],
          ).paddingAll(16.w),
        ],
      ),
    );
  }

  void _showExplanationBottomSheet(BuildContext context) {
    final viewModel = context.read<SymptomsCheckerViewModel>();
    final conditionId = condition.id ?? "";

    if (conditionId.isEmpty) {
      final dialogService = getIt<DialogService>();
      dialogService.showErrorBottomSheet(
        message: "Condition ID not available",
      );
      return;
    }

    // Get all evidence with proper sources
    final allEvidenceWithSources = viewModel.getAllEvidenceWithSources();

    // Convert to format expected by GetExplanations API (with choice_id)
    final evidence = allEvidenceWithSources.map((item) {
      return {
        "id": item["id"] ?? "",
        "choice_id": "present",
        "source": item["source"] ?? "initial",
      };
    }).toList();

    // Show loading
    LoaderBottomSheet.showLoader();

    // Call Explanations API
    viewModel.fetchExplanations(
      targetConditionId: conditionId,
      evidence: evidence,
      onSuccess: (response) {
        LoaderBottomSheet.hideLoader();

        final supportingEvidence = response.dataDetails?.supportingEvidence ?? [];

        // Show bottom sheet with supporting evidence
        showCommonBottomSheetWithoutHeight(
          title: LocaleKeys.whyThisCondition.tr(context: context),
          context,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Human-understandable description
              LocaleKeys.explanationDescription.tr(context: context).toText14(
                    color: AppColors.textColor,
                  ),
              SizedBox(height: 12.h),

              // Supporting Evidence List
              if (supportingEvidence.isEmpty)
                LocaleKeys.noDataAvailable.tr(context: context).toText14(
                      color: AppColors.greyTextColor,
                    )
              else
                ...supportingEvidence.map((evidence) {
                  return Padding(
                    padding: EdgeInsets.only(bottom: 8.h),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 6.h, right: 12.w, left: 12.w),
                          width: 6.w,
                          height: 6.h,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: AppColors.textColor,
                          ),
                        ),
                        Expanded(
                          child: (evidence.getDisplayName()).toText14(
                            color: AppColors.textColor,
                          ),
                        ),
                      ],
                    ),
                  );
                }).toList(),

              SizedBox(height: 24.h),
              CustomButton(
                text: LocaleKeys.ok.tr(context: context),
                onPressed: () => Navigator.pop(context),
                backgroundColor: AppColors.primaryRedColor,
                borderColor: AppColors.primaryRedColor,
                textColor: AppColors.whiteColor,
              ),
            ],
          ),
          callBackFunc: () {},
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      },
      onError: (error) {
        LoaderBottomSheet.hideLoader();
        final dialogService = getIt<DialogService>();
        dialogService.showErrorBottomSheet(message: error);
      },
    );
  }
}
