// ABOUTME: Blood pressure utility functions for medical categorization and validation
// ABOUTME: Provides BP category classification, color coding, and validation helpers for the UI

import 'package:flutter/material.dart';
import '../models/blood_pressure_entry.dart';
import '../utils/constants.dart';

/// Blood pressure utility functions for UI and validation
class BloodPressureUtils {
  /// Get color for blood pressure category
  static Color getCategoryColor(String category) {
    switch (category) {
      case 'normal':
        return const Color(0xFF4CAF50); // Green - success
      case 'elevated':
        return const Color(0xFFFF9800); // Orange - warning
      case 'high_stage_1':
        return const Color(0xFFFF9800); // Orange - warning
      case 'high_stage_2':
        return const Color(0xFFE53935); // Red - error
      case 'crisis':
        return const Color(0xFF8E24AA); // Deep purple for crisis
      default:
        return const Color(0xFFE53935); // Red - error
    }
  }

  /// Get icon for blood pressure category
  static IconData getCategoryIcon(String category) {
    switch (category) {
      case 'normal':
        return Icons.favorite;
      case 'elevated':
        return Icons.warning_amber;
      case 'high_stage_1':
        return Icons.warning;
      case 'high_stage_2':
        return Icons.error;
      case 'crisis':
        return Icons.local_hospital;
      default:
        return Icons.help;
    }
  }

  /// Get description for blood pressure category
  static String getCategoryDescription(String category) {
    switch (category) {
      case 'normal':
        return 'Optimal blood pressure. Keep up the good work!';
      case 'elevated':
        return 'Blood pressure is slightly elevated. Consider lifestyle changes.';
      case 'high_stage_1':
        return 'High blood pressure (Stage 1). Consider consulting your doctor.';
      case 'high_stage_2':
        return 'High blood pressure (Stage 2). Medical attention recommended.';
      case 'crisis':
        return 'Hypertensive crisis. Seek immediate medical attention!';
      default:
        return 'Blood pressure status unclear.';
    }
  }

  /// Get emergency indicator for blood pressure reading
  static bool isEmergency(int systolic, int diastolic) {
    return systolic >= 180 || diastolic >= 120;
  }

  /// Get trend arrow for blood pressure change
  static Widget getTrendArrow(BloodPressureEntry? current, BloodPressureEntry? previous) {
    if (current == null || previous == null) {
      return const SizedBox.shrink();
    }

    final currentMean = current.meanArterialPressure;
    final previousMean = previous.meanArterialPressure;
    final difference = currentMean - previousMean;

    if (difference > 5) {
      return const Icon(
        Icons.trending_up,
        color: Colors.red,
        size: 16,
      );
    } else if (difference < -5) {
      return const Icon(
        Icons.trending_down,
        color: Colors.green,
        size: 16,
      );
    } else {
      return const Icon(
        Icons.trending_flat,
        color: Colors.grey,
        size: 16,
      );
    }
  }

  /// Validate systolic blood pressure value
  static String? validateSystolic(int? systolic) {
    if (systolic == null) {
      return 'Systolic pressure is required';
    }

    if (systolic < HealthDefaults.minBloodPressure) {
      return 'Systolic pressure too low (minimum ${HealthDefaults.minBloodPressure})';
    }

    if (systolic > HealthDefaults.maxSystolic) {
      return 'Systolic pressure too high (maximum ${HealthDefaults.maxSystolic})';
    }

    return null; // Valid
  }

  /// Validate diastolic blood pressure value
  static String? validateDiastolic(int? diastolic) {
    if (diastolic == null) {
      return 'Diastolic pressure is required';
    }

    if (diastolic < HealthDefaults.minBloodPressure) {
      return 'Diastolic pressure too low (minimum ${HealthDefaults.minBloodPressure})';
    }

    if (diastolic > HealthDefaults.maxDiastolic) {
      return 'Diastolic pressure too high (maximum ${HealthDefaults.maxDiastolic})';
    }

    return null; // Valid
  }

  /// Validate both systolic and diastolic values together
  static String? validateBloodPressure(int? systolic, int? diastolic) {
    final systolicError = validateSystolic(systolic);
    if (systolicError != null) return systolicError;

    final diastolicError = validateDiastolic(diastolic);
    if (diastolicError != null) return diastolicError;

    if (systolic! <= diastolic!) {
      return 'Systolic pressure must be higher than diastolic pressure';
    }

    return null; // Valid
  }

  /// Format blood pressure reading with unit
  static String formatReading(int systolic, int diastolic) {
    return '$systolic/$diastolic ${UnitConstants.mmHgUnit}';
  }

  /// Format blood pressure reading with category
  static String formatReadingWithCategory(BloodPressureEntry entry) {
    return '${entry.formatted} (${entry.categoryDisplayName})';
  }

  /// Get formatted pulse pressure
  static String formatPulsePressure(BloodPressureEntry entry) {
    return 'Pulse Pressure: ${entry.pulsePressure} ${UnitConstants.mmHgUnit}';
  }

  /// Get formatted mean arterial pressure
  static String formatMeanArterialPressure(BloodPressureEntry entry) {
    return 'MAP: ${entry.meanArterialPressure.toStringAsFixed(1)} ${UnitConstants.mmHgUnit}';
  }

  /// Check if values are in emergency range
  static bool areValuesEmergency(int? systolic, int? diastolic) {
    if (systolic == null || diastolic == null) return false;
    return systolic >= 180 || diastolic >= 120;
  }

  /// Get emergency warning message
  static String getEmergencyWarning() {
    return '⚠️ These readings indicate a hypertensive crisis. Please seek immediate medical attention.';
  }

  /// Get health tip based on blood pressure category
  static String getHealthTip(String category) {
    switch (category) {
      case 'normal':
        return '💚 Great job! Maintain a healthy diet and regular exercise.';
      case 'elevated':
        return '🟡 Consider reducing sodium intake and increasing physical activity.';
      case 'high_stage_1':
        return '🟠 Lifestyle changes and regular monitoring are important.';
      case 'high_stage_2':
        return '🔴 Consider consulting your healthcare provider about treatment options.';
      case 'crisis':
        return '🚨 This is a medical emergency. Seek immediate care.';
      default:
        return 'Monitor your blood pressure regularly.';
    }
  }

  /// Calculate blood pressure difference between two readings
  static Map<String, double> calculateDifference(
    BloodPressureEntry current,
    BloodPressureEntry previous,
  ) {
    return {
      'systolic': (current.systolic - previous.systolic).toDouble(),
      'diastolic': (current.diastolic - previous.diastolic).toDouble(),
      'pulse_pressure': (current.pulsePressure - previous.pulsePressure).toDouble(),
      'mean_arterial': current.meanArterialPressure - previous.meanArterialPressure,
    };
  }
}
