/// Page: Favorites Page
///
/// Displays all favorited products in a grid layout.
/// Allows users to view and manage their favorite products.
library;

import 'package:flutter/material.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:shimmer/shimmer.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/favorites/presentation/providers/favorites_provider.dart';
import 'package:worker/features/favorites/presentation/widgets/favorite_product_card.dart';
import 'package:worker/features/products/domain/entities/product.dart';

/// Favorites Page
///
/// Shows all products that the user has marked as favorites.
/// Features:
/// - Search bar for filtering favorites
/// - Grid layout of favorite products
/// - Pull-to-refresh
/// - Empty state when no favorites
/// - Error state with retry
/// - Clear all functionality
class FavoritesPage extends HookConsumerWidget {
  const FavoritesPage({super.key});

  /// Show confirmation dialog before clearing all favorites
  Future<void> _showClearAllDialog(
    BuildContext context,
    WidgetRef ref,
    int count,
  ) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Xóa tất cả yêu thích?'),
        content: Text(
          'Bạn có chắc muốn xóa toàn bộ $count sản phẩm khỏi danh sách yêu thích?',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('Hủy'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.danger,
              foregroundColor: AppColors.white,
            ),
            child: const Text('Xóa tất cả'),
          ),
        ],
      ),
    );

    if (confirmed == true && context.mounted) {
      // TODO: Implement clear all functionality
      // For now, we would need to remove each product individually
      // or add a clearAll method to the repository

      // Show snackbar
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Chức năng này đang được phát triển'),
            duration: Duration(seconds: 2),
          ),
        );
      }
    }
  }

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

    // Search controller
    final searchController = useTextEditingController();
    final searchQuery = useState('');

    // Watch favorites and products
    final favoriteProductsAsync = ref.watch(favoriteProductsProvider);
    final favoriteCount = ref.watch(favoriteCountProvider);

    // Track if we've loaded data at least once to prevent empty state flash
    final hasLoadedOnce =
        favoriteProductsAsync.hasValue || favoriteProductsAsync.hasError;

    // Filter products based on search query
    List<Product> filterProducts(List<Product> products) {
      if (searchQuery.value.isEmpty) return products;

      final query = searchQuery.value.toLowerCase().trim();
      return products.where((product) {
        final matchesName = product.name.toLowerCase().contains(query);
        final matchesSku =
            product.erpnextItemCode?.toLowerCase().contains(query) ?? false;
        return matchesName || matchesSku;
      }).toList();
    }

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        leading: IconButton(
          icon: FaIcon(
            FontAwesomeIcons.arrowLeft,
            color: colorScheme.onSurface,
            size: 20,
          ),
          onPressed: () => context.pop(),
        ),
        title: Text('Yêu thích', style: TextStyle(color: colorScheme.onSurface)),
        elevation: AppBarSpecs.elevation,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
        actions: [
          // Count badge
          if (favoriteCount > 0)
            Center(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                child: Text(
                  '($favoriteCount)',
                  style: TextStyle(
                    fontSize: 16.0,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.primary,
                  ),
                ),
              ),
            ),

          // Clear all button
          if (favoriteCount > 0)
            IconButton(
              icon: FaIcon(
                FontAwesomeIcons.trashCan,
                color: colorScheme.onSurface,
                size: 20,
              ),
              tooltip: 'Xóa tất cả',
              onPressed: () => _showClearAllDialog(context, ref, favoriteCount),
            ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: SafeArea(
        child: favoriteProductsAsync.when(
          data: (products) {
            // Filter products based on search
            final filteredProducts = filterProducts(products);

            // IMPORTANT: Only show empty state after we've confirmed data loaded
            // This prevents empty state flash during initial load
            if (products.isEmpty && hasLoadedOnce) {
              return const _EmptyState();
            }

            // If products is empty but we haven't loaded yet, show loading
            if (products.isEmpty && !hasLoadedOnce) {
              return const _LoadingState();
            }

            return Column(
              children: [
                // Search Bar
                Padding(
                  padding: const EdgeInsets.all(AppSpacing.md),
                  child: TextField(
                    controller: searchController,
                    onChanged: (value) => searchQuery.value = value,
                    decoration: InputDecoration(
                      hintText: 'Tìm kiếm sản phẩm...',
                      hintStyle: TextStyle(color: colorScheme.onSurfaceVariant),
                      prefixIcon: Icon(
                        Icons.search,
                        color: colorScheme.onSurfaceVariant,
                      ),
                      suffixIcon: searchQuery.value.isNotEmpty
                          ? IconButton(
                              icon: Icon(
                                Icons.clear,
                                color: colorScheme.onSurfaceVariant,
                              ),
                              onPressed: () {
                                searchController.clear();
                                searchQuery.value = '';
                              },
                            )
                          : null,
                      filled: true,
                      fillColor: colorScheme.surface,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(AppRadius.button),
                        borderSide: BorderSide(color: colorScheme.surfaceContainerHighest),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(AppRadius.button),
                        borderSide: BorderSide(color: colorScheme.surfaceContainerHighest),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(AppRadius.button),
                        borderSide: BorderSide(
                          color: colorScheme.primary,
                          width: 2,
                        ),
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: AppSpacing.md,
                        vertical: AppSpacing.sm,
                      ),
                    ),
                  ),
                ),

                // Results count when searching
                if (searchQuery.value.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: AppSpacing.md,
                    ),
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        'Tìm thấy ${filteredProducts.length} sản phẩm',
                        style: TextStyle(
                          fontSize: 14,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ),
                    ),
                  ),

                // Products Grid
                Expanded(
                  child:
                      filteredProducts.isEmpty && searchQuery.value.isNotEmpty
                      ? Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              FaIcon(
                                FontAwesomeIcons.magnifyingGlass,
                                size: 64,
                                color: colorScheme.onSurfaceVariant,
                              ),
                              const SizedBox(height: AppSpacing.md),
                              Text(
                                'Không tìm thấy "${searchQuery.value}"',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600,
                                  color: colorScheme.onSurface,
                                ),
                              ),
                              const SizedBox(height: AppSpacing.sm),
                              Text(
                                'Thử tìm kiếm với từ khóa khác',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: colorScheme.onSurfaceVariant,
                                ),
                              ),
                            ],
                          ),
                        )
                      : RefreshIndicator(
                          onRefresh: () async {
                            await ref
                                .read(favoriteProductsProvider.notifier)
                                .refresh();
                          },
                          child: _FavoritesGrid(products: filteredProducts),
                        ),
                ),
              ],
            );
          },
          loading: () {
            // IMPORTANT: Check for previous data first to prevent empty state flash
            final previousValue = favoriteProductsAsync.hasValue
                ? favoriteProductsAsync.value
                : null;

            // If we have previous data, show it while loading new data
            if (previousValue != null && previousValue.isNotEmpty) {
              return Stack(
                children: [
                  RefreshIndicator(
                    onRefresh: () async {
                      await ref
                          .read(favoriteProductsProvider.notifier)
                          .refresh();
                    },
                    child: _FavoritesGrid(products: previousValue),
                  ),
                  Positioned(
                    top: 16,
                    left: 0,
                    right: 0,
                    child: Center(
                      child: Card(
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16.0,
                            vertical: 8.0,
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              SizedBox(
                                width: 16,
                                height: 16,
                                child: CustomLoadingIndicator(color: colorScheme.primary, size: 20),
                              ),
                              const SizedBox(width: 8),
                              const Text('Đang tải...'),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }

            // Check if we should show skeleton or empty state
            // Use favoriteCount as a hint - if it's > 0, we likely have data coming
            if (favoriteCount > 0) {
              // Show skeleton loading for better UX
              return const _LoadingState();
            }

            // No previous data and no favorites - show skeleton briefly
            return const _LoadingState();
          },
          error: (error, stackTrace) {
            // Check if we have previous data to show with error
            final previousValue = favoriteProductsAsync.hasValue
                ? favoriteProductsAsync.value
                : null;
            if (previousValue != null && previousValue.isNotEmpty) {
              // Show previous data with error message
              return Stack(
                children: [
                  RefreshIndicator(
                    onRefresh: () async {
                      await ref
                          .read(favoriteProductsProvider.notifier)
                          .refresh();
                    },
                    child: _FavoritesGrid(products: previousValue),
                  ),
                  Positioned(
                    top: 16,
                    left: 16,
                    right: 16,
                    child: Material(
                      color: AppColors.danger,
                      borderRadius: BorderRadius.circular(8),
                      child: Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: Row(
                          children: [
                            const Icon(
                              Icons.error_outline,
                              color: AppColors.white,
                              size: 20,
                            ),
                            const SizedBox(width: 8),
                            const Expanded(
                              child: Text(
                                'Không thể tải dữ liệu mới',
                                style: TextStyle(color: AppColors.white),
                              ),
                            ),
                            TextButton(
                              onPressed: () async {
                                await ref
                                    .read(favoriteProductsProvider.notifier)
                                    .refresh();
                              },
                              child: const Text(
                                'Thử lại',
                                style: TextStyle(
                                  color: AppColors.white,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }
            // No previous data, show full error state
            return _ErrorState(
              error: error,
              onRetry: () async {
                await ref.read(favoriteProductsProvider.notifier).refresh();
              },
            );
          },
        ),
      ),
    );
  }
}

// ============================================================================
// EMPTY STATE
// ============================================================================

/// Empty State Widget
///
/// Displayed when there are no favorite products.
class _EmptyState extends StatelessWidget {
  const _EmptyState();

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

    return Center(
      child: Padding(
        padding: const EdgeInsets.all(AppSpacing.xl),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Large icon
            FaIcon(
              FontAwesomeIcons.heart,
              size: 80.0,
              color: colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
            ),

            const SizedBox(height: AppSpacing.lg),

            // Heading
            Text(
              'Chưa có sản phẩm yêu thích',
              style: TextStyle(
                fontSize: 18.0,
                fontWeight: FontWeight.w600,
                color: colorScheme.onSurface,
              ),
              textAlign: TextAlign.center,
            ),

            const SizedBox(height: AppSpacing.sm),

            // Subtext
            Text(
              'Thêm sản phẩm vào danh sách yêu thích để xem lại sau',
              style: TextStyle(fontSize: 14.0, color: colorScheme.onSurfaceVariant),
              textAlign: TextAlign.center,
            ),

            const SizedBox(height: AppSpacing.xl),

            // Explore Products Button
            ElevatedButton(
              onPressed: () {
                // Navigate to products page
                context.pushReplacement('/products');
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: colorScheme.primary,
                foregroundColor: colorScheme.surface,
                padding: const EdgeInsets.symmetric(
                  horizontal: AppSpacing.xl,
                  vertical: AppSpacing.md,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(AppRadius.button),
                ),
              ),
              child: const Text(
                'Khám phá sản phẩm',
                style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w600),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ============================================================================
// LOADING STATE
// ============================================================================

/// Loading State Widget
///
/// Displayed while favorites are being loaded.
class _LoadingState extends StatelessWidget {
  const _LoadingState();

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      padding: const EdgeInsets.all(AppSpacing.md),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 12.0,
        mainAxisSpacing: 12.0,
        childAspectRatio: 0.62,
      ),
      itemCount: 6, // Show 6 shimmer cards
      itemBuilder: (context, index) => _ShimmerCard(),
    );
  }
}

/// Shimmer Card for Loading State
class _ShimmerCard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Card(
      elevation: ProductCardSpecs.elevation,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(ProductCardSpecs.borderRadius),
      ),
      child: Shimmer.fromColors(
        baseColor: colorScheme.surfaceContainerHighest,
        highlightColor: colorScheme.surfaceContainerLowest,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Image placeholder
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: colorScheme.surfaceContainerHighest,
                  borderRadius: const BorderRadius.vertical(
                    top: Radius.circular(ProductCardSpecs.borderRadius),
                  ),
                ),
              ),
            ),

            // Info placeholder
            Padding(
              padding: const EdgeInsets.all(AppSpacing.sm),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Name placeholder
                  Container(
                    height: 14.0,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: colorScheme.surfaceContainerHighest,
                      borderRadius: BorderRadius.circular(4.0),
                    ),
                  ),

                  const SizedBox(height: 8.0),

                  // SKU placeholder
                  Container(
                    height: 12.0,
                    width: 80.0,
                    decoration: BoxDecoration(
                      color: colorScheme.surfaceContainerHighest,
                      borderRadius: BorderRadius.circular(4.0),
                    ),
                  ),

                  const SizedBox(height: 8.0),

                  // Price placeholder
                  Container(
                    height: 16.0,
                    width: 100.0,
                    decoration: BoxDecoration(
                      color: colorScheme.surfaceContainerHighest,
                      borderRadius: BorderRadius.circular(4.0),
                    ),
                  ),

                  const SizedBox(height: 12.0),

                  // Button placeholder
                  Container(
                    height: 36.0,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: colorScheme.surfaceContainerHighest,
                      borderRadius: BorderRadius.circular(AppRadius.button),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ============================================================================
// ERROR STATE
// ============================================================================

/// Error State Widget
///
/// Displayed when there's an error loading favorites.
class _ErrorState extends StatelessWidget {
  const _ErrorState({required this.error, required this.onRetry});

  final Object error;
  final Future<void> Function() onRetry;

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

    return Center(
      child: Padding(
        padding: const EdgeInsets.all(AppSpacing.xl),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Error icon
            FaIcon(
              FontAwesomeIcons.circleExclamation,
              size: 80.0,
              color: AppColors.danger.withValues(alpha: 0.7),
            ),

            const SizedBox(height: AppSpacing.lg),

            // Title
            Text(
              'Có lỗi xảy ra',
              style: TextStyle(
                fontSize: 18.0,
                fontWeight: FontWeight.w600,
                color: colorScheme.onSurface,
              ),
              textAlign: TextAlign.center,
            ),

            const SizedBox(height: AppSpacing.sm),

            // Error message
            Text(
              error.toString(),
              style: TextStyle(fontSize: 14.0, color: colorScheme.onSurfaceVariant),
              textAlign: TextAlign.center,
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ),

            const SizedBox(height: AppSpacing.xl),

            // Retry Button
            ElevatedButton.icon(
              onPressed: onRetry,
              style: ElevatedButton.styleFrom(
                backgroundColor: colorScheme.primary,
                foregroundColor: colorScheme.surface,
                padding: const EdgeInsets.symmetric(
                  horizontal: AppSpacing.xl,
                  vertical: AppSpacing.md,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(AppRadius.button),
                ),
              ),
              icon: const FaIcon(FontAwesomeIcons.arrowsRotate, size: 18),
              label: const Text(
                'Thử lại',
                style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w600),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ============================================================================
// FAVORITES GRID
// ============================================================================

/// Favorites Grid Widget
///
/// Displays favorite products in a grid layout.
class _FavoritesGrid extends StatelessWidget {
  const _FavoritesGrid({required this.products});

  final List<Product> products;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      padding: const EdgeInsets.all(AppSpacing.md),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: GridSpecs.productGridColumns,
        crossAxisSpacing: 12.0,
        mainAxisSpacing: 12.0,
        childAspectRatio: 0.62, // Same as products page
      ),
      itemCount: products.length,
      itemBuilder: (context, index) {
        final product = products[index];
        return RepaintBoundary(child: FavoriteProductCard(product: product));
      },
    );
  }
}
