import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';
import 'package:nokken/src/core/ui/widgets/shared_widgets.dart';
import 'package:nokken/src/core/ui/widgets/timeframe_selector.dart';
import 'package:nokken/src/features/mood_tracker/models/mood_entry.dart';
import 'package:nokken/src/features/mood_tracker/providers/mood_state.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/stats/providers/statistics_provider.dart';
import 'package:nokken/src/features/stats/widgets/analysis_card.dart';

class EmotionAnalysisScreen extends ConsumerStatefulWidget {
  final String initialTimeFrame;

  const EmotionAnalysisScreen({
    super.key,
    this.initialTimeFrame = 'All Time',
  });

  @override
  ConsumerState<EmotionAnalysisScreen> createState() =>
      _EmotionAnalysisScreenState();
}

class _EmotionAnalysisScreenState extends ConsumerState<EmotionAnalysisScreen> {
  late String _selectedTimeFrame;
  String? _selectedEmotion;

  @override
  void initState() {
    super.initState();
    _selectedTimeFrame = widget.initialTimeFrame;
  }

  void _selectEmotion(String emotion) {
    setState(() {
      if (_selectedEmotion == emotion) {
        _selectedEmotion = null; // Deselect if already selected
      } else {
        _selectedEmotion = emotion;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // Get data for analysis
    final moodEntries = ref.watch(moodEntriesProvider);
    final filteredMoodEntries = TimeframeSelector.filterByTimeframe(
      items: moodEntries,
      timeframe: _selectedTimeFrame,
      getDate: (entry) => entry.date,
    );

    // Watch for comprehensive analysis
    final analysisAsync =
        ref.watch(comprehensiveAnalysisProvider(_selectedTimeFrame));

    return Scaffold(
      appBar: AppBar(
        title: const Text('Emotion Analysis'),
        actions: [
          TimeframeSelector.dropdownButton(
            context: context,
            selectedTimeframe: _selectedTimeFrame,
            onTimeframeSelected: (value) {
              setState(() {
                _selectedTimeFrame = value;
                _selectedEmotion =
                    null; // Reset selection when timeframe changes
              });
            },
          ),
        ],
      ),
      body: analysisAsync.when(
        data: (analysis) {
          if (filteredMoodEntries.isEmpty) {
            return _buildNoDataView();
          }

          return _buildEmotionAnalysisContent(
            filteredMoodEntries,
            analysis,
          );
        },
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (error, stack) => _buildErrorView(error.toString()),
      ),
    );
  }

  Widget _buildEmotionAnalysisContent(
    List<MoodEntry> moodEntries,
    ComprehensiveAnalysis analysis,
  ) {
    return ListView(
      padding: const EdgeInsets.all(12),
      children: [
        // Emotion Selection Grid at the top
        AnalysisCard(
          title: 'Select an Emotion',
          subtitle: 'Tap for insights',
          content: _buildEmotionSelectionGrid(moodEntries),
          icon: Icons.emoji_emotions,
          color: Colors.purple,
        ),

        SharedWidgets.verticalSpace(8),

        // Selected emotion analysis (if any)
        if (_selectedEmotion != null) ...[
          _buildSelectedEmotionAnalysis(
              _selectedEmotion!, moodEntries, analysis),
          SharedWidgets.verticalSpace(8),
        ],

        // Emotions Distribution
        AnalysisCard(
          title: 'Emotions Overview',
          subtitle: 'Most common emotions',
          content: _buildEmotionsOverview(moodEntries),
          icon: Icons.emoji_emotions,
          color: Colors.purple,
        ),
      ],
    );
  }

  Widget _buildEmotionSelectionGrid(List<MoodEntry> moodEntries) {
    // Count emotions
    final emotionCounts = <String, int>{};
    for (final entry in moodEntries) {
      for (final emotion in entry.emotions) {
        final emotionName = emotion.name;
        emotionCounts[emotionName] = (emotionCounts[emotionName] ?? 0) + 1;
      }
    }

    // Sort emotions by frequency
    final sortedEmotions = emotionCounts.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Grid of emotions to select
        Wrap(
          spacing: 6,
          runSpacing: 6,
          children: [
            // Add emotions
            ...sortedEmotions.map((entry) {
              final emotionName = entry.key;
              final count = entry.value;
              final isSelected = _selectedEmotion == emotionName;

              return _buildCompactSelectionChip(
                emotionName,
                MoodUtils.getEmotionIcon(emotionName),
                MoodUtils.getEmotionColorString(emotionName),
                isSelected,
                count,
                () => _selectEmotion(emotionName),
              );
            }),
          ],
        ),
      ],
    );
  }

  Widget _buildCompactSelectionChip(
    String name,
    IconData icon,
    Color color,
    bool isSelected,
    int? count,
    VoidCallback onTap,
  ) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: isSelected ? color : color.withAlpha(20),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: color,
            width: isSelected ? 2 : 1,
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              color: isSelected ? Colors.white : color,
              size: 12,
            ),
            SharedWidgets.horizontalSpace(4),
            Text(
              name,
              style: TextStyle(
                color: isSelected ? Colors.white : color,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                fontSize: 10,
              ),
            ),
            if (count != null) ...[
              SharedWidgets.horizontalSpace(2),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                decoration: BoxDecoration(
                  color: isSelected
                      ? Colors.white.withAlpha(50)
                      : color.withAlpha(40),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Text(
                  count.toString(),
                  style: TextStyle(
                    fontSize: 8,
                    color: isSelected ? Colors.white : color,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildSelectedEmotionAnalysis(
    String emotionName,
    List<MoodEntry> entries,
    ComprehensiveAnalysis analysis,
  ) {
    // Filter entries that have this emotion
    final entriesWithEmotion = entries.where((entry) {
      return entry.emotions.any((e) => e.name == emotionName);
    }).toList();

    if (entriesWithEmotion.isEmpty) {
      return Text(
        'No data available for $emotionName analysis.',
        style: AppTextStyles.bodySmall,
      );
    }

    // Get dates when this emotion was recorded
    final dates = entriesWithEmotion.map((e) => e.date).toList();

    // Find relationships involving this emotion
    final emotionRelationships = analysis.relationships.where((rel) {
      return rel.factorNames.any((name) => name == 'Emotion: $emotionName');
    }).toList();

    return AnalysisCard(
      title: '$emotionName Analysis',
      subtitle: 'Insights for this emotion',
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Basic stats - compact layout
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildCompactStatBox(
                'Occurrences',
                entriesWithEmotion.length.toString(),
                MoodUtils.getEmotionColorString(emotionName),
              ),
              _buildCompactStatBox(
                'Frequency',
                '${(entriesWithEmotion.length / entries.length * 100).toStringAsFixed(0)}%',
                MoodUtils.getEmotionColorString(emotionName),
              ),
              _buildCompactStatBox(
                'Last Felt',
                _getDaysAgo(dates.isNotEmpty ? dates.last : null),
                MoodUtils.getEmotionColorString(emotionName),
              ),
            ],
          ),

          const SizedBox(height: 12),

          // Show associated moods - compact chart
          Text(
            'Associated Moods:',
            style:
                AppTextStyles.bodySmall.copyWith(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 4),

          SizedBox(
            height: 60,
            child: _buildAssociatedMoodsChart(entriesWithEmotion),
          ),

          const SizedBox(height: 12),

          // Show correlations
          if (emotionRelationships.isNotEmpty) ...[
            Text(
              'Correlations:',
              style:
                  AppTextStyles.bodySmall.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 4),

            // More compact correlation display
            ...emotionRelationships.take(2).map((relationship) {
              // Get the other factor name
              final otherFactorName = relationship.factorNames.firstWhere(
                (name) => name != 'Emotion: $emotionName',
                orElse: () => relationship.factorNames.first,
              );

              return Padding(
                padding: const EdgeInsets.only(bottom: 6.0),
                child: Row(
                  children: [
                    Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: relationship.relationshipColor.withAlpha(30),
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                        child: Text(
                          '${(relationship.strength * 100).toStringAsFixed(0)}%',
                          style: TextStyle(
                            fontSize: 9,
                            fontWeight: FontWeight.bold,
                            color: relationship.relationshipColor,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 6),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            _getDisplayName(otherFactorName),
                            style: AppTextStyles.bodySmall.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            relationship.description,
                            style:
                                AppTextStyles.bodySmall.copyWith(fontSize: 10),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            }),
          ],

          const SizedBox(height: 12),

          // Insights
          Text(
            'Insights:',
            style:
                AppTextStyles.bodySmall.copyWith(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 4),

          _buildEmotionInsights(emotionName, entriesWithEmotion, dates),
        ],
      ),
      icon: MoodUtils.getEmotionIcon(emotionName),
      color: MoodUtils.getEmotionColorString(emotionName),
    );
  }

  Widget _buildCompactStatBox(String label, String value, Color color) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: color.withAlpha(20),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Text(
            value,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          Text(
            label,
            style: AppTextStyles.bodySmall.copyWith(fontSize: 10),
          ),
        ],
      ),
    );
  }

  Widget _buildAssociatedMoodsChart(List<MoodEntry> entries) {
    // Count mood ratings
    final moodCounts = <MoodRating, int>{};
    for (final mood in MoodRating.values) {
      moodCounts[mood] = 0;
    }

    for (final entry in entries) {
      moodCounts[entry.mood] = (moodCounts[entry.mood] ?? 0) + 1;
    }

    // Calculate percentages
    final moodPercentages = <MoodRating, double>{};
    for (final mood in MoodRating.values) {
      moodPercentages[mood] =
          entries.isEmpty ? 0.0 : (moodCounts[mood] ?? 0) / entries.length;
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: MoodRating.values.map((mood) {
        final count = moodCounts[mood] ?? 0;
        final percentage = moodPercentages[mood] ?? 0.0;

        return Column(
          children: [
            // Bar visualization
            Container(
              width: 20,
              height: 30 * percentage,
              decoration: BoxDecoration(
                color: MoodUtils.getMoodColor(mood),
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(3),
                ),
              ),
            ),

            // Mood emoji
            Text(
              mood.emoji,
              style: const TextStyle(
                fontSize: 12,
                fontFamily: 'EmojiFont',
              ),
            ),

            // Count
            Text(
              count.toString(),
              style: AppTextStyles.bodySmall.copyWith(fontSize: 9),
            ),
          ],
        );
      }).toList(),
    );
  }

  Widget _buildEmotionInsights(
    String emotionName,
    List<MoodEntry> entries,
    List<DateTime> dates,
  ) {
    if (entries.isEmpty) {
      return Text(
        'No data available for $emotionName yet.',
        style: AppTextStyles.bodySmall,
      );
    }

    // Calculate insights
    final totalEntries = entries.length;

    // Most common day of week
    final dayOfWeekCounts = <int, int>{};
    for (final date in dates) {
      final dayOfWeek = date.weekday;
      dayOfWeekCounts[dayOfWeek] = (dayOfWeekCounts[dayOfWeek] ?? 0) + 1;
    }

    int? mostCommonDay;
    int maxCount = 0;
    for (final entry in dayOfWeekCounts.entries) {
      if (entry.value > maxCount) {
        maxCount = entry.value;
        mostCommonDay = entry.key;
      }
    }

    // Get associated mood
    MoodRating? mostCommonMood;
    int maxMoodCount = 0;

    final moodCounts = <MoodRating, int>{};
    for (final entry in entries) {
      moodCounts[entry.mood] = (moodCounts[entry.mood] ?? 0) + 1;

      if ((moodCounts[entry.mood] ?? 0) > maxMoodCount) {
        maxMoodCount = moodCounts[entry.mood] ?? 0;
        mostCommonMood = entry.mood;
      }
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Icon(
              Icons.insights,
              color: MoodUtils.getEmotionColorString(emotionName),
              size: 14,
            ),
            const SizedBox(width: 6),
            Expanded(
              child: Text(
                'You\'ve recorded $emotionName $totalEntries times.',
                style: AppTextStyles.bodySmall.copyWith(fontSize: 10),
              ),
            ),
          ],
        ),
        if (mostCommonDay != null) ...[
          const SizedBox(height: 6),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Icon(
                Icons.calendar_today,
                color: MoodUtils.getEmotionColorString(emotionName),
                size: 14,
              ),
              const SizedBox(width: 6),
              Expanded(
                child: Text(
                  'Most often on ${_getDayName(mostCommonDay)}s.',
                  style: AppTextStyles.bodySmall.copyWith(fontSize: 10),
                ),
              ),
            ],
          ),
        ],
        if (mostCommonMood != null) ...[
          const SizedBox(height: 6),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Icon(
                Icons.mood,
                color: MoodUtils.getMoodColor(mostCommonMood),
                size: 14,
              ),
              const SizedBox(width: 6),
              Expanded(
                child: Text(
                  'Usually feel ${mostCommonMood.displayName.toLowerCase()} when experiencing $emotionName.',
                  style: AppTextStyles.bodySmall.copyWith(fontSize: 10),
                ),
              ),
            ],
          ),
        ],
      ],
    );
  }

  Widget _buildEmotionsOverview(List<MoodEntry> entries) {
    // Calculate emotion frequencies
    final emotionCounts = <String, int>{};
    int totalCount = 0;

    for (final entry in entries) {
      for (final emotion in entry.emotions) {
        final emotionName = emotion.name;
        emotionCounts[emotionName] = (emotionCounts[emotionName] ?? 0) + 1;
        totalCount++;
      }
    }

    // Sort by frequency
    final sortedEmotions = emotionCounts.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Emotion list - more compact version
        ...sortedEmotions.take(6).map((entry) {
          final emotionName = entry.key;
          final count = entry.value;
          final percentage = (count / entries.length * 100).toStringAsFixed(1);

          return Padding(
            padding: const EdgeInsets.only(bottom: 6.0),
            child: Row(
              children: [
                Container(
                  width: 22,
                  height: 22,
                  decoration: BoxDecoration(
                    color: MoodUtils.getEmotionColorString(emotionName)
                        .withAlpha(40),
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Icon(
                      MoodUtils.getEmotionIcon(emotionName),
                      color: MoodUtils.getEmotionColorString(emotionName),
                      size: 12,
                    ),
                  ),
                ),
                SharedWidgets.horizontalSpace(6),

                // Emotion name
                Expanded(
                  child: Text(
                    emotionName,
                    style: AppTextStyles.bodySmall,
                  ),
                ),

                // Percentage
                Text(
                  '$percentage%',
                  style: AppTextStyles.bodySmall.copyWith(
                    color: AppColors.onSurfaceVariant,
                    fontWeight: FontWeight.bold,
                    fontSize: 10,
                  ),
                ),

                SharedWidgets.horizontalSpace(4),

                // Progress bar - compact
                Container(
                  width: 40,
                  height: 6,
                  clipBehavior: Clip.hardEdge,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(3),
                    color: AppColors.surfaceContainer,
                  ),
                  child: FractionallySizedBox(
                    alignment: Alignment.centerLeft,
                    widthFactor: count / entries.length,
                    child: Container(
                      color: MoodUtils.getEmotionColorString(emotionName),
                    ),
                  ),
                ),
              ],
            ),
          );
        }),
      ],
    );
  }

  String _getDisplayName(String factorName) {
    if (factorName.startsWith('Emotion: ')) {
      return factorName.substring(9);
    } else if (factorName.startsWith('Hormone: ')) {
      return factorName.substring(9);
    }
    return factorName;
  }

  String _getDaysAgo(DateTime? date) {
    if (date == null) {
      return 'N/A';
    }

    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays < 1) {
      return 'Today';
    } else if (difference.inDays == 1) {
      return '1d ago';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}d ago';
    } else if (difference.inDays < 30) {
      return '${(difference.inDays / 7).floor()}w ago';
    } else if (difference.inDays < 365) {
      return '${(difference.inDays / 30).floor()}m ago';
    } else {
      return '${(difference.inDays / 365).floor()}y ago';
    }
  }

  String _getDayName(int day) {
    const days = [
      'Mon',
      'Tue',
      'Wed',
      'Thu',
      'Fri',
      'Sat',
      'Sun',
    ];
    return days[day - 1];
  }

  Widget _buildNoDataView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.emoji_emotions,
            size: 48,
            color: AppColors.primary.withAlpha(120),
          ),
          SharedWidgets.verticalSpace(8),
          Text(
            'No Emotion Data Available',
            style: AppTextStyles.titleMedium,
          ),
          SharedWidgets.verticalSpace(8),
          Text(
            'Start tracking your emotions to see analytics.',
            textAlign: TextAlign.center,
            style: AppTextStyles.bodySmall,
          ),
        ],
      ),
    );
  }

  Widget _buildErrorView(String error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 48,
            color: AppColors.error,
          ),
          SharedWidgets.verticalSpace(8),
          Text(
            'Analysis Error',
            style: AppTextStyles.titleMedium,
          ),
          SharedWidgets.verticalSpace(8),
          Text(
            'Could not generate insights: $error',
            textAlign: TextAlign.center,
            style: TextStyle(color: AppColors.error, fontSize: 12),
          ),
        ],
      ),
    );
  }
}
