// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// stats_overview_screen.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/bloodwork_tracker/models/bloodwork.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/providers/statistics_provider.dart';
import 'package:nokken/src/features/stats/screens/emotion_analysis_screen.dart';
import 'package:nokken/src/features/stats/widgets/loading_error_views.dart';
import 'package:nokken/src/features/stats/widgets/empty_state_view.dart';
import 'package:nokken/src/features/stats/screens/totals_screen.dart';
import 'package:nokken/src/features/stats/screens/insights_screen.dart';
import 'package:nokken/src/features/stats/widgets/day_of_week_card.dart';
import 'package:nokken/src/features/stats/widgets/monthly_trends_card.dart';
import 'package:nokken/src/features/stats/widgets/insights_overview_card.dart';
import 'package:nokken/src/features/stats/widgets/analysis_card.dart';
import 'package:nokken/src/core/ui/theme/app_theme.dart';
import 'package:nokken/src/features/medication_tracker/providers/medication_state.dart';
import 'package:nokken/src/features/bloodwork_tracker/providers/bloodwork_state.dart';
import 'package:nokken/src/features/mood_tracker/providers/mood_state.dart';

class StatsOverviewScreen extends ConsumerStatefulWidget {
  final String initialTimeFrame;

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

  @override
  ConsumerState<StatsOverviewScreen> createState() =>
      _StatsOverviewScreenState();
}

class _StatsOverviewScreenState extends ConsumerState<StatsOverviewScreen> {
  late String _selectedTimeFrame;
  final Set<String> _expandedCardIds = {};

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

  void _toggleExpanded(String cardId) {
    setState(() {
      if (_expandedCardIds.contains(cardId)) {
        _expandedCardIds.remove(cardId);
      } else {
        _expandedCardIds.add(cardId);
      }
    });
  }

  void _navigateToFactorAnalysis(String factorName) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => EmotionAnalysisScreen(
          initialTimeFrame: _selectedTimeFrame,
        ),
      ),
    );
  }

  void _navigateToInsightsScreen(ComprehensiveAnalysis analysis) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => InsightsScreen(
          analysis: analysis,
          timeframe: _selectedTimeFrame,
        ),
      ),
    );
  }

  bool _hasNoData(ComprehensiveAnalysis analysis) {
    return analysis.generalInsights.isEmpty &&
        analysis.relationships.isEmpty &&
        analysis.patterns.isEmpty &&
        analysis.factorRankings.isEmpty;
  }

  @override
  Widget build(BuildContext context) {
    // Watch for comprehensive analysis data based on the selected timeframe
    final analysisAsync =
        ref.watch(comprehensiveAnalysisProvider(_selectedTimeFrame));

    return Scaffold(
      appBar: AppBar(
        title: const Text('Health Analytics'),
        elevation: 0,
        actions: [
          TimeframeSelector.dropdownButton(
            context: context,
            selectedTimeframe: _selectedTimeFrame,
            onTimeframeSelected: (value) {
              setState(() {
                _selectedTimeFrame = value;
              });
            },
          ),
        ],
      ),
      body: analysisAsync.when(
        data: (analysis) {
          if (_hasNoData(analysis)) {
            return EmptyStateView.noData();
          }

          return RefreshIndicator(
            onRefresh: () async {
              ref.invalidate(comprehensiveAnalysisProvider(_selectedTimeFrame));
            },
            child: ListView(
              padding: AppTheme.standardCardPadding,
              children: [
                // Health Summary Card
                AnalysisCard(
                  title: 'Health Summary',
                  subtitle: 'Summary of your tracked data',
                  content: _buildTotalsCardContent(analysis),
                  icon: Icons.format_list_numbered,
                  color: Colors.deepPurple,
                  onTap: () => Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => TotalsScreen(
                        analysis: analysis,
                        timeframe: _selectedTimeFrame,
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 16),

                // Insights Overview Card
                InsightsOverviewCard(
                  analysis: analysis,
                  onTap: () => _navigateToInsightsScreen(analysis),
                ),
                const SizedBox(height: 16),

                // Day of Week Patterns Card
                DayOfWeekCard(
                  timeframe: _selectedTimeFrame,
                ),
                const SizedBox(height: 16),

                // Monthly Trends Card
                MonthlyTrendsCard(
                  timeframe: _selectedTimeFrame,
                ),
              ],
            ),
          );
        },
        loading: () => LoadingErrorViews.loading(),
        error: (error, stack) => LoadingErrorViews.error(
          error: error.toString(),
          onRetry: () {
            ref.invalidate(comprehensiveAnalysisProvider(_selectedTimeFrame));
          },
          onGoBack: () => Navigator.of(context).pop(),
        ),
      ),
    );
  }

  Widget _buildTotalsCardContent(ComprehensiveAnalysis analysis) {
    // Get data from providers
    final totalFactors =
        ref.watch(totalHealthFactorsProvider(_selectedTimeFrame));
    final totalRelationships = analysis.relationships.length;
    final totalPatterns = analysis.patterns.length;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Preview grid - 3 cells showing totals
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            _buildTotalStat('Factors', totalFactors.toString(), Colors.blue),
            _buildTotalStat(
                'Relationships', totalRelationships.toString(), Colors.purple),
            _buildTotalStat('Patterns', totalPatterns.toString(), Colors.teal),
          ],
        ),

        const SizedBox(height: 16),

        // Tap to see more
        Center(
          child: Text(
            'Tap to see detailed statistics',
            style: AppTextStyles.bodySmall.copyWith(
              fontStyle: FontStyle.italic,
              color: AppColors.onSurfaceVariant,
            ),
          ),
        ),
      ],
    );
  }

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

// Provider for counting total health factors across different data sources
final totalHealthFactorsProvider =
    Provider.family<int, String>((ref, timeframe) {
  final moodEntries = ref.watch(filteredMoodEntriesProvider(timeframe));
  final medications = ref.watch(medicationsProvider);
  final bloodwork = ref.watch(filteredBloodworkProvider(timeframe));

  // Count unique factors
  final factorSet = <String>{};

  // Count mood factors
  if (moodEntries.isNotEmpty) {
    factorSet.add('Mood');

    // Count health metrics that have data
    if (moodEntries.any((e) => e.sleepQuality != null)) factorSet.add('Sleep');
    if (moodEntries.any((e) => e.energyLevel != null)) factorSet.add('Energy');
    if (moodEntries.any((e) => e.focusLevel != null)) factorSet.add('Focus');
    if (moodEntries.any((e) => e.appetiteLevel != null)) {
      factorSet.add('Appetite');
    }
    if (moodEntries.any((e) => e.dysphoriaLevel != null)) {
      factorSet.add('Dysphoria');
    }
    if (moodEntries.any((e) => e.exerciseLevel != null)) {
      factorSet.add('Exercise');
    }
    if (moodEntries.any((e) => e.libidoLevel != null)) factorSet.add('Libido');

    // Count emotions as factors
    final emotionSet = <String>{};
    for (final entry in moodEntries) {
      for (final emotion in entry.emotions) {
        emotionSet.add(emotion.name);
      }
    }

    // Add each unique emotion as a factor
    factorSet.addAll(emotionSet.map((e) => 'Emotion: $e'));
  }

  // Count medications
  factorSet.addAll(medications.map((m) => 'Medication: ${m.name}'));

  // Count hormones
  for (final record in bloodwork) {
    for (final reading in record.hormoneReadings) {
      factorSet.add('Hormone: ${reading.name}');
    }
  }

  return factorSet.length;
});

// Filter bloodwork records by timeframe
final filteredBloodworkProvider =
    Provider.family<List<Bloodwork>, String>((ref, timeframe) {
  final allBloodwork = ref.watch(bloodworkRecordsProvider);

  if (timeframe == 'All Time') {
    return allBloodwork;
  }

  // Extract start date based on timeframe
  final now = DateTime.now();
  final DateTime startDate;

  switch (timeframe) {
    case 'Last 7 Days':
      startDate = now.subtract(const Duration(days: 7));
      break;
    case 'Last 30 Days':
      startDate = now.subtract(const Duration(days: 30));
      break;
    case 'Last 90 Days':
      startDate = now.subtract(const Duration(days: 90));
      break;
    case 'Last 6 Months':
      startDate = DateTime(now.year, now.month - 6, now.day);
      break;
    case 'Last Year':
      startDate = DateTime(now.year - 1, now.month, now.day);
      break;
    default:
      return allBloodwork;
  }

  // Filter records by date
  return allBloodwork
      .where((record) => record.date.isAfter(startDate))
      .toList();
});
