/// Widget: Sticky Action Bar
///
/// Fixed bottom action bar with quantity controls and add to cart button.
library;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:worker/core/constants/ui_constants.dart';

/// Sticky Action Bar
///
/// Fixed at the bottom of the screen with:
/// - Quantity section with label, controls, and conversion text
/// - Add to cart button
class StickyActionBar extends StatelessWidget {

  const StickyActionBar({
    super.key,
    required this.quantity,
    required this.onIncrease,
    required this.onDecrease,
    required this.onQuantityChanged,
    required this.onAddToCart,
    this.unit = 'm²',
    this.conversionOfSm,
    this.uomFromIntroAttributes,
  });
  final int quantity;
  final VoidCallback onIncrease;
  final VoidCallback onDecrease;
  final ValueChanged<int> onQuantityChanged;
  final VoidCallback onAddToCart;
  final String unit;
  final double? conversionOfSm;
  final String? uomFromIntroAttributes;

  String _getConversionText() {
    if (conversionOfSm == null || conversionOfSm == 0) {
      return ''; // No conversion data available
    }

    // Calculate boxes needed using API conversion factor
    // Formula: boxes_needed = quantity_m² / conversion_of_sm
    final boxesNeeded = (quantity / conversionOfSm!).ceil();

    // Extract pieces per box from UOM if available (e.g., "2 viên/hộp" -> 2)
    int piecesPerBox = 1;
    if (uomFromIntroAttributes != null) {
      final match = RegExp(r'(\d+)\s*viên').firstMatch(uomFromIntroAttributes!);
      if (match != null) {
        piecesPerBox = int.tryParse(match.group(1) ?? '1') ?? 1;
      }
    }

    final totalPieces = boxesNeeded * piecesPerBox;

    return 'Tương đương: $boxesNeeded hộp / $totalPieces viên';
  }

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

    return Container(
      decoration: BoxDecoration(
        color: colorScheme.surface,
        border: Border(
          top: BorderSide(color: colorScheme.outlineVariant, width: 1),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha(26), // 0.1 opacity
            offset: const Offset(0, -4),
            blurRadius: 15,
          ),
        ],
      ),
      padding: const EdgeInsets.all(16),
      child: SafeArea(
        top: false,
        child: Row(
          children: [
            // Quantity Section
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                // Label
                Text(
                  'Số lượng ($unit)',
                  style: TextStyle(
                    fontSize: 12,
                    color: colorScheme.onSurfaceVariant,
                    fontWeight: FontWeight.w500,
                  ),
                ),

                const SizedBox(height: 8),

                // Quantity Controls
                Container(
                  width: 142,
                  decoration: BoxDecoration(
                    border: Border.all(color: colorScheme.outlineVariant),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    children: [
                      // Decrease Button
                      _QuantityButton(
                        icon: FontAwesomeIcons.minus,
                        onPressed: quantity > 1 ? onDecrease : null,
                      ),

                      // Quantity Input
                      Expanded(
                        child: TextField(
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            FilteringTextInputFormatter.digitsOnly,
                          ],
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                          ),
                          controller: TextEditingController(
                            text: quantity.toString(),
                          ),
                          onChanged: (value) {
                            final newQuantity = int.tryParse(value);
                            if (newQuantity != null && newQuantity >= 1) {
                              onQuantityChanged(newQuantity);
                            }
                          },
                        ),
                      ),

                      // Increase Button
                      _QuantityButton(icon: FontAwesomeIcons.plus, onPressed: onIncrease),
                    ],
                  ),
                ),

                const SizedBox(height: 4),

                // Conversion Text
                if (_getConversionText().isNotEmpty)
                  Text(
                    _getConversionText(),
                    style: TextStyle(
                      fontSize: 11,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
              ],
            ),

            const SizedBox(width: 8),

            // Add to Cart Button
            Expanded(
              child: ElevatedButton.icon(
                onPressed: onAddToCart,
                style: ElevatedButton.styleFrom(
                  backgroundColor: colorScheme.primary,
                  foregroundColor: colorScheme.onPrimary,
                  elevation: 0,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 8,
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                icon: const FaIcon(FontAwesomeIcons.cartShopping, size: 18),
                label:  Text(
                  'Thêm vào giỏ hàng',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// Quantity Button Widget
class _QuantityButton extends StatelessWidget {

  const _QuantityButton({required this.icon, this.onPressed});
  final IconData icon;
  final VoidCallback? onPressed;

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

    return SizedBox(
      width: 40,
      height: 40,
      child: Material(
        color: colorScheme.surfaceContainerHighest,
        child: InkWell(
          onTap: onPressed,
          child: Icon(
            icon,
            size: 20,
            color: onPressed != null ? colorScheme.onSurface : colorScheme.onSurfaceVariant,
          ),
        ),
      ),
    );
  }
}
