/// 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/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/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).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) {
    // Show share options
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        decoration: const BoxDecoration(
          color: AppColors.white,
          borderRadius: 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: AppColors.grey100,
                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: const FaIcon(FontAwesomeIcons.message, color: AppColors.primaryBlue, size: 20),
              title: const Text('Chia sẻ qua tin nhắn'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Đang phát triển tính năng chat'),
                  ),
                );
              },
            ),
            ListTile(
              leading: const FaIcon(FontAwesomeIcons.shareNodes, color: AppColors.primaryBlue, size: 20),
              title: const Text('Chia sẻ khác'),
              onTap: () {
                Navigator.pop(context);
                // TODO: Use share plugin
              },
            ),
            ListTile(
              leading: const FaIcon(FontAwesomeIcons.copy, color: AppColors.primaryBlue, 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) {
    // TODO: Add to cart logic
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          'Đã thêm $_quantity ${product.unit} ${product.name} vào giỏ hàng!',
        ),
        duration: const Duration(seconds: 2),
        action: SnackBarAction(
          label: 'Xem giỏ hàng',
          onPressed: () {
            // TODO: Navigate to cart
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 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: const Color(0xFFF4F6F8),
      appBar: AppBar(
        leading: IconButton(
          icon: const FaIcon(FontAwesomeIcons.arrowLeft, color: Colors.black, size: 20),
          onPressed: () => context.pop(),
        ),
        title: const Text(
          'Chi tiết sản phẩm',
          style: TextStyle(color: Colors.black),
        ),
        elevation: AppBarSpecs.elevation,
        backgroundColor: AppColors.white,
        foregroundColor: AppColors.grey900,
        centerTitle: false,
        actions: [
          // Share button
          IconButton(
            icon: const FaIcon(FontAwesomeIcons.shareNodes, color: Colors.black, size: 20),
            onPressed: () {
              productAsync.whenData((product) {
                _shareProduct(product);
              });
            },
          ),
          // Favorite button
          IconButton(
            icon: Icon(
              isFavorite ? FontAwesomeIcons.solidHeart : FontAwesomeIcons.heart,
              color: isFavorite ? AppColors.danger : Colors.black,
            ),
            onPressed: _toggleFavorite,
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: productAsync.when(
        data: (product) {
          return Stack(
            children: [
              // Scrollable content
              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),

                    // Bottom padding for sticky action bar
                    const SizedBox(height: 88.0),
                  ],
                ),
              ),

              // Sticky Action Bar
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: StickyActionBar(
                  quantity: _quantity,
                  unit: product.unit ?? 'm²',
                  conversionOfSm: product.conversionOfSm,
                  uomFromIntroAttributes: product.getIntroAttribute('UOM'),
                  onIncrease: _increaseQuantity,
                  onDecrease: _decreaseQuantity,
                  onQuantityChanged: _updateQuantity,
                  onAddToCart: () => _addToCart(product),
                ),
              ),
            ],
          );
        },
        loading: () => const Center(
          child: CircularProgressIndicator(color: AppColors.primaryBlue),
        ),
        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: const TextStyle(
                    fontSize: 14,
                    color: AppColors.grey500,
                  ),
                  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: AppColors.primaryBlue,
                    foregroundColor: AppColors.white,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
