/// Widget: Favorite Product Card
///
/// Displays a favorited product in a card format with image, name, price,
/// and favorite toggle button.
library;

import 'package:cached_network_image/cached_network_image.dart';
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:intl/intl.dart';
import 'package:shimmer/shimmer.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart'; // Keep for AppColors.danger and AppColors.white
import 'package:worker/features/favorites/presentation/providers/favorites_provider.dart';
import 'package:worker/features/products/domain/entities/product.dart';

/// Favorite Product Card Widget
///
/// Displays product information in a card format with a favorite toggle button.
/// Used in the favorites grid view.
class FavoriteProductCard extends ConsumerWidget {

  const FavoriteProductCard({super.key, required this.product});
  final Product product;

  String _formatPrice(double price) {
    final formatter = NumberFormat('#,###', 'vi_VN');
    return '${formatter.format(price)}đ';
  }

  /// Show confirmation dialog before removing from favorites
  Future<void> _showRemoveDialog(BuildContext context, WidgetRef ref) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Xóa khỏi yêu thích?'),
        content: const Text(
          'Bạn có chắc muốn xóa sản phẩm này 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'),
          ),
        ],
      ),
    );

    if (confirmed == true && context.mounted) {
      // Remove from favorites
      await ref
          .read(favoriteProductsProvider.notifier)
          .removeFavorite(product.productId);

      // Show snackbar
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Đã xóa khỏi yêu thích'),
            duration: Duration(seconds: 2),
          ),
        );
      }
    }
  }

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

    return Card(
      elevation: ProductCardSpecs.elevation,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(ProductCardSpecs.borderRadius),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Product Image with Favorite Button
          Expanded(
            child: Stack(
              children: [
                // Image
                ClipRRect(
                  borderRadius: const BorderRadius.vertical(
                    top: Radius.circular(ProductCardSpecs.borderRadius),
                  ),
                  child: CachedNetworkImage(
                    imageUrl: product.thumbnail,
                    width: double.infinity,
                    height: double.infinity,
                    fit: BoxFit.cover,
                    memCacheWidth: ImageSpecs.productImageCacheWidth,
                    memCacheHeight: ImageSpecs.productImageCacheHeight,
                    placeholder: (context, url) => Shimmer.fromColors(
                      baseColor: colorScheme.surfaceContainerHighest,
                      highlightColor: colorScheme.surfaceContainerLowest,
                      child: Container(color: colorScheme.surfaceContainerHighest),
                    ),
                    errorWidget: (context, url, error) => Container(
                      color: colorScheme.surfaceContainerHighest,
                      child: FaIcon(
                        FontAwesomeIcons.image,
                        size: 48.0,
                        color: colorScheme.onSurfaceVariant,
                      ),
                    ),
                  ),
                ),

                // Favorite Button (top-right)
                Positioned(
                  top: AppSpacing.sm,
                  right: AppSpacing.sm,
                  child: Container(
                    decoration: BoxDecoration(
                      color: colorScheme.surface,
                      shape: BoxShape.circle,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withValues(alpha: 0.15),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: IconButton(
                      icon: const FaIcon(
                        FontAwesomeIcons.solidHeart,
                        color: AppColors.danger,
                        size: 18.0,
                      ),
                      padding: const EdgeInsets.all(AppSpacing.sm),
                      constraints: const BoxConstraints(
                        minWidth: 36,
                        minHeight: 36,
                      ),
                      onPressed: () => _showRemoveDialog(context, ref),
                    ),
                  ),
                ),
              ],
            ),
          ),

          // Product Info
          Padding(
            padding: const EdgeInsets.all(AppSpacing.sm),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                // Product Name
                Text(
                  product.name,
                  style: const TextStyle(
                    fontSize: 14.0,
                    fontWeight: FontWeight.w600,
                    height: 1.3,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),

                const SizedBox(height: AppSpacing.xs),

                // SKU (if available)
                if (product.erpnextItemCode != null)
                  Text(
                    'Mã: ${product.erpnextItemCode}',
                    style: TextStyle(
                      fontSize: 12.0,
                      color: colorScheme.onSurfaceVariant,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),

                const SizedBox(height: AppSpacing.xs),

                // Price
                Text(
                  _formatPrice(product.effectivePrice),
                  style: TextStyle(
                    fontSize: 16.0,
                    fontWeight: FontWeight.bold,
                    color: colorScheme.primary,
                  ),
                ),

                const SizedBox(height: AppSpacing.sm),

                // View Details Button
                SizedBox(
                  width: double.infinity,
                  height: 36.0,
                  child: OutlinedButton(
                    onPressed: () {
                      // Navigate to product detail
                      context.push('/products/${product.productId}');
                    },
                    style: OutlinedButton.styleFrom(
                      foregroundColor: colorScheme.primary,
                      side: BorderSide(
                        color: colorScheme.primary,
                        width: 1.5,
                      ),
                      elevation: 0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(AppRadius.button),
                      ),
                      padding: const EdgeInsets.symmetric(
                        horizontal: AppSpacing.sm,
                      ),
                    ),
                    child: const Text(
                      'Xem chi tiết',
                      style: TextStyle(
                        fontSize: 12.0,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
