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

/// The result returned by [showAddNoteDialog].
class AddNoteDialogResult {
  /// The trimmed note text entered by the operator.
  final String note;

  const AddNoteDialogResult({required this.note});
}

/// Shows a modal dialog that lets the operator type a note for an order.
///
/// Returns an [AddNoteDialogResult] when the operator confirms, or `null`
/// if they cancel.
Future<AddNoteDialogResult?> showAddNoteDialog(BuildContext context) {
  return showDialog<AddNoteDialogResult>(
    context: context,
    builder: (context) => const _AddNoteDialog(),
  );
}

class _AddNoteDialog extends StatefulWidget {
  const _AddNoteDialog();

  @override
  State<_AddNoteDialog> createState() => _AddNoteDialogState();
}

class _AddNoteDialogState extends State<_AddNoteDialog> {
  final _controller = TextEditingController();
  String? _error;

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _submit() {
    final text = _controller.text.trim();
    if (text.isEmpty) {
      setState(() => _error = 'Note cannot be empty.');
      return;
    }
    Navigator.of(context).pop(AddNoteDialogResult(note: text));
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Add Note'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('Enter a note to attach to this order.'),
          const SizedBox(height: KcSpacing.md),
          TextField(
            controller: _controller,
            autofocus: true,
            maxLines: 3,
            decoration: InputDecoration(
              hintText: 'e.g. Gift wrap requested, fragile item…',
              border: const OutlineInputBorder(),
              errorText: _error,
            ),
            onChanged: (_) {
              if (_error != null) setState(() => _error = null);
            },
          ),
        ],
      ),
      actions: [
        TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel')),
        FilledButton(onPressed: _submit, child: const Text('Add Note')),
      ],
    );
  }
}
