// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// add_edit_inventory.dart
//
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:nokken/src/core/ui/widgets/shared_widgets.dart';
import 'package:nokken/src/core/ui/theme/app_icons.dart';
import 'package:nokken/src/core/services/navigation/navigation_service.dart';

/// Inventory Section for tracking medication quantities
class InventorySection extends StatelessWidget {
  final int currentQuantity;
  final int refillThreshold;
  final ValueChanged<int> onQuantityChanged;
  final ValueChanged<int> onThresholdChanged;

  const InventorySection({
    super.key,
    required this.currentQuantity,
    required this.refillThreshold,
    required this.onQuantityChanged,
    required this.onThresholdChanged,
  });

  @override
  Widget build(BuildContext context) {
    return SharedWidgets.basicCard(
      context: context,
      title: 'Inventory',
      children: [
        _buildCounterRow(
          context,
          label: 'Current Quantity',
          value: currentQuantity,
          onChanged: onQuantityChanged,
          minValue: 0,
          showAddButton: true,
        ),
        SharedWidgets.verticalSpace(),
        _buildCounterRow(
          context,
          label: 'Refill Alert at',
          value: refillThreshold,
          onChanged: onThresholdChanged,
          minValue: 0,
          showAddButton: false,
        ),
      ],
    );
  }

  Widget _buildCounterRow(
    BuildContext context, {
    required String label,
    required int value,
    required ValueChanged<int> onChanged,
    required int minValue,
    required bool showAddButton,
    int? maxValue,
  }) {
    final controller = TextEditingController(text: value.toString());

    return Row(
      children: [
        Text('$label: '),
        Flexible(
          child: TextField(
            controller: controller,
            keyboardType: TextInputType.number,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly],
            // onChanged callback to update parent state as user types
            onChanged: (String val) {
              final newValue = int.tryParse(val) ?? value;
              if (newValue >= minValue &&
                  (maxValue == null || newValue <= maxValue)) {
                onChanged(newValue);
              }
            },
            // Keep onSubmitted for validation
            onSubmitted: (String val) {
              final newValue = int.tryParse(val) ?? value;
              if (newValue >= minValue &&
                  (maxValue == null || newValue <= maxValue)) {
                onChanged(newValue);
              } else {
                controller.text = value.toString();
              }
            },
          ),
        ),
        if (showAddButton)
          TextButton.icon(
            icon: Icon(AppIcons.getIcon('add')),
            label: const Text('Add More'),
            onPressed: () {
              showDialog(
                context: context,
                builder: (context) => AlertDialog(
                  title: const Text('Add More'),
                  content: TextField(
                    controller: controller,
                    keyboardType: TextInputType.number,
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    decoration: const InputDecoration(
                      labelText: 'Amount to add',
                    ),
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => NavigationService.goBack(context),
                      child: const Text('Cancel'),
                    ),
                    TextButton(
                      onPressed: () {
                        final amount = int.tryParse(controller.text) ?? 0;
                        final newValue = value + amount;
                        if (maxValue == null || newValue <= maxValue) {
                          onChanged(newValue);
                          controller.text = newValue.toString();
                        }
                        NavigationService.goBack(context);
                      },
                      child: const Text('Add'),
                    ),
                  ],
                ),
              );
            },
          ),
      ],
    );
  }
}
