/// Widget: Product Card
///
/// Displays a product in a card format with image, name, price, and add to cart 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:intl/intl.dart';
import 'package:shimmer/shimmer.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/products/domain/entities/product.dart';
import 'package:worker/generated/l10n/app_localizations.dart';

/// Product Card Widget
///
/// Displays product information in a card format.
/// Includes image, name, price, stock status, favorite toggle, and add to cart button.
class ProductCard extends ConsumerWidget {
  const ProductCard({
    super.key,
    required this.product,
    this.onTap,
    this.onAddToCart,
  });

  final Product product;
  final VoidCallback? onTap;
  final VoidCallback? onAddToCart;

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

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

    return Card(
      elevation: ProductCardSpecs.elevation,
      margin: const EdgeInsets.all(8),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(ProductCardSpecs.borderRadius),
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(ProductCardSpecs.borderRadius),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Product Image
            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: Icon(
                          FontAwesomeIcons.image,
                          size: 48.0,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ),
                    ),
                  ),

                  // Sale Badge
                  if (product.isOnSale)
                    Positioned(
                      top: AppSpacing.sm,
                      right: AppSpacing.sm,
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: AppSpacing.sm,
                          vertical: 4.0,
                        ),
                        decoration: BoxDecoration(
                          color: AppColors.danger,
                          borderRadius: BorderRadius.circular(AppRadius.sm),
                        ),
                        child: Text(
                          '-${product.discountPercentage}%',
                          style: const TextStyle(
                            color: AppColors.white,
                            fontSize: 11.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),

                  // Low Stock Badge
                  if (product.isLowStock)
                    Positioned(
                      top: AppSpacing.sm,
                      left: AppSpacing.sm,
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: AppSpacing.sm,
                          vertical: 4.0,
                        ),
                        decoration: BoxDecoration(
                          color: AppColors.warning,
                          borderRadius: BorderRadius.circular(AppRadius.sm),
                        ),
                        child: Text(
                          l10n.lowStock,
                          style: const TextStyle(
                            color: AppColors.white,
                            fontSize: 11.0,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),

                  // Favorite Button (bottom-left corner)
                  // Positioned(
                  //   bottom: AppSpacing.sm,
                  //   left: AppSpacing.sm,
                  //   child: Material(
                  //     color: Colors.transparent,
                  //     child: InkWell(
                  //       onTap: () async {
                  //         // Capture current state before toggle
                  //         final wasfavorited = isFavorited;
                  //
                  //         // Toggle favorite
                  //         await ref
                  //             .read(favoritesProvider.notifier)
                  //             .toggleFavorite(product.productId);
                  //
                  //         // Show feedback with correct message
                  //         if (context.mounted) {
                  //           ScaffoldMessenger.of(context).showSnackBar(
                  //             SnackBar(
                  //               content: Text(
                  //                 wasfavorited
                  //                     ? 'Đã xóa khỏi yêu thích'
                  //                     : 'Đã thêm vào yêu thích',
                  //               ),
                  //               duration: const Duration(seconds: 1),
                  //               behavior: SnackBarBehavior.floating,
                  //             ),
                  //           );
                  //         }
                  //       },
                  //       borderRadius: BorderRadius.circular(20),
                  //       child: Container(
                  //         width: 36,
                  //         height: 36,
                  //         decoration: BoxDecoration(
                  //           color: colorScheme.surface,
                  //           shape: BoxShape.circle,
                  //           boxShadow: [
                  //             BoxShadow(
                  //               color: Colors.black.withValues(alpha: 0.15),
                  //               blurRadius: 6,
                  //               offset: const Offset(0, 2),
                  //             ),
                  //           ],
                  //         ),
                  //         child: Icon(
                  //           isFavorited
                  //               ? Icons.favorite
                  //               : Icons.favorite_border,
                  //           color: isFavorited
                  //               ? AppColors.danger
                  //               : colorScheme.onSurfaceVariant,
                  //           size: 20,
                  //         ),
                  //       ),
                  //     ),
                  //   ),
                  // ),
                ],
              ),
            ),

            // 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),

                  // Price
                  Text(
                    '${_formatPrice(product.effectivePrice)}/m²',
                    style: TextStyle(
                      fontSize: 16.0,
                      fontWeight: FontWeight.bold,
                      color: colorScheme.primary,
                    ),
                  ),

                  const SizedBox(height: AppSpacing.sm),

                  // Action Buttons
                  Column(
                    spacing: 8.0,
                    children: [
                      // Add to Cart Button
                      SizedBox(
                        width: double.infinity,
                        height: 36.0,
                        child: ElevatedButton.icon(
                          onPressed: onAddToCart,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: colorScheme.primary,
                            foregroundColor: colorScheme.onPrimary,
                            elevation: 0,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(
                                AppRadius.button,
                              ),
                            ),
                            padding: const EdgeInsets.symmetric(
                              horizontal: AppSpacing.sm,
                            ),
                          ),
                          icon: const FaIcon(FontAwesomeIcons.cartShopping, size: 14.0),
                          label:  Text(
                            'Thêm vào giỏ',
                            style: TextStyle(
                              fontSize: 12.0,
                              fontWeight: FontWeight.w600,
                              color: colorScheme.surface
                            ),
                          ),
                        ),
                      ),

                      // 360° View Button (if available)
                      if (product.has360View)
                        SizedBox(
                          width: double.infinity,
                          height: 36.0,
                          child: OutlinedButton.icon(
                            onPressed: () async {
                              final url = Uri.parse(product.customLink360!);
                              if (await canLaunchUrl(url)) {
                                await launchUrl(
                                  url,
                                  mode: LaunchMode.inAppWebView,
                                );
                              }
                            },
                            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,
                              ),
                            ),
                            icon: const FaIcon(FontAwesomeIcons.cube, size: 14.0),
                            label:  Text(
                              'Phối cảnh 360°',
                              style: TextStyle(
                                fontSize: 12.0,
                                fontWeight: FontWeight.w600,
                                color: colorScheme.onSurface
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
