import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../domain/inventory_item.dart';

/// Result returned by [showAdjustQuantityDialog].
class AdjustQuantityDialogResult {
  final int delta;
  final String reason;

  const AdjustQuantityDialogResult({required this.delta, required this.reason});
}

/// Shows a modal dialog for adjusting the quantity of [item].
///
/// Returns an [AdjustQuantityDialogResult] if the operator confirms, or `null`
/// if they cancel.
Future<AdjustQuantityDialogResult?> showAdjustQuantityDialog(
  BuildContext context,
  InventoryItem item,
) {
  return showDialog<AdjustQuantityDialogResult>(
    context: context,
    builder: (_) => _AdjustQuantityDialog(item: item),
  );
}

// ── Private dialog widget ──────────────────────────────────────────────────────

class _AdjustQuantityDialog extends StatefulWidget {
  final InventoryItem item;

  const _AdjustQuantityDialog({required this.item});

  @override
  State<_AdjustQuantityDialog> createState() => _AdjustQuantityDialogState();
}

class _AdjustQuantityDialogState extends State<_AdjustQuantityDialog> {
  final _deltaController = TextEditingController();
  final _reasonController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  /// Whether the adjustment is an addition (+) or removal (−).
  bool _isAddition = true;

  @override
  void dispose() {
    _deltaController.dispose();
    _reasonController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final currentQty = widget.item.quantityOnHand;

    return AlertDialog(
      title: const Text('Adjust Quantity'),
      content: SizedBox(
        width: 360,
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Current quantity display
              Text(
                'Current quantity: $currentQty',
                style: theme.textTheme.bodySmall?.copyWith(color: KcColors.neutral),
              ),
              const SizedBox(height: KcSpacing.md),

              // Add / Remove toggle
              SegmentedButton<bool>(
                segments: const [
                  ButtonSegment(value: true, label: Text('Add'), icon: Icon(Icons.add)),
                  ButtonSegment(value: false, label: Text('Remove'), icon: Icon(Icons.remove)),
                ],
                selected: {_isAddition},
                onSelectionChanged: (s) => setState(() => _isAddition = s.first),
              ),
              const SizedBox(height: KcSpacing.md),

              // Amount field
              TextFormField(
                controller: _deltaController,
                keyboardType: TextInputType.number,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                decoration: const InputDecoration(
                  labelText: 'Amount',
                  hintText: 'e.g. 5',
                  border: OutlineInputBorder(),
                ),
                autofocus: true,
                validator: (v) {
                  if (v == null || v.trim().isEmpty) return 'Enter an amount';
                  final n = int.tryParse(v.trim());
                  if (n == null || n <= 0) return 'Must be a positive number';
                  if (!_isAddition && n > currentQty) {
                    return 'Cannot remove more than $currentQty';
                  }
                  return null;
                },
              ),
              const SizedBox(height: KcSpacing.md),

              // Reason field
              TextFormField(
                controller: _reasonController,
                decoration: const InputDecoration(
                  labelText: 'Reason',
                  hintText: 'e.g. restock, sold, damaged',
                  border: OutlineInputBorder(),
                ),
                validator: (v) {
                  if (v == null || v.trim().isEmpty) return 'Enter a reason';
                  return null;
                },
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel')),
        FilledButton(onPressed: _submit, child: const Text('Confirm')),
      ],
    );
  }

  void _submit() {
    if (!_formKey.currentState!.validate()) return;
    final amount = int.parse(_deltaController.text.trim());
    final delta = _isAddition ? amount : -amount;
    Navigator.of(
      context,
    ).pop(AdjustQuantityDialogResult(delta: delta, reason: _reasonController.text.trim()));
  }
}
