import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../data/learn_content.dart';

class HusbandLearnArticlesScreen extends StatelessWidget {
  const HusbandLearnArticlesScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Learn',
              style: GoogleFonts.outfit(
                fontSize: 28,
                fontWeight: FontWeight.w600,
                color: Theme.of(context).textTheme.displayMedium?.color,
              ),
            ),
            const SizedBox(height: 24),
            _buildSection(context, 'Understanding Her', const [
              _LearnItem(
                icon: Icons.loop,
                title: 'The 4 Phases of Her Cycle',
                subtitle: 'What\'s happening in her body each month',
                articleId: 'four_phases',
              ),
              _LearnItem(
                icon: Icons.psychology_outlined,
                title: 'Why Does Her Mood Change?',
                subtitle: 'Hormones explained simply',
                articleId: 'mood_changes',
              ),
              _LearnItem(
                icon: Icons.medical_information_outlined,
                title: 'PMS is Real',
                subtitle: 'Medical facts for supportive husbands',
                articleId: 'pms_is_real',
              ),
            ]),
            const SizedBox(height: 24),
            _buildSection(context, 'Biblical Manhood', const [
              _LearnItem(
                icon: Icons.favorite,
                title: 'Loving Like Christ',
                subtitle: 'Ephesians 5 in daily practice',
                articleId: 'loving_like_christ',
              ),
              _LearnItem(
                icon: Icons.handshake,
                title: 'Servant Leadership at Home',
                subtitle: 'What it really means',
                articleId: 'servant_leadership',
              ),
              _LearnItem(
                icon: Icons.auto_awesome,
                title: 'Praying for Your Wife',
                subtitle: 'Practical guide',
                articleId: 'praying_for_wife',
              ),
            ]),
            const SizedBox(height: 24),
            _buildSection(context, 'NFP for Husbands', const [
              _LearnItem(
                icon: Icons.show_chart,
                title: 'Reading the Charts Together',
                subtitle: 'Understanding fertility signs',
                articleId: 'reading_charts',
              ),
              _LearnItem(
                icon: Icons.schedule,
                title: 'Abstinence as Spiritual Discipline',
                subtitle: 'Growing together during fertile days',
                articleId: 'abstinence_discipline',
              ),
            ]),
          ],
        ),
      ),
    );
  }

  Widget _buildSection(
      BuildContext context, String title, List<_LearnItem> items) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: GoogleFonts.outfit(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: Theme.of(context).textTheme.bodySmall?.color,
            letterSpacing: 0.5,
          ),
        ),
        const SizedBox(height: 8),
        Container(
          decoration: BoxDecoration(
            color: Theme.of(context).cardTheme.color,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            children: items
                .map((item) => ListTile(
                      leading: Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Theme.of(context)
                              .colorScheme
                              .primary
                              .withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: Icon(
                          item.icon,
                          color: Theme.of(context).colorScheme.primary,
                          size: 20,
                        ),
                      ),
                      title: Text(
                        item.title,
                        style: GoogleFonts.outfit(
                          fontSize: 15,
                          fontWeight: FontWeight.w500,
                          color: Theme.of(context).textTheme.bodyLarge?.color,
                        ),
                      ),
                      subtitle: Text(
                        item.subtitle,
                        style: GoogleFonts.outfit(
                          fontSize: 13,
                          color: Theme.of(context).textTheme.bodyMedium?.color,
                        ),
                      ),
                      trailing: Icon(
                        Icons.chevron_right,
                        color: Theme.of(context).disabledColor,
                      ),
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) =>
                                CombinedLearnArticleDetailScreen(
                                    articleId: item.articleId),
                          ),
                        );
                      },
                    ))
                .toList(),
          ),
        ),
      ],
    );
  }
}

class _LearnItem {
  final IconData icon;
  final String title;
  final String subtitle;
  final String articleId;

  const _LearnItem({
    required this.icon,
    required this.title,
    required this.subtitle,
    required this.articleId,
  });
}

class CombinedLearnArticleDetailScreen extends StatelessWidget {
  final String articleId;

  const CombinedLearnArticleDetailScreen({super.key, required this.articleId});

  @override
  Widget build(BuildContext context) {
    final article = LearnContent.getArticle(articleId);

    if (article == null) {
      return Scaffold(
        appBar: AppBar(title: const Text('Article Not Found')),
        body: const Center(child: Text('Article not found')),
      );
    }

    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: AppBar(
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        elevation: 0,
        leading: IconButton(
          icon:
              Icon(Icons.arrow_back, color: Theme.of(context).iconTheme.color),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(
          article.category,
          style: GoogleFonts.outfit(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: Theme.of(context).textTheme.bodySmall?.color,
          ),
        ),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              article.title,
              style: GoogleFonts.outfit(
                fontSize: 26,
                fontWeight: FontWeight.w700,
                color: Theme.of(context).textTheme.headlineMedium?.color,
                height: 1.2,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              article.subtitle,
              style: GoogleFonts.outfit(
                fontSize: 15,
                color: Theme.of(context).textTheme.bodyMedium?.color,
              ),
            ),
            const SizedBox(height: 24),
            Container(
              height: 3,
              width: 40,
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primary,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(height: 24),
            ...article.sections
                .map((section) => _buildSection(context, section)),
          ],
        ),
      ),
    );
  }

  Widget _buildSection(BuildContext context, LearnSection section) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (section.heading != null) ...[
            Text(
              section.heading!,
              style: GoogleFonts.outfit(
                fontSize: 17,
                fontWeight: FontWeight.w600,
                color: Theme.of(context).textTheme.titleLarge?.color,
              ),
            ),
            const SizedBox(height: 10),
          ],
          _buildRichText(context, section.content),
        ],
      ),
    );
  }

  Widget _buildRichText(BuildContext context, String content) {
    final List<InlineSpan> spans = [];
    final RegExp boldPattern = RegExp(r'\*\*(.*?)\*\*');

    int currentIndex = 0;
    for (final match in boldPattern.allMatches(content)) {
      if (match.start > currentIndex) {
        spans.add(TextSpan(
          text: content.substring(currentIndex, match.start),
          style: GoogleFonts.outfit(
            fontSize: 15,
            color: Theme.of(context).textTheme.bodyLarge?.color,
            height: 1.7,
          ),
        ));
      }
      spans.add(TextSpan(
        text: match.group(1),
        style: GoogleFonts.outfit(
          fontSize: 15,
          fontWeight: FontWeight.w600,
          color: Theme.of(context).textTheme.titleMedium?.color,
          height: 1.7,
        ),
      ));
      currentIndex = match.end;
    }

    if (currentIndex < content.length) {
      spans.add(TextSpan(
        text: content.substring(currentIndex),
        style: GoogleFonts.outfit(
          fontSize: 15,
          color: Theme.of(context).textTheme.bodyLarge?.color,
          height: 1.7,
        ),
      ));
    }

    return RichText(
      text: TextSpan(children: spans),
    );
  }
}
