/// Page: Product Detail Page
///
/// Full product detail screen with image gallery, specifications, reviews, and purchase options.
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/theme/colors.dart';
import 'package:worker/features/cart/presentation/providers/cart_provider.dart';
import 'package:worker/features/favorites/presentation/providers/favorites_provider.dart';
import 'package:worker/features/products/domain/entities/product.dart';
import 'package:worker/features/products/presentation/providers/products_provider.dart';
import 'package:worker/features/products/presentation/widgets/product_detail/image_gallery_section.dart';
import 'package:worker/features/products/presentation/widgets/product_detail/product_info_section.dart';
import 'package:worker/features/products/presentation/widgets/product_detail/product_tabs_section.dart';
import 'package:worker/features/products/presentation/widgets/product_detail/sticky_action_bar.dart';

/// Product Detail Page
///
/// Displays comprehensive product information including:
/// - Image gallery with 360° view
/// - Product info (SKU, name, price, discount)
/// - Quick info cards (size, warranty, delivery)
/// - Tabbed content (description, specifications, reviews)
/// - Sticky bottom action bar (quantity selector + add to cart)
class ProductDetailPage extends ConsumerStatefulWidget {
  final String productId;

  const ProductDetailPage({super.key, required this.productId});

  @override
  ConsumerState<ProductDetailPage> createState() => _ProductDetailPageState();
}

class _ProductDetailPageState extends ConsumerState<ProductDetailPage> {
  int _quantity = 1;

  void _increaseQuantity() {
    setState(() {
      _quantity++;
    });
  }

  void _decreaseQuantity() {
    if (_quantity > 1) {
      setState(() {
        _quantity--;
      });
    }
  }

  void _updateQuantity(int newQuantity) {
    if (newQuantity >= 1) {
      setState(() {
        _quantity = newQuantity;
      });
    }
  }

  void _toggleFavorite() async {
    // Toggle favorite using favorites provider
    await ref.read(favoriteProductsProvider.notifier).toggleFavorite(widget.productId);

    // Show feedback
    final isFavorite = ref.read(isFavoriteProvider(widget.productId));
    if (mounted) {
      ScaffoldMessenger.of(context).clearSnackBars();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            isFavorite ? 'Đã thêm vào yêu thích' : 'Đã xóa khỏi yêu thích',
          ),
          duration: const Duration(seconds: 1),
        ),
      );
    }
  }

  void _shareProduct(Product product) {
    final colorScheme = Theme.of(context).colorScheme;

    // Show share options
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        decoration: BoxDecoration(
          color: colorScheme.surface,
          borderRadius: const BorderRadius.vertical(
            top: Radius.circular(AppRadius.xl),
          ),
        ),
        padding: const EdgeInsets.all(AppSpacing.lg),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Handle bar
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: colorScheme.outlineVariant,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(height: AppSpacing.lg),

            // Title
            const Text(
              'Chia sẻ sản phẩm',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
            ),
            const SizedBox(height: AppSpacing.lg),

            // Share options
            ListTile(
              leading: FaIcon(FontAwesomeIcons.message, color: colorScheme.primary, size: 20),
              title: const Text('Chia sẻ qua tin nhắn'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).clearSnackBars();
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Đang phát triển tính năng chat'),
                  ),
                );
              },
            ),
            ListTile(
              leading: FaIcon(FontAwesomeIcons.shareNodes, color: colorScheme.primary, size: 20),
              title: const Text('Chia sẻ khác'),
              onTap: () {
                Navigator.pop(context);
                // TODO: Use share plugin
              },
            ),
            ListTile(
              leading: FaIcon(FontAwesomeIcons.copy, color: colorScheme.primary, size: 20),
              title: const Text('Sao chép link'),
              onTap: () {
                Navigator.pop(context);
                // TODO: Copy to clipboard
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Đã sao chép link sản phẩm!')),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  void _addToCart(Product product) async {
    // Add to cart via provider
    await ref.read(cartProvider.notifier).addToCart(
      product,
      quantity: _quantity.toDouble(),
    );

    // Log analytics event
    await AnalyticsService.logAddToCart(
      productId: product.productId,
      productName: product.name,
      price: product.basePrice,
      quantity: _quantity,
      brand: product.itemGroupName,
    );

    if (!mounted) return;

    ScaffoldMessenger.of(context).clearSnackBars();
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          'Đã thêm $_quantity m² ${product.name} vào giỏ hàng!',
        ),
        duration: const Duration(seconds: 2),
        action: SnackBarAction(
          label: 'Xem giỏ hàng',
          onPressed: () {
            context.push('/cart');
          },
        ),
      ),
    );
  }

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

    // Use productDetailProvider with productId parameter
    final productAsync = ref.watch(productDetailProvider(productId: widget.productId));

    // Watch favorite status from favorites provider
    final isFavorite = ref.watch(isFavoriteProvider(widget.productId));

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        leading: IconButton(
          icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Chi tiết sản phẩm',
          style: TextStyle(color: colorScheme.onSurface),
        ),
        elevation: AppBarSpecs.elevation,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
        actions: [
          // Share button
          IconButton(
            icon: FaIcon(FontAwesomeIcons.shareNodes, color: colorScheme.onSurface, size: 20),
            onPressed: () {
              productAsync.whenData((product) {
                _shareProduct(product);
              });
            },
          ),
          // Favorite button
          IconButton(
            icon: Icon(
              isFavorite ? FontAwesomeIcons.solidHeart : FontAwesomeIcons.heart,
              color: isFavorite ? AppColors.danger : colorScheme.onSurface,
            ),
            onPressed: _toggleFavorite,
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: productAsync.when(
        data: (product) {
          // Log view item analytics event
          AnalyticsService.logViewItem(
            productId: product.productId,
            productName: product.name,
            price: product.basePrice,
            brand: product.itemGroupName,
            category: product.itemGroupName,
          );

          return Column(
            children: [
              // Scrollable content
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      // Image Gallery Section
                      ImageGallerySection(product: product),

                      const SizedBox(height: AppSpacing.md),

                      // Product Information Section
                      ProductInfoSection(product: product),

                      const SizedBox(height: AppSpacing.md),

                      // Product Tabs Section
                      ProductTabsSection(product: product),
                    ],
                  ),
                ),
              ),

              // Sticky Action Bar
              StickyActionBar(
                quantity: _quantity,
                unit: 'm²',
                conversionOfSm: product.conversionOfSm,
                uomFromIntroAttributes: product.getIntroAttribute('UOM'),
                onIncrease: _increaseQuantity,
                onDecrease: _decreaseQuantity,
                onQuantityChanged: _updateQuantity,
                onAddToCart: () => _addToCart(product),
              ),
            ],
          );
        },
        loading: () => const CustomLoadingIndicator(),
        error: (error, stack) => Center(
          child: Padding(
            padding: const EdgeInsets.all(AppSpacing.xl),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(
                  FontAwesomeIcons.circleExclamation,
                  size: 80,
                  color: AppColors.danger,
                ),
                const SizedBox(height: AppSpacing.lg),
                const Text(
                  'Không thể tải thông tin sản phẩm',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: AppSpacing.sm),
                Text(
                  error.toString(),
                  style: TextStyle(
                    fontSize: 14,
                    color: colorScheme.onSurfaceVariant,
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: AppSpacing.lg),
                ElevatedButton.icon(
                  onPressed: () {
                    // Invalidate to trigger refetch
                    ref.invalidate(productDetailProvider(productId: widget.productId));
                  },
                  icon: const FaIcon(FontAwesomeIcons.arrowsRotate, size: 18),
                  label: const Text('Thử lại'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: colorScheme.primary,
                    foregroundColor: colorScheme.onPrimary,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
