// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// stat_utils.dart
//
import 'package:flutter/material.dart';
import 'dart:math' as math;
import 'package:nokken/src/features/mood_tracker/models/mood_entry.dart';
import 'package:nokken/src/features/mood_tracker/utils/mood_utils.dart';
import 'package:nokken/src/features/stats/models/stat_analysis.dart';
import 'package:nokken/src/features/bloodwork_tracker/models/bloodwork.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';

class StatUtils {
  /// Get color for mood score (0-4 scale)
  static Color getMoodColorFromScore(double score) {
    if (score >= 3.5) return MoodUtils.getMoodColor(MoodRating.great);
    if (score >= 2.5) return MoodUtils.getMoodColor(MoodRating.good);
    if (score >= 1.5) return MoodUtils.getMoodColor(MoodRating.okay);
    if (score >= 0.5) return MoodUtils.getMoodColor(MoodRating.meh);
    return MoodUtils.getMoodColor(MoodRating.bad);
  }

  /// Get mood description from score
  static String getMoodDescriptionFromScore(double score) {
    if (score >= 3.5) return 'Great';
    if (score >= 2.5) return 'Good';
    if (score >= 1.5) return 'Okay';
    if (score >= 0.5) return 'Meh';
    return 'Bad';
  }

  /// Check if data spans multiple months
  static bool hasMultiMonthData(List<MoodEntry> entries) {
    if (entries.length < 2) return false;

    final months = entries.map((e) => '${e.date.year}-${e.date.month}').toSet();
    return months.length > 1;
  }

  static IconData getFactorIcon(String factorName) {
    if (factorName == 'Mood') {
      return Icons.mood;
    } else if (factorName == 'Sleep') {
      return Icons.bedtime;
    } else if (factorName == 'Energy') {
      return Icons.battery_charging_full;
    } else if (factorName == 'Appetite') {
      return Icons.restaurant;
    } else if (factorName == 'Focus') {
      return Icons.center_focus_strong;
    } else if (factorName == 'Dysphoria') {
      return Icons.sentiment_dissatisfied;
    } else if (factorName == 'Libido') {
      return Icons.favorite;
    } else if (factorName == 'Exercise') {
      return Icons.fitness_center;
    } else if (factorName.startsWith('Emotion:')) {
      return Icons.emoji_emotions;
    } else if (factorName.startsWith('Hormone:')) {
      return Icons.science;
    } else {
      return Icons.analytics;
    }
  }

  static Color getFactorColor(String factorName) {
    if (factorName == 'Mood') {
      return Colors.amber;
    } else if (factorName == 'Sleep') {
      return Colors.indigo;
    } else if (factorName == 'Energy') {
      return Colors.orange;
    } else if (factorName == 'Appetite') {
      return Colors.green;
    } else if (factorName == 'Focus') {
      return Colors.blue;
    } else if (factorName == 'Dysphoria') {
      return Colors.purple;
    } else if (factorName == 'Libido') {
      return Colors.red;
    } else if (factorName == 'Exercise') {
      return Colors.teal;
    } else if (factorName.startsWith('Emotion:')) {
      return Colors.pinkAccent;
    } else if (factorName.startsWith('Hormone:')) {
      return Colors.deepPurple;
    } else {
      return AppColors.primary;
    }
  }

  static IconData getPatternIcon(PatternType type) {
    switch (type) {
      case PatternType.cyclical:
        return Icons.autorenew;
      case PatternType.trend:
        return Icons.trending_up;
      case PatternType.cluster:
        return Icons.bubble_chart;
      case PatternType.anomaly:
        return Icons.warning;
      case PatternType.threshold:
        return Icons.speed;
      case PatternType.unknown:
        return Icons.help_outline;
    }
  }

  static Color getHormoneColor(String hormoneName, HormoneReading reading) {
    final name = hormoneName.toLowerCase();

    // Check if in range first
    if (reading.minValue != null && reading.maxValue != null) {
      if (reading.value < reading.minValue!) {
        return Colors.red;
      } else if (reading.value > reading.maxValue!) {
        return Colors.red;
      } else {
        return Colors.green;
      }
    }

    // Default colors by hormone type
    if (name.contains('estrogen') || name.contains('estradiol')) {
      return Colors.purple;
    } else if (name.contains('testosterone')) {
      return Colors.blue;
    } else if (name.contains('thyroid') || name.contains('tsh')) {
      return Colors.teal;
    } else if (name.contains('cortisol')) {
      return Colors.orange;
    } else {
      return Colors.indigo;
    }
  }

  static String getTrendTitle(HealthTrend trend) {
    switch (trend.direction) {
      case TrendDirection.increasing:
        return 'Increasing Levels';
      case TrendDirection.decreasing:
        return 'Decreasing Levels';
      case TrendDirection.none:
        return 'Stable Levels';
    }
  }

  static String getDefaultTrendDescription(HormoneAnalysis analysis) {
    final hormoneName = analysis.hormoneName;

    switch (analysis.trend.direction) {
      case TrendDirection.increasing:
        if (analysis.averageLevel > analysis.optimalMaxLevel) {
          return '$hormoneName levels are rising and currently above the optimal range.';
        } else if (analysis.averageLevel < analysis.optimalMinLevel) {
          return '$hormoneName levels are rising, which is positive as they are currently below the optimal range.';
        } else {
          return '$hormoneName levels are rising while remaining within the optimal range.';
        }

      case TrendDirection.decreasing:
        if (analysis.averageLevel > analysis.optimalMaxLevel) {
          return '$hormoneName levels are decreasing, which is positive as they are currently above the optimal range.';
        } else if (analysis.averageLevel < analysis.optimalMinLevel) {
          return '$hormoneName levels are decreasing and currently below the optimal range.';
        } else {
          return '$hormoneName levels are decreasing while remaining within the optimal range.';
        }

      case TrendDirection.none:
        if (analysis.isWithinOptimalRange) {
          return '$hormoneName levels are stable and within the optimal range, which is ideal.';
        } else {
          return '$hormoneName levels are stable but ${analysis.averageLevel < analysis.optimalMinLevel ? 'below' : 'above'} the optimal range.';
        }
    }
  }

  static String getDayName(int weekday) {
    switch (weekday) {
      case 0:
        return 'Mon';
      case 1:
        return 'Tue';
      case 2:
        return 'Wed';
      case 3:
        return 'Thu';
      case 4:
        return 'Fri';
      case 5:
        return 'Sat';
      case 6:
        return 'Sun';
      default:
        return '';
    }
  }

  static String getCustomInsight(String emotionName) {
    final name = emotionName.toLowerCase();

    if (name == 'happy' || name == 'joy') {
      return 'Tracking what makes you happy can help reinforce positive habits and increase overall well-being.';
    } else if (name == 'sad') {
      return 'Noticing patterns in sadness can help identify triggers and develop coping strategies.';
    } else if (name == 'angry') {
      return 'Understanding anger patterns helps with emotional regulation and reducing stress.';
    } else if (name == 'anxious' || name == 'stressed') {
      return 'Recognizing anxiety triggers can be the first step toward developing effective management techniques.';
    } else if (name == 'relaxed') {
      return 'Identifying what helps you feel relaxed can be valuable for stress management.';
    } else if (name == 'tired') {
      return 'Tracking fatigue patterns can help optimize your sleep and energy management.';
    } else if (name == 'excited') {
      return 'Noticing what excites you can help bring more positive experiences into your life.';
    } else if (name == 'bored') {
      return 'Understanding boredom patterns can help identify areas where you might need more stimulation or purpose.';
    } else {
      return 'Understanding your emotional patterns can help you develop greater emotional intelligence and self-awareness.';
    }
  }

  static String calculateDiversityScore(
      int uniqueEmotions, double avgPerEntry) {
    // Simple algorithm for diversity score (0-10 scale)
    final rawScore = (uniqueEmotions * 0.3) + (avgPerEntry * 1.5);

    return math.min(rawScore, 10).toStringAsFixed(1);
  }

  static String getDiversityDescription(
      int uniqueEmotions, double avgPerEntry) {
    final score =
        double.parse(calculateDiversityScore(uniqueEmotions, avgPerEntry));

    if (score >= 8.0) {
      return 'You have a rich emotional vocabulary and track a diverse range of emotions';
    } else if (score >= 6.0) {
      return 'You have a good emotional awareness with a healthy range of tracked emotions';
    } else if (score >= 4.0) {
      return 'You track a moderate range of emotions, with room to expand your emotional awareness';
    } else {
      return 'Consider expanding your emotional tracking to develop greater emotional intelligence';
    }
  }

  int min(double a, double b) {
    return a < b ? a.toInt() : b.toInt();
  }
}
