// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// key_insights_card.dart
//
import 'package:flutter/material.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/theme/app_theme.dart';
import 'package:nokken/src/core/ui/widgets/shared_widgets.dart';
import 'package:nokken/src/features/stats/models/stat_analysis.dart';
import 'package:nokken/src/features/stats/utils/stat_utils.dart';

class KeyInsightsCard extends StatelessWidget {
  final ComprehensiveAnalysis analysis;
  final Set<String> expandedCardIds;
  final Function(String) onToggleExpanded;

  const KeyInsightsCard({
    super.key,
    required this.analysis,
    required this.expandedCardIds,
    required this.onToggleExpanded,
  });

  @override
  Widget build(BuildContext context) {
    // Generate key insights based on analysis data
    final insights = <Map<String, dynamic>>[];

    // Add mood trend insight
    if (analysis.moodTrend.strength > 0.3) {
      insights.add({
        'icon': analysis.moodTrend.type == TrendType.increasing
            ? Icons.trending_up
            : analysis.moodTrend.type == TrendType.decreasing
                ? Icons.trending_down
                : Icons.autorenew,
        'color': analysis.moodTrend.type == TrendType.increasing
            ? Colors.green
            : analysis.moodTrend.type == TrendType.decreasing
                ? Colors.red
                : Colors.purple,
        'text': analysis.moodTrend.description,
      });
    }

    // Add top correlation insight
    if (analysis.relationships.isNotEmpty) {
      final topCorrelation = analysis.relationships.first;
      insights.add({
        'icon': Icons.compare_arrows,
        'color': Colors.blue,
        'text': topCorrelation.description,
      });
    }

    // Add pattern insight
    if (analysis.patterns.isNotEmpty) {
      final topPattern = analysis.patterns.first;
      insights.add({
        'icon': StatUtils.getPatternIcon(topPattern.type),
        'color': topPattern.patternColor,
        'text': topPattern.description,
      });
    }

    // Add factor impact insight
    if (analysis.factorRankings.isNotEmpty) {
      final topFactor = analysis.factorRankings.first;
      insights.add({
        'icon': Icons.insights,
        'color': Colors.teal,
        'text': topFactor.description,
      });
    }

    // If we have no insights, add a default one
    if (insights.isEmpty) {
      insights.add({
        'icon': Icons.info_outline,
        'color': AppTheme.grey,
        'text':
            'Continue tracking your health to discover meaningful insights.',
      });
    }

    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Key Insights',
              style: AppTextStyles.titleMedium,
            ),
            SharedWidgets.verticalSpace(16),

            // Display key insights
            ...insights.take(3).map((insight) => Padding(
                  padding: const EdgeInsets.only(bottom: 12.0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: insight['color'].withAlpha(20),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          insight['icon'],
                          color: insight['color'],
                          size: 20,
                        ),
                      ),
                      SharedWidgets.horizontalSpace(12),
                      Expanded(
                        child: Text(
                          insight['text'],
                          style: AppTextStyles.bodyMedium,
                        ),
                      ),
                    ],
                  ),
                )),

            // Show all insights button
            if (insights.length > 3)
              Center(
                child: TextButton.icon(
                  onPressed: () => onToggleExpanded('key-insights'),
                  icon: Icon(
                    expandedCardIds.contains('key-insights')
                        ? Icons.expand_less
                        : Icons.expand_more,
                  ),
                  label: Text(
                    expandedCardIds.contains('key-insights')
                        ? 'Show less'
                        : 'Show more',
                  ),
                  style: TextButton.styleFrom(
                    foregroundColor: AppColors.primary,
                  ),
                ),
              ),

            // Additional insights if expanded
            if (expandedCardIds.contains('key-insights') && insights.length > 3)
              ...insights.skip(3).map((insight) => Padding(
                    padding: const EdgeInsets.only(bottom: 12.0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          padding: const EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: insight['color'].withAlpha(20),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            insight['icon'],
                            color: insight['color'],
                            size: 20,
                          ),
                        ),
                        SharedWidgets.horizontalSpace(12),
                        Expanded(
                          child: Text(
                            insight['text'],
                            style: AppTextStyles.bodyMedium,
                          ),
                        ),
                      ],
                    ),
                  )),
          ],
        ),
      ),
    );
  }
}
