/// News List Page
///
/// Displays all news articles with category filtering and featured section.
/// Matches HTML design at html/news-list.html
library;

import 'package:flutter/material.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/news/domain/entities/news_article.dart';
import 'package:worker/features/news/presentation/providers/news_provider.dart';
import 'package:worker/features/news/presentation/widgets/category_filter_chips.dart';
import 'package:worker/features/news/presentation/widgets/featured_news_card.dart';
import 'package:worker/features/news/presentation/widgets/news_card.dart';

/// News List Page
///
/// Features:
/// - Standard AppBar with title "Tin tức & chuyên môn"
/// - Horizontal scrollable category chips (dynamic from Frappe API)
/// - Featured article section (large card)
/// - "Mới nhất" section with news cards list
/// - RefreshIndicator for pull-to-refresh
/// - Loading and error states
class NewsListPage extends ConsumerStatefulWidget {
  const NewsListPage({super.key});

  @override
  ConsumerState<NewsListPage> createState() => _NewsListPageState();
}

class _NewsListPageState extends ConsumerState<NewsListPage> {
  /// Currently selected category name (null = All)
  String? selectedCategoryName;

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    // Watch providers
    final featuredArticleAsync = ref.watch(featuredArticleProvider);
    final newsArticlesAsync = ref.watch(newsArticlesProvider);

    // Filter articles by selected category
    final filteredArticles = newsArticlesAsync.whenData((articles) {
      if (selectedCategoryName == null) {
        return articles;
      }
      // TODO: Filter by category when articles have category field
      return articles;
    });

    return Scaffold(
      backgroundColor: colorScheme.surface,
      appBar: _buildAppBar(context),
      body: RefreshIndicator(
        onRefresh: () async {
          // Invalidate providers to trigger refresh
          ref
            ..invalidate(newsArticlesProvider)
            ..invalidate(featuredArticleProvider)
            ..invalidate(blogCategoriesProvider);
        },
        child: CustomScrollView(
          slivers: [
            // Category Filter Chips
            SliverToBoxAdapter(
              child: Padding(
                padding: const EdgeInsets.only(top: 4, bottom: AppSpacing.md),
                child: CategoryFilterChips(
                  selectedCategoryName: selectedCategoryName,
                  onCategorySelected: (categoryName) {
                    setState(() {
                      selectedCategoryName = categoryName;
                    });
                  },
                ),
              ),
            ),

            // Featured Article Section
            featuredArticleAsync.when(
              data: (article) {
                if (article == null) {
                  return const SliverToBoxAdapter(child: SizedBox.shrink());
                }

                return SliverToBoxAdapter(
                  child:  FeaturedNewsCard(
                    article: article,
                    onTap: () => _onArticleTap(context, article),
                  ),
                );
              },
              loading: () => const SliverToBoxAdapter(
                child: Padding(
                  padding: EdgeInsets.all(AppSpacing.md),
                  child: const CustomLoadingIndicator(),
                ),
              ),
              error: (error, stack) =>
                  const SliverToBoxAdapter(child: SizedBox.shrink()),
            ),

            const SliverToBoxAdapter(
              child: SizedBox(height: AppSpacing.xl),
            ),
            // Latest News Section
            SliverToBoxAdapter(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
                child: Row(
                  children: [
                    FaIcon(
                      FontAwesomeIcons.newspaper,
                      size: 16,
                      color: Theme.of(context).colorScheme.primary,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      'Mới nhất',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w600,
                        color: Theme.of(context).colorScheme.onSurface,
                      ),
                    ),
                  ],
                ),
              ),
            ),

            const SliverToBoxAdapter(child: SizedBox(height: AppSpacing.md)),

            // News List
            filteredArticles.when(
              data: (articles) {
                if (articles.isEmpty) {
                  return SliverFillRemaining(child: _buildEmptyState());
                }

                return SliverPadding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: AppSpacing.md,
                  ),
                  sliver: SliverList(
                    delegate: SliverChildBuilderDelegate((context, index) {
                      final article = articles[index];
                      return NewsCard(
                        article: article,
                        onTap: () => _onArticleTap(context, article),
                      );
                    }, childCount: articles.length),
                  ),
                );
              },
              loading: () => const SliverFillRemaining(
                child: const CustomLoadingIndicator(),
              ),
              error: (error, stack) => SliverFillRemaining(
                child: _buildErrorState(error.toString()),
              ),
            ),

            // Bottom padding
            const SliverToBoxAdapter(child: SizedBox(height: AppSpacing.md)),
          ],
        ),
      ),
    );
  }

  /// Build standard AppBar
  PreferredSizeWidget _buildAppBar(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return AppBar(
      backgroundColor: colorScheme.surface,
      elevation: AppBarSpecs.elevation,
      title: Text(
        'Tin tức & chuyên môn',
        style: TextStyle(
          color: colorScheme.onSurface,
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
      centerTitle: false,
      actions: const [SizedBox(width: AppSpacing.sm)],
    );
  }

  /// Build empty state
  Widget _buildEmptyState() {
    final colorScheme = Theme.of(context).colorScheme;

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FaIcon(FontAwesomeIcons.newspaper, size: 64, color: colorScheme.onSurfaceVariant),
          const SizedBox(height: 16),
          Text(
            'Chưa có tin tức',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            'Hãy quay lại sau để xem các bài viết mới',
            style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  /// Build error state
  Widget _buildErrorState(String error) {
    final colorScheme = Theme.of(context).colorScheme;

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Keep AppColors.danger for error state - semantic status color
          FaIcon(FontAwesomeIcons.circleExclamation, size: 64, color: AppColors.danger),
          const SizedBox(height: 16),
          Text(
            'Không thể tải tin tức',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: 8),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32),
            child: Text(
              error,
              style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
    );
  }

  /// Handle article tap
  void _onArticleTap(BuildContext context, NewsArticle article) {
    // Navigate to article detail page
    context.push('/news/${article.id}');
  }
}
