/// Page: Products Page
///
/// Main products browsing page with search, category filters, and product grid.
library;

import 'package:flutter/material.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/services/analytics_service.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/router/app_router.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/cart/presentation/providers/cart_provider.dart';
import 'package:worker/features/products/presentation/providers/product_filters_provider.dart';
import 'package:worker/features/products/presentation/providers/products_provider.dart';
import 'package:worker/features/products/presentation/widgets/brand_filter_chips.dart';
import 'package:worker/features/products/presentation/widgets/product_filter_drawer.dart';
import 'package:worker/features/products/presentation/widgets/product_grid.dart';
import 'package:worker/features/products/presentation/widgets/product_search_bar.dart';
import 'package:worker/generated/l10n/app_localizations.dart';

/// Products Page
///
/// Displays the products catalog with:
/// - Search bar
/// - Category filter chips
/// - Product grid
/// - Pull-to-refresh
/// - Loading and error states
class ProductsPage extends ConsumerWidget {
  const ProductsPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;
    final l10n = AppLocalizations.of(context);
    final productsAsync = ref.watch(productsProvider);

    // Filter options loaded lazily when filter drawer is opened (not here)

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      endDrawer: const ProductFilterDrawer(),
      appBar: AppBar(
        leading: IconButton(
          icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
          onPressed: () {
            if (context.canPop()) {
              context.pop();
            } else {
              context.go(RouteNames.home);
            }
          },
        ),
        title: Text('Sản phẩm', style: TextStyle(color: colorScheme.onSurface)),
        elevation: AppBarSpecs.elevation,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
        actions: [
          // Cart Icon with Badge (extracted to Consumer to prevent full page rebuild)
          Consumer(
            builder: (context, ref, child) {
              final cartItemCount = ref.watch(cartItemCountProvider);
              return IconButton(
                icon: Badge(
                  label: Text('$cartItemCount'),
                  backgroundColor: AppColors.danger,
                  textColor: colorScheme.surface,
                  isLabelVisible: cartItemCount > 0,
                  child: FaIcon(FontAwesomeIcons.cartShopping, color: colorScheme.onSurface, size: 20),
                ),
                onPressed: () => context.push(RouteNames.cart),
              );
            },
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: Builder(
        builder: (BuildContext scaffoldContext) {
          return Column(
            children: [
              // Search Bar with Filter Button
              Padding(
                padding: const EdgeInsets.all(AppSpacing.sm),
                child: Row(
                  children: [
                    // Search Bar (Expanded)
                    const Expanded(child: ProductSearchBar()),
                    const SizedBox(width: 8),
                    // Filter Button
                    Container(
                      height: InputFieldSpecs.height,
                      width: InputFieldSpecs.height,
                      decoration: BoxDecoration(
                        color: colorScheme.surface,
                        borderRadius: BorderRadius.circular(InputFieldSpecs.borderRadius),
                      ),
                      child: IconButton(
                        onPressed: () {
                          // Sync pending filters with applied filters before opening drawer
                          ref.read(productFiltersProvider.notifier).syncWithApplied();
                          // Open filter drawer from right
                          Scaffold.of(scaffoldContext).openEndDrawer();
                        },
                        icon: const FaIcon(FontAwesomeIcons.sliders, size: 18),
                        color: colorScheme.onSurface,
                      ),
                    ),
                  ],
                ),
              ),

              // Brand Filter Chips - only show after products are loaded
              productsAsync.hasValue
                  ? const BrandFilterChips()
                  : const SizedBox(height: 48.0),

              // Products Grid
              Expanded(
                child: productsAsync.when(
                  data: (products) {
                    if (products.isEmpty) {
                      return _buildEmptyState(context, l10n, colorScheme);
                    }

                    final productsNotifier = ref.read(productsProvider.notifier);
                    final hasMore = productsNotifier.hasMore;

                    return ProductGrid(
                      products: products,
                      hasMore: hasMore,
                      isLoadingMore: false,
                      onLoadMore: () async {
                        await productsNotifier.loadMore();
                      },
                      onProductTap: (product) {
                        // Navigate to product detail page
                        context.push('/products/${product.productId}');
                      },
                      onAddToCart: (product) {
                        // Add to cart
                        ref.read(cartProvider.notifier).addToCart(product);

                        AnalyticsService.logAddToCart(
                          productId: product.productId,
                          productName: product.name,
                          price: product.basePrice,
                          quantity: 1,
                          brand: product.itemGroupName,
                        );

                        // Show SnackBar with manual dismissal
                        final messenger = ScaffoldMessenger.of(context)
                        ..clearSnackBars();

                        final controller = messenger.showSnackBar(
                          SnackBar(
                            content: Text('${product.name} đã thêm vào giỏ hàng'),
                            duration: const Duration(days: 365), // Prevent auto-dismiss
                            behavior: SnackBarBehavior.floating,
                            action: SnackBarAction(
                              label: 'Xem',
                              onPressed: () {
                                messenger.hideCurrentSnackBar();
                                context.go(RouteNames.cart);
                              },
                            ),
                          ),
                        );

                        // Manually dismiss after 2 seconds
                        Future.delayed(const Duration(seconds: 2), () {
                          controller.close();
                        });
                      },
                    );
                  },
                  loading: () => _buildLoadingState(colorScheme),
                  error: (error, stack) => _buildErrorState(context, l10n, error, ref, colorScheme),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  /// Build empty state
  Widget _buildEmptyState(BuildContext context, AppLocalizations l10n, ColorScheme colorScheme) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FaIcon(FontAwesomeIcons.boxOpen, size: 80.0, color: colorScheme.onSurfaceVariant.withAlpha(128)),
          const SizedBox(height: AppSpacing.lg),
          Text(
            l10n.noProductsFound,
            style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.w500, color: colorScheme.onSurface),
          ),
          const SizedBox(height: AppSpacing.sm),
          Text(l10n.noResults, style: TextStyle(fontSize: 14.0, color: colorScheme.onSurfaceVariant)),
        ],
      ),
    );
  }

  /// Build loading state
  Widget _buildLoadingState(ColorScheme colorScheme) {
    return const CustomLoadingIndicator();
  }

  /// Build error state
  Widget _buildErrorState(BuildContext context, AppLocalizations l10n, Object error, WidgetRef ref, ColorScheme colorScheme) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(AppSpacing.xl),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FaIcon(FontAwesomeIcons.circleExclamation, size: 80.0, color: AppColors.danger.withAlpha(128)),
            const SizedBox(height: AppSpacing.lg),
            Text(
              l10n.error,
              style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.w600, color: colorScheme.onSurface),
            ),
            const SizedBox(height: AppSpacing.sm),
            Text(
              error.toString(),
              style: TextStyle(fontSize: 14.0, color: colorScheme.onSurfaceVariant),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: AppSpacing.lg),
            ElevatedButton.icon(
              onPressed: () async {
                await ref.read(productsProvider.notifier).refresh();
              },
              icon: const FaIcon(FontAwesomeIcons.arrowsRotate, size: 18),
              label: Text(l10n.tryAgain),
              style: ElevatedButton.styleFrom(
                backgroundColor: colorScheme.primary,
                foregroundColor: colorScheme.onPrimary,
                padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg, vertical: AppSpacing.md),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
