// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// day_of_week_card.dart
//
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/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/stats/models/stat_analysis.dart';
import 'package:nokken/src/features/stats/charts/weekday_chart.dart';

class DayOfWeekCard extends ConsumerWidget {
  final String timeframe;

  const DayOfWeekCard({
    super.key,
    required this.timeframe,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Get mood entries from the provider
    final moodEntries = ref.watch(moodEntriesProvider);
    final filteredEntries = TimeframeSelector.filterByTimeframe(
      items: moodEntries,
      timeframe: timeframe,
      getDate: (entry) => entry.date,
    );

    // Check if we have enough data
    if (filteredEntries.length < 7) {
      return _buildEmptyState();
    }

    // Create the analysis
    final weekdayAnalysis = _createWeekdayAnalysis(filteredEntries);

    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.amber.withAlpha(30),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.calendar_today,
                    color: Colors.amber,
                    size: 24,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Day of Week Patterns',
                        style: AppTextStyles.titleMedium,
                      ),
                      Text(
                        'How your mood varies by day',
                        style: AppTextStyles.bodySmall.copyWith(
                          color: AppColors.onSurfaceVariant,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // Chart
            SizedBox(
              height: 180,
              child: WeekdayBarChart(
                analysis: weekdayAnalysis,
                factor: 'Mood',
              ),
            ),

            const SizedBox(height: 16),

            // Key findings
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: AppColors.surfaceContainer,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      const Icon(
                        Icons.mood,
                        color: Colors.green,
                        size: 20,
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          'Best day: ${weekdayAnalysis.getDayName(weekdayAnalysis.bestDays['Mood'] ?? 1)}',
                          style: AppTextStyles.bodyMedium,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      const Icon(
                        Icons.mood_bad,
                        color: Colors.red,
                        size: 20,
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          'Worst day: ${weekdayAnalysis.getDayName(weekdayAnalysis.worstDays['Mood'] ?? 7)}',
                          style: AppTextStyles.bodyMedium,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.amber.withAlpha(30),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.calendar_today,
                    color: Colors.amber,
                    size: 24,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Day of Week Patterns',
                        style: AppTextStyles.titleMedium,
                      ),
                      Text(
                        'How your mood varies by day',
                        style: AppTextStyles.bodySmall.copyWith(
                          color: AppColors.onSurfaceVariant,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // Empty state
            Text(
              'Not enough data to analyze patterns by day of week. Continue tracking your mood for at least a week to see day-specific patterns.',
              style: AppTextStyles.bodyMedium,
            ),
          ],
        ),
      ),
    );
  }

  WeekdayAnalysis _createWeekdayAnalysis(List<MoodEntry> entries) {
    // Group entries by day of week
    final Map<int, List<double>> moodByWeekday = {};

    // Initialize all days of week
    for (int i = 1; i <= 7; i++) {
      moodByWeekday[i] = [];
    }

    // Process each entry
    for (final entry in entries) {
      final weekday = entry.date.weekday; // 1 = Monday, 7 = Sunday
      // Convert mood to a 0-4 scale (4 = Great, 0 = Bad)
      final moodValue = 4 - entry.mood.index.toDouble();
      moodByWeekday[weekday]!.add(moodValue);
    }

    // Calculate average mood for each day
    final Map<String, List<double>> factorsByWeekday = {};

    for (int i = 1; i <= 7; i++) {
      final dayMoods = moodByWeekday[i] ?? [];
      if (dayMoods.isNotEmpty) {
        factorsByWeekday['Mood-$i'] = dayMoods;
      }
    }

    // Find best and worst days
    int bestDay = 1;
    int worstDay = 1;
    double bestAvg = -1;
    double worstAvg = 5;

    for (int i = 1; i <= 7; i++) {
      final dayMoods = moodByWeekday[i] ?? [];
      if (dayMoods.isNotEmpty) {
        final avg = dayMoods.reduce((a, b) => a + b) / dayMoods.length;

        if (avg > bestAvg) {
          bestAvg = avg;
          bestDay = i;
        }

        if (avg < worstAvg) {
          worstAvg = avg;
          worstDay = i;
        }
      }
    }

    // Create WeekdayAnalysis object
    return WeekdayAnalysis(
      factorsByWeekday: factorsByWeekday,
      bestDays: {'Mood': bestDay},
      worstDays: {'Mood': worstDay},
      description: 'Analysis of how your mood varies by day of the week',
    );
  }
}
