import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

import '../../../../core/di/providers.dart';
import '../../../../core/services/sunmi_service.dart';
import '../../../../core/storage/secure_storage.dart';
import '../../../../core/utils/text_utils.dart';
import '../../../users/domain/entities/user_entity.dart';
import '../../data/models/create_product_warehouse_request.dart';
import '../../domain/entities/product_stage_entity.dart';

/// Product detail page
/// Displays product stages as chips and shows selected stage information
/// If [stageId] is provided, only that stage is shown, otherwise all stages are shown
class ProductDetailPage extends ConsumerStatefulWidget {
  final int warehouseId;
  final int productId;
  final String warehouseName;
  final int? stageId;
  final String operationType;

  const ProductDetailPage({
    super.key,
    required this.warehouseId,
    required this.productId,
    required this.warehouseName,
    this.stageId,
    this.operationType = 'import',
  });

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

class _ProductDetailPageState extends ConsumerState<ProductDetailPage> {
  late String _providerKey;

  // Text editing controllers for quantity fields
  final TextEditingController _passedQuantityController = TextEditingController();
  final TextEditingController _passedWeightController = TextEditingController();
  final TextEditingController _issuedQuantityController = TextEditingController();
  final TextEditingController _issuedWeightController = TextEditingController();

  // Selected users for dropdowns
  UserEntity? _selectedWarehouseUser;
  UserEntity? _selectedEmployee;

  @override
  void initState() {
    super.initState();
    _providerKey = '${widget.warehouseId}_${widget.productId}';

    // Load product stages and users when page is initialized
    Future.microtask(() async {
      // Load users from Hive (no API call)
      await ref.read(usersProvider.notifier).getUsers();

      // Auto-select warehouse user based on stored email
      await _autoSelectWarehouseUser();

      await ref.read(productDetailProvider(_providerKey).notifier).loadProductDetail(
            widget.warehouseId,
            widget.productId,
          );

      // If stageId is provided, auto-select that stage
      if (widget.stageId != null) {
        final stages = ref.read(productDetailProvider(_providerKey)).stages;
        final stageIndex = stages.indexWhere(
          (stage) => stage.productStageId == widget.stageId,
        );
        if (stageIndex != -1) {
          ref.read(productDetailProvider(_providerKey).notifier).selectStage(stageIndex);
        }
      }
    });
  }

  @override
  void dispose() {
    _passedQuantityController.dispose();
    _passedWeightController.dispose();
    _issuedQuantityController.dispose();
    _issuedWeightController.dispose();
    super.dispose();
  }

  /// Auto-select warehouse user based on stored user ID from login
  Future<void> _autoSelectWarehouseUser() async {
    try {
      // Get stored current user ID from secure storage
      final secureStorage = SecureStorage();
      final currentUserId = await secureStorage.getCurrentUserId();

      if (currentUserId == null) {
        return;
      }

      // Get all warehouse users
      final warehouseUsers = ref.read(usersListProvider)
          .where((user) => user.isWareHouseUser)
          .toList();

      // Find user with matching ID
      final matchingUsers = warehouseUsers
          .where((user) => user.id == currentUserId)
          .toList();

      final matchingUser = matchingUsers.isNotEmpty ? matchingUsers.first : null;

      // Set selected warehouse user only if a match is found
      if (matchingUser != null && mounted) {
        setState(() {
          _selectedWarehouseUser = matchingUser;
        });
      }
    } catch (e) {
      // Silently fail - user can still manually select
      debugPrint('Error auto-selecting warehouse user: $e');
    }
  }

  Future<void> _onRefresh() async {
    // await ref.read(productDetailProvider(_providerKey).notifier).refreshProductDetail(
    //       widget.warehouseId,
    //       widget.productId,
    //     );
  }

  void _clearControllers() {
    _passedQuantityController.clear();
    _passedWeightController.clear();
    _issuedQuantityController.clear();
    _issuedWeightController.clear();
    setState(() {
      _selectedWarehouseUser = null;
      _selectedEmployee = null;
    });
  }

  void _clearUserSelections() {
    setState(() {
      _selectedWarehouseUser = null;
      _selectedEmployee = null;
    });
  }

  void _showBarcodeScanner() {
    final controller = MobileScannerController(
      formats: const [BarcodeFormat.code128],
      facing: CameraFacing.back,
    );

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.7,
        decoration: const BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        child: Column(
          children: [
            // Header
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey.shade900,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(20),
                ),
              ),
              child: Row(
                children: [
                  const Icon(
                    Icons.qr_code_scanner,
                    color: Colors.white,
                  ),
                  const SizedBox(width: 12),
                  const Expanded(
                    child: Text(
                      'Quét mã vạch',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close, color: Colors.white),
                    onPressed: () {
                      controller.dispose();
                      Navigator.pop(context);
                    },
                  ),
                ],
              ),
            ),
            // Scanner
            Expanded(
              child: MobileScanner(
                controller: controller,
                onDetect: (capture) {
                  final List<Barcode> barcodes = capture.barcodes;
                  if (barcodes.isNotEmpty) {
                    final barcode = barcodes.first.rawValue;
                    if (barcode != null) {
                      controller.dispose();
                      Navigator.pop(context);
                      _handleScannedBarcode(barcode);
                    }
                  }
                },
              ),
            ),
            // Instructions
            Container(
              padding: const EdgeInsets.all(16),
              color: Colors.grey.shade900,
              child: const Text(
                'Đặt mã vạch Code 128 vào khung để quét',
                style: TextStyle(
                  color: Colors.white70,
                  fontSize: 14,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    ).whenComplete(() => controller.dispose());
  }

  Future<void> _handleScannedBarcode(String barcode) async {
    // Parse barcode to extract productId and optional stageId
    // Format 1: "123" (only productId)
    // Format 2: "123-456" (productId-stageId)

    int? productId;
    int? stageId;

    if (barcode.contains('-')) {
      // Format: productId-stageId
      final parts = barcode.split('-');
      if (parts.length == 2) {
        productId = int.tryParse(parts[0]);
        stageId = int.tryParse(parts[1]);
      }
    } else {
      // Format: productId only
      productId = int.tryParse(barcode);
    }

    if (productId == null) {
      // Invalid barcode format
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Định dạng mã vạch không hợp lệ: "$barcode"'),
          backgroundColor: Colors.red,
          action: SnackBarAction(
            label: 'OK',
            textColor: Colors.white,
            onPressed: () {},
          ),
        ),
      );
      return;
    }

    // Show loading indicator
    if (!mounted) return;
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );

    try {
      // Update the provider key and load product detail
      setState(() {
        _providerKey = '${widget.warehouseId}_$productId';
      });

      // Clear current selections
      _clearControllers();

      // Load product detail data from API
      await ref.read(productDetailProvider(_providerKey).notifier).loadProductDetail(
            widget.warehouseId,
            productId,
          );

      // Dismiss loading dialog
      if (mounted) Navigator.of(context).pop();

      // If stageId is provided, auto-select that stage
      if (stageId != null && mounted) {
        final stages = ref.read(productDetailProvider(_providerKey)).stages;
        final stageIndex = stages.indexWhere(
          (stage) => stage.productStageId == stageId,
        );
        if (stageIndex != -1) {
          ref.read(productDetailProvider(_providerKey).notifier).selectStage(stageIndex);
        }
      }

      // Show success message
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Đã tải sản phẩm ID: $productId'),
            backgroundColor: Colors.green,
            duration: const Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      // Dismiss loading dialog
      if (mounted) Navigator.of(context).pop();

      // Show error message
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Lỗi khi tải sản phẩm: ${e.toString()}'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }
  }

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

    // Watch the product detail state
    final productDetailState = ref.watch(productDetailProvider(_providerKey));
    final stages = productDetailState.stages;
    final selectedStage = productDetailState.selectedStage;
    final isLoading = productDetailState.isLoading;
    final error = productDetailState.error;
    final selectedIndex = productDetailState.selectedStageIndex;

    // Get product name from stages if available
    final productName = stages.isNotEmpty ? stages.first.productName : 'Product';

    // Capitalize first letter of operation type
    final operationTitle = widget.operationType == 'import' ? 'Nhập' : 'Xuất';

    return Scaffold(
      appBar: AppBar(
        title: Text('$operationTitle: $productName'),
        actions: [
          IconButton(
            icon: const Icon(Icons.qr_code_scanner),
            onPressed: _showBarcodeScanner,
            tooltip: 'Quét mã vạch',
          ),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _onRefresh,
            tooltip: 'Làm mới',
          ),
        ],
      ),
      body: _buildBody(
        isLoading: isLoading,
        error: error,
        stages: stages,
        selectedStage: selectedStage,
        selectedIndex: selectedIndex,
        theme: theme,
      ),
      bottomNavigationBar: _buildBottomActionBar(
        selectedStage: selectedStage,
        stages: stages,
        theme: theme,
      ),
    );
  }

  Widget _buildBody({
    required bool isLoading,
    required String? error,
    required List<ProductStageEntity> stages,
    required ProductStageEntity? selectedStage,
    required int selectedIndex,
    required ThemeData theme,
  }) {
    if (isLoading && stages.isEmpty) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (error != null && stages.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.error_outline,
                size: 48,
                color: theme.colorScheme.error,
              ),
              const SizedBox(height: 16),
              Text(
                'Lỗi',
                style: theme.textTheme.titleLarge?.copyWith(
                  color: theme.colorScheme.error,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                error,
                textAlign: TextAlign.center,
                style: theme.textTheme.bodyMedium,
              ),
              const SizedBox(height: 24),
              FilledButton.icon(
                onPressed: _onRefresh,
                icon: const Icon(Icons.refresh),
                label: const Text('Thử lại'),
              ),
            ],
          ),
        ),
      );
    }

    if (stages.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.inventory_2_outlined,
              size: 48,
              color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
            ),
            const SizedBox(height: 16),
            Text(
              'Không tìm thấy công đoạn',
              style: theme.textTheme.titleLarge,
            ),
          ],
        ),
      );
    }

    // Filter stages if stageId is provided
    final displayStages = widget.stageId != null
        ? stages.where((stage) => stage.productStageId == widget.stageId).toList()
        : stages;

    // When stageId is provided but no matching stage found
    if (widget.stageId != null && displayStages.isEmpty && stages.isNotEmpty) {
      return Scaffold(
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.search_off,
                  size: 64,
                  color: theme.colorScheme.error,
                ),
                const SizedBox(height: 16),
                Text(
                  'Không tìm thấy công đoạn',
                  style: theme.textTheme.titleLarge?.copyWith(
                    color: theme.colorScheme.error,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'Công đoạn với ID ${widget.stageId} không được tìm thấy trong sản phẩm này.',
                  textAlign: TextAlign.center,
                  style: theme.textTheme.bodyMedium,
                ),
                const SizedBox(height: 24),
                FilledButton.icon(
                  onPressed: () => Navigator.pop(context),
                  icon: const Icon(Icons.arrow_back),
                  label: const Text('Quay lại'),
                ),
              ],
            ),
          ),
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Stage chips section
          if (displayStages.isNotEmpty)
            Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
              decoration: BoxDecoration(
                color: theme.colorScheme.surfaceContainerHighest,
                border: Border(
                  bottom: BorderSide(
                    color: theme.colorScheme.outline.withValues(alpha: 0.2),
                  ),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: List.generate(displayStages.length, (index) {
                      final stage = displayStages[index];
                      // When stageId is provided, check if this stage matches the stageId
                      // Otherwise, check if the index matches the selected index
                      final isSelected = widget.stageId != null
                          ? stage.productStageId == widget.stageId
                          : stages.indexOf(stage) == selectedIndex;

                      return FilterChip(
                        selected: isSelected,
                        label: Text(stage.displayName),
                        onSelected: widget.stageId == null
                            ? (_) {
                                ref
                                    .read(productDetailProvider(_providerKey).notifier)
                                    .selectStage(stages.indexOf(stage));
                              }
                            : null, // Disable selection when specific stage is shown
                        backgroundColor: theme.colorScheme.surface,
                        selectedColor: theme.colorScheme.primaryContainer,
                        checkmarkColor: theme.colorScheme.primary,
                        labelStyle: TextStyle(
                          color: isSelected
                              ? theme.colorScheme.onPrimaryContainer
                              : theme.colorScheme.onSurface,
                          fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                        ),
                      );
                    }),
                  ),
                ],
              ),
            ),

          // Stage details section
          Expanded(
            child: () {
              // When stageId is provided, use the filtered stage
              final stageToShow = widget.stageId != null && displayStages.isNotEmpty
                  ? displayStages.first
                  : selectedStage;

              if (stageToShow == null) {
                return const Center(child: Text('Chưa chọn công đoạn'));
              }

              return SingleChildScrollView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      spacing: 8,
                      children: [
                        // Stage header
                        // _buildStageHeader(stageToShow, theme),
                        //
                        // _buildSectionCard(
                        //   theme: theme,
                        //   title: 'Thông tin công đoạn',
                        //   icon: Icons.info_outlined,
                        //   children: [
                        //     _buildInfoRow('Mã sản phẩm', '${stageToShow.productId}'),
                        //     if (stageToShow.productStageId != null)
                        //       _buildInfoRow('Mã công đoạn', '${stageToShow.productStageId}'),
                        //     if (stageToShow.actionTypeId != null)
                        //       _buildInfoRow('Mã loại thao tác', '${stageToShow.actionTypeId}'),
                        //     _buildInfoRow('Tên công đoạn', stageToShow.displayName),
                        //   ],
                        // ),

                        // Add New Quantities section
                        _buildSectionCard(
                          theme: theme,
                          title: 'Thêm số lượng mới',
                          icon: Icons.add_circle_outline,
                          children: [

                            _buildTextField(
                              label: 'Khối lượng đạt (kg)',
                              controller: _passedWeightController,
                              keyboardType: const TextInputType.numberWithOptions(decimal: true),
                              theme: theme,
                            ),
                            _buildTextField(
                              label: 'Số lượng đạt',
                              controller: _passedQuantityController,
                              keyboardType: TextInputType.number,
                              theme: theme,
                            ),
                            _buildTextField(
                              label: 'Khối lượng lỗi (kg)',
                              controller: _issuedWeightController,
                              keyboardType: const TextInputType.numberWithOptions(decimal: true),
                              theme: theme,
                            ),
                            _buildTextField(
                              label: 'Số lượng lỗi',
                              controller: _issuedQuantityController,
                              keyboardType: TextInputType.number,
                              theme: theme,
                            ),

                          ],
                        ),

                        _buildSectionCard(theme: theme, title: "Nhân viên", icon: Icons.people, children: [
                          // Warehouse User Dropdown (Required)
                          _buildUserDropdown(
                            label: 'Người dùng kho *',
                            value: _selectedWarehouseUser,
                            users: ref.watch(usersListProvider)
                                .where((user) => user.isWareHouseUser)
                                .toList(),
                            onChanged: (user) {
                              setState(() {
                                _selectedWarehouseUser = user;
                              });
                            },
                            theme: theme,
                          ),
                          const SizedBox(height: 8),
                          // All Employees Dropdown (Required)
                          _buildUserDropdown(
                            label: 'Nhân viên *',
                            value: _selectedEmployee,
                            users: ref.watch(usersListProvider)
                            .where((user) =>  user.roleId == 2)
                            .toList(),
                            onChanged: (user) {
                              setState(() {
                                _selectedEmployee = user;
                              });
                            },
                            theme: theme,
                          ),
                        ]),

                        // Current Quantity information
                        _buildSectionCard(
                          theme: theme,
                          title: 'Số lượng hiện tại',
                          icon: Icons.info_outlined,
                          children: [
                            _buildInfoRow('Số lượng đạt', '${stageToShow.passedQuantity}'),
                            _buildInfoRow(
                              'Khối lượng đạt',
                              '${stageToShow.passedQuantityWeight.toStringAsFixed(2)} kg',
                            ),
                            _buildInfoRow('Số lượng lỗi', '${stageToShow.issuedQuantity}'),
                            _buildInfoRow(
                              'Khối lượng lỗi',
                              '${stageToShow.issuedQuantityWeight.toStringAsFixed(2)} kg',
                            ),
                          ],
                        ),
                      ],
                    ),
                  );
            }(),
          ),
        ],
      ),
    );
  }

  Future<void> _printQuantities(ProductStageEntity stage) async {
    // Validate that both users are selected
    if (_selectedEmployee == null || _selectedWarehouseUser == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Vui lòng chọn cả Nhân viên và Người dùng kho trước khi in'),
          backgroundColor: Colors.orange,
          duration: Duration(seconds: 3),
        ),
      );
      return;
    }

    // Get the current quantity values (entered by user or use current values)
    final passedQuantity = int.tryParse(_passedQuantityController.text) ?? 0;
    final passedWeight = double.tryParse(_passedWeightController.text) ?? 0.0;
    final issuedQuantity = int.tryParse(_issuedQuantityController.text) ?? 0;
    final issuedWeight = double.tryParse(_issuedWeightController.text) ?? 0.0;

    // Use entered values if available, otherwise use current stock values
    final finalPassedPcs = passedQuantity > 0 ? passedQuantity : stage.passedQuantity;
    final finalPassedKg = passedWeight > 0.0 ? passedWeight : stage.passedQuantityWeight;
    final finalIssuedPcs = issuedQuantity > 0 ? issuedQuantity : stage.issuedQuantity;
    final finalIssuedKg = issuedWeight > 0.0 ? issuedWeight : stage.issuedQuantityWeight;

    // Get responsible user name
    final responsibleName = '${_selectedWarehouseUser!.name} ${_selectedWarehouseUser!.firstName}';
    final receiverName = '${_selectedEmployee!.name} ${_selectedEmployee!.firstName}';
    // Generate barcode data (using product code or product ID)
    final barcodeData = stage.productCode.isNotEmpty
        ? stage.productCode
        : 'P${stage.productId}';

    try {
      await SunmiService.printWarehouseExport(
        context: context,
        warehouseName: widget.warehouseName,
        productId: stage.productId,
        productCode: stage.productCode,
        productName: stage.productName,
        stageName: stage.displayName,
        passedKg: finalPassedKg,
        passedPcs: finalPassedPcs,
        issuedKg: finalIssuedKg,
        issuedPcs: finalIssuedPcs,
        responsibleName: responsibleName,
        receiverName: receiverName,
        barcodeData: barcodeData,
      );
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Lỗi khi in: ${e.toString()}'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }
  }

  Future<void> _addNewQuantities(ProductStageEntity stage) async {
    // Parse the values from text fields
    final passedQuantity = int.tryParse(_passedQuantityController.text) ?? 0;
    final passedWeight = double.tryParse(_passedWeightController.text) ?? 0.0;
    final issuedQuantity = int.tryParse(_issuedQuantityController.text) ?? 0;
    final issuedWeight = double.tryParse(_issuedWeightController.text) ?? 0.0;

    // Validate that at least one field has a value
    if (passedQuantity == 0 && passedWeight == 0.0 &&
        issuedQuantity == 0 && issuedWeight == 0.0) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Vui lòng nhập ít nhất một giá trị số lượng hoặc khối lượng'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // Validate that both users are selected
    if (_selectedEmployee == null || _selectedWarehouseUser == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Vui lòng chọn cả Nhân viên và Người dùng kho trước khi lưu'),
          backgroundColor: Colors.orange,
          duration: Duration(seconds: 3),
        ),
      );
      return;
    }



    // Show loading dialog
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );

    try {
      // Determine actionTypeId based on operation type
      // 4 = Import, 5 = Export
      final typeId = widget.operationType == 'import' ? 4 : 5;
      final actionTypeId = widget.operationType == 'import' ? 1 : 2;

      // Create request with all required fields
      final request = CreateProductWarehouseRequest(
        typeId: typeId, // Import type
        productId: stage.productId,
        stageId: stage.stageId ?? 0,
        orderId: null,
        recordDate: DateTime.now().toIso8601String(),
        passedQuantityWeight: passedWeight,
        passedQuantity: passedQuantity,
        issuedQuantityWeight: issuedWeight,
        issuedQuantity: issuedQuantity,
        responsibleUserId: _selectedEmployee!.id,
        description: '',
        productName: stage.productName,
        productCode: stage.productCode,
        stockPassedQuantityWeight: stage.passedQuantityWeight,
        stockPassedQuantity: stage.passedQuantity,
        stockIssuedQuantity: stage.issuedQuantity,
        stockIssuedQuantityWeight: stage.issuedQuantityWeight,
        receiverUserId: _selectedWarehouseUser!.id,
        actionTypeId: actionTypeId,
        wareHouseId: widget.warehouseId,
        productStageId: stage.productStageId ?? 0,
        isConfirm: true,
      );

      // Call the repository to create product warehouse entry
      final repository = ref.read(productsRepositoryProvider);
      final result = await repository.createProductWarehouse(request);

      // Dismiss loading dialog
      if (mounted) Navigator.of(context).pop();

      result.fold(
        (failure) {
          // Show error message
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('Lỗi khi thêm số lượng: ${failure.message}'),
                backgroundColor: Colors.red,
                duration: const Duration(seconds: 3),
              ),
            );
          }
        },
        (_) async {
          // Success - show success message
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('Đã thêm số lượng thành công!'),
                backgroundColor: Colors.green,
                duration: const Duration(seconds: 2),
              ),
            );

            // Print before saving to API
            await _printQuantities(stage);

            // Refresh the product detail to show updated quantities
            await ref.read(productDetailProvider(_providerKey).notifier).refreshProductDetail(
                  widget.warehouseId,
                  widget.productId,
                );

            // Do NOT clear quantity/weight fields - keep them for reference
            // User can manually clear them if needed using the 'C' button
          }
        },
      );
    } catch (e) {
      // Dismiss loading dialog
      if (mounted) Navigator.of(context).pop();

      // Show error message
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Lỗi: ${e.toString()}'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }
  }

  Widget _buildStageHeader(ProductStageEntity stage, ThemeData theme) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            Container(
              width: 56,
              height: 56,
              decoration: BoxDecoration(
                color: theme.colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(
                Icons.build_circle_outlined,
                size: 32,
                color: theme.colorScheme.primary,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    stage.displayName,
                    style: theme.textTheme.titleLarge?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    'Sản phẩm ID: ${stage.productId}',
                    style: theme.textTheme.bodyMedium?.copyWith(
                      color: theme.colorScheme.onSurfaceVariant,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionCard({
    required ThemeData theme,
    required String title,
    required IconData icon,
    required List<Widget> children,
  }) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 4,
          children: [
            ...children,
          ],
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            flex: 2,
            child: Text(
              label,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Theme.of(context).colorScheme.onSurfaceVariant,
                  ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            flex: 3,
            child: Text(
              value,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    fontWeight: FontWeight.w500,
                  ),
              textAlign: TextAlign.end,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTextField({
    required String label,
    required TextEditingController controller,
    required TextInputType keyboardType,
    required ThemeData theme,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TextField(
          controller: controller,
          keyboardType: keyboardType,
          decoration: InputDecoration(
            labelText: label,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide(
                color: theme.colorScheme.outline,
              ),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide(
                color: theme.colorScheme.primary,
                width: 2,
              ),
            ),
            filled: true,
            fillColor: theme.colorScheme.surface,
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 12,
            ),
          ),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: OutlinedButton(
                onPressed: () => _incrementValue(controller, 0.1),
                style: OutlinedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 8),
                ),
                child: const Text('+0.1'),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: OutlinedButton(
                onPressed: () => _incrementValue(controller, 0.5),
                style: OutlinedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 8),
                ),
                child: const Text('+0.5'),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: OutlinedButton(
                onPressed: () => _incrementValue(controller, 1),
                style: OutlinedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 8),
                ),
                child: const Text('+1'),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: OutlinedButton(
                onPressed: () => controller.clear(),
                style: OutlinedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 8),
                  foregroundColor: theme.colorScheme.error,
                ),
                child: const Text('C'),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildUserDropdown({
    required String label,
    required UserEntity? value,
    required List<UserEntity> users,
    required Function(UserEntity?) onChanged,
    required ThemeData theme,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        DropdownSearch<UserEntity>(
          items: (filter, infiniteScrollProps) => users,
          selectedItem: value,
          itemAsString: (UserEntity user) {
            return user.name.isNotEmpty
                ? '${user.name} ${user.firstName}'
                : user.email;
          },
          compareFn: (item1, item2) => item1.id == item2.id,
          // Custom filter function for Vietnamese-aware search
          filterFn: (user, filter) {
            if (filter.isEmpty) return true;

            // Search in name, firstName, and email
            final searchTexts = [
              user.name,
              user.firstName,
              user.email,
              '${user.name} ${user.firstName}', // Full name
            ];

            // Use Vietnamese-aware search
            return TextUtils.containsVietnameseSearchInAny(searchTexts, filter);
          },
          popupProps: PopupProps.menu(
            showSearchBox: true,
            searchFieldProps: TextFieldProps(
              decoration: InputDecoration(
                labelText: 'Tìm kiếm',
                hintText: 'Nhập tên hoặc email...',
                prefixIcon: const Icon(Icons.search),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
              ),
            ),
            menuProps: const MenuProps(
              borderRadius: BorderRadius.all(Radius.circular(8)),
              elevation: 8,
            ),
            itemBuilder: (context, item, isDisabled, isSelected) {
              return ListTile(
                selected: isSelected,
                dense: true,
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 4,
                ),
                title: Text(
                  item.name.isNotEmpty
                      ? '${item.name} ${item.firstName}'
                      : item.email,
                  overflow: TextOverflow.ellipsis,
                ),
                subtitle: item.email.isNotEmpty && item.name.isNotEmpty
                    ? Text(
                        item.email,
                        style: Theme.of(context).textTheme.bodySmall,
                        overflow: TextOverflow.ellipsis,
                      )
                    : null,
              );
            },
            emptyBuilder: (context, searchEntry) {
              return Center(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Text(
                    'Không tìm thấy kết quả',
                    style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                          color: theme.colorScheme.onSurfaceVariant,
                        ),
                  ),
                ),
              );
            },
          ),
          decoratorProps: DropDownDecoratorProps(
            decoration: InputDecoration(
              labelText: label,
              hintText: 'Chọn $label',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide(
                  color: theme.colorScheme.outline,
                ),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide(
                  color: theme.colorScheme.primary,
                  width: 2,
                ),
              ),
              filled: true,
              fillColor: theme.colorScheme.surface,
              contentPadding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 12,
              ),
            ),
          ),
          onChanged: onChanged,
        ),
      ],
    );
  }

  void _incrementValue(TextEditingController controller, double increment) {
    final currentValue = double.tryParse(controller.text) ?? 0.0;
    final newValue = currentValue + increment;

    // Format the value based on whether it's a whole number or has decimals
    if (newValue == newValue.toInt()) {
      controller.text = newValue.toInt().toString();
    } else {
      controller.text = newValue.toStringAsFixed(1);
    }
  }

  Widget? _buildBottomActionBar({
    required ProductStageEntity? selectedStage,
    required List<ProductStageEntity> stages,
    required ThemeData theme,
  }) {
    // Determine which stage to show
    // When stageId is provided, use the filtered stage
    final displayStages = widget.stageId != null
        ? stages.where((stage) => stage.productStageId == widget.stageId).toList()
        : stages;

    final stageToShow = widget.stageId != null && displayStages.isNotEmpty
        ? displayStages.first
        : selectedStage;

    // Don't show action bar if there's no stage to work with
    if (stageToShow == null) {
      return null;
    }

    return Container(
      decoration: BoxDecoration(
        color: theme.colorScheme.surface,
        boxShadow: [
          BoxShadow(
            color: theme.colorScheme.shadow.withValues(alpha: 0.1),
            blurRadius: 8,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        top: false,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            spacing: 12,
            children: [
              Expanded(
                child: OutlinedButton.icon(
                  onPressed: () => _printQuantities(stageToShow),
                  icon: const Icon(Icons.print),
                  label: const Text('In'),
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                  ),
                ),
              ),
              Expanded(
                child: FilledButton.icon(
                  onPressed: () => _addNewQuantities(stageToShow),
                  icon: const Icon(Icons.save),
                  label: const Text('Lưu'),
                  style: FilledButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

}
