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

import '../../../../core/di/providers.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();

      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();
  }

  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;
    });
  }

  @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' ? 'Import' : 'Export';

    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              operationTitle,
              style: textTheme.titleMedium,
            ),
            Text(
              productName,
              style: textTheme.bodySmall?.copyWith(
                color: theme.colorScheme.onSurfaceVariant,
              ),
            ),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _onRefresh,
            tooltip: 'Refresh',
          ),
        ],
      ),
      body: _buildBody(
        isLoading: isLoading,
        error: error,
        stages: stages,
        selectedStage: selectedStage,
        selectedIndex: selectedIndex,
        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(
                'Error',
                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('Retry'),
              ),
            ],
          ),
        ),
      );
    }

    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(
              'No stages found',
              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(
                  'Stage Not Found',
                  style: theme.textTheme.titleLarge?.copyWith(
                    color: theme.colorScheme.error,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'Stage with ID ${widget.stageId} was not found in this product.',
                  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('Go Back'),
                ),
              ],
            ),
          ),
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Stage chips section
          if (displayStages.isNotEmpty)
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: theme.colorScheme.surfaceContainerHighest,
                border: Border(
                  bottom: BorderSide(
                    color: theme.colorScheme.outline.withValues(alpha: 0.2),
                  ),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
                        widget.stageId != null
                            ? 'Selected Stage'
                            : 'Production Stages (${displayStages.length})',
                        style: theme.textTheme.titleSmall?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      if (widget.stageId != null) ...[
                        const Spacer(),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: theme.colorScheme.primaryContainer,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Text(
                            'ID: ${widget.stageId}',
                            style: theme.textTheme.bodySmall?.copyWith(
                              color: theme.colorScheme.onPrimaryContainer,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ],
                  ),
                  const SizedBox(height: 12),
                  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('No stage selected'));
              }

              return SingleChildScrollView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      spacing: 16,
                      children: [
                        // Stage header
                        _buildStageHeader(stageToShow, theme),

                        _buildSectionCard(
                          theme: theme,
                          title: 'Stage Information',
                          icon: Icons.info_outlined,
                          children: [
                            _buildInfoRow('Product ID', '${stageToShow.productId}'),
                            if (stageToShow.productStageId != null)
                              _buildInfoRow('Stage ID', '${stageToShow.productStageId}'),
                            if (stageToShow.actionTypeId != null)
                              _buildInfoRow('Action Type ID', '${stageToShow.actionTypeId}'),
                            _buildInfoRow('Stage Name', stageToShow.displayName),
                          ],
                        ),

                        // Current Quantity information
                        _buildSectionCard(
                          theme: theme,
                          title: 'Current Quantities',
                          icon: Icons.info_outlined,
                          children: [
                            _buildInfoRow('Passed Quantity', '${stageToShow.passedQuantity}'),
                            _buildInfoRow(
                              'Passed Weight',
                              '${stageToShow.passedQuantityWeight.toStringAsFixed(2)} kg',
                            ),
                            _buildInfoRow('Issued Quantity', '${stageToShow.issuedQuantity}'),
                            _buildInfoRow(
                              'Issued Weight',
                              '${stageToShow.issuedQuantityWeight.toStringAsFixed(2)} kg',
                            ),
                          ],
                        ),

                        // Add New Quantities section
                        _buildSectionCard(
                          theme: theme,
                          title: 'Add New Quantities',
                          icon: Icons.add_circle_outline,
                          children: [
                            _buildTextField(
                              label: 'Passed Quantity',
                              controller: _passedQuantityController,
                              keyboardType: TextInputType.number,
                              theme: theme,
                            ),
                            _buildTextField(
                              label: 'Passed Weight (kg)',
                              controller: _passedWeightController,
                              keyboardType: const TextInputType.numberWithOptions(decimal: true),
                              theme: theme,
                            ),
                            _buildTextField(
                              label: 'Issued Quantity',
                              controller: _issuedQuantityController,
                              keyboardType: TextInputType.number,
                              theme: theme,
                            ),
                            _buildTextField(
                              label: 'Issued Weight (kg)',
                              controller: _issuedWeightController,
                              keyboardType: const TextInputType.numberWithOptions(decimal: true),
                              theme: theme,
                            ),
                          ],
                        ),

                        _buildSectionCard(theme: theme, title: "Nhân viên", icon: Icons.people, children: [
                          // Warehouse User Dropdown
                          _buildUserDropdown(
                            label: 'Warehouse User',
                            value: _selectedWarehouseUser,
                            users: ref.watch(usersListProvider)
                                .where((user) => user.isWareHouseUser)
                                .toList(),
                            onChanged: (user) {
                              setState(() {
                                _selectedWarehouseUser = user;
                              });
                            },
                            theme: theme,
                          ),
                          // All Employees Dropdown
                          _buildUserDropdown(
                            label: 'Employee',
                            value: _selectedEmployee,
                            users: ref.watch(usersListProvider),
                            onChanged: (user) {
                              setState(() {
                                _selectedEmployee = user;
                              });
                            },
                            theme: theme,
                          ),
                        ]),

                        // Action buttons
                        Row(
                          spacing: 12,
                          children: [

                            Expanded(
                              child: OutlinedButton.icon(
                                onPressed: () => _printQuantities(stageToShow),
                                icon: const Icon(Icons.print),
                                label: const Text('Print'),
                                style: OutlinedButton.styleFrom(
                                  padding: const EdgeInsets.symmetric(vertical: 16),
                                ),
                              ),
                            ),
                            Expanded(
                              child: FilledButton.icon(
                                onPressed: () => _addNewQuantities(stageToShow),
                                icon: const Icon(Icons.save),
                                label: const Text('Save'),
                                style: FilledButton.styleFrom(
                                  padding: const EdgeInsets.symmetric(vertical: 16),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  );
            }(),
          ),
        ],
      ),
    );
  }

  void _printQuantities(ProductStageEntity stage) {
    // TODO: Implement print functionality
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Print functionality coming soon'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  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('Please enter at least one quantity or weight value'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // Validate that both users are selected
    if (_selectedEmployee == null || _selectedWarehouseUser == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please select both Employee and Warehouse User'),
          backgroundColor: Colors.orange,
        ),
      );
      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('Failed to add quantities: ${failure.message}'),
                backgroundColor: Colors.red,
                duration: const Duration(seconds: 3),
              ),
            );
          }
        },
        (_) {
          // Success - show success message
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('Quantities added successfully!'),
                backgroundColor: Colors.green,
                duration: const Duration(seconds: 2),
              ),
            );

            // Clear the text fields after successful add
            _clearControllers();

            // Refresh the product detail to show updated quantities
            ref.read(productDetailProvider(_providerKey).notifier).refreshProductDetail(
                  widget.warehouseId,
                  widget.productId,
                );
          }
        },
      );
    } catch (e) {
      // Dismiss loading dialog
      if (mounted) Navigator.of(context).pop();

      // Show error message
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Error: ${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(
                    'Product 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(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 12,
          children: [
            Row(
              children: [
                Icon(
                  icon,
                  size: 20,
                  color: theme.colorScheme.primary,
                ),
                const SizedBox(width: 8),
                Text(
                  title,
                  style: theme.textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            ...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: [
        DropdownButtonFormField<UserEntity>(
          value: value,
          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,
            ),
          ),
          hint: Text('Select $label'),
          items: users.map((user) {
            return DropdownMenuItem<UserEntity>(
              value: user,
              child: Text(
                user.name.isNotEmpty ? '${user.name} ${user.firstName}' : user.email,
                overflow: TextOverflow.ellipsis,
              ),
            );
          }).toList(),
          onChanged: onChanged,
          isExpanded: true,
        ),
      ],
    );
  }

  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 _buildStatusCards(ProductStageEntity stage, ThemeData theme) {
    return Row(
      children: [
        Expanded(
          child: Card(
            color: stage.hasPassedQuantity
                ? Colors.green.withValues(alpha: 0.1)
                : Colors.grey.withValues(alpha: 0.1),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  Icon(
                    stage.hasPassedQuantity ? Icons.check_circle : Icons.cancel,
                    color: stage.hasPassedQuantity ? Colors.green : Colors.grey,
                    size: 32,
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Has Passed',
                    style: theme.textTheme.bodySmall,
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Card(
            color: stage.hasIssuedQuantity
                ? Colors.blue.withValues(alpha: 0.1)
                : Colors.grey.withValues(alpha: 0.1),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  Icon(
                    stage.hasIssuedQuantity ? Icons.check_circle : Icons.cancel,
                    color: stage.hasIssuedQuantity ? Colors.blue : Colors.grey,
                    size: 32,
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Has Issued',
                    style: theme.textTheme.bodySmall,
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}
