import '../../../ui/theme/app_theme.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../ui/sessions/chat_adaptive.dart'; import 'chat_card_styles.dart'; import 'chat_question_card_controls.dart'; import 'chat_question_card_fields.dart'; import 'chat_question_card_model.dart'; import 'chat_question_recorded_answers.dart'; import 'chat_question_validation.dart'; /// One recorded agent question as a native card. /// /// A pending question keeps the operator's choices locally until Send answer; /// the answer map is field-keyed, exactly as `chat_answer` expects. Resolved /// and expired questions show the recorded answers read-only. class ChatQuestionCard extends StatefulWidget { const ChatQuestionCard({ super.key, required this.form, required this.onSubmit, this.error, }); final JsonMap form; final Future Function(Map answers, String action) onSubmit; final String? error; @override State createState() => _ChatQuestionCardState(); } class _ChatQuestionCardState extends State { late final List _fields = chatFormFields(widget.form); late final Map _answers = _initialAnswers(); final Map _controllers = {}; String _localError = ''; bool _sending = false; bool get _pending => chatFormPending(widget.form); Map _initialAnswers() { final recorded = widget.form['answers']; final answers = recorded is Map ? Map.from(recorded) : {}; for (final field in _fields) { final key = '${field['key'] ?? ''}'.trim(); if (key.isEmpty || answers.containsKey(key)) continue; if (field['default'] != null) answers[key] = field['default']; } return answers; } @override void initState() { super.initState(); for (final field in _fields) { if (!chatQuestionFieldNeedsInput(field)) continue; final key = '${field['key'] ?? ''}'.trim(); if (key.isEmpty) continue; final value = _answers[key]; final options = chatQuestionOptions( field, ).map(chatQuestionOptionValue).toSet(); final custom = value is List ? value.where((entry) => !options.contains('$entry')).join(', ') : (value is String && !options.contains(value) ? value : ''); final controller = TextEditingController(text: custom); _controllers[key] = controller; } } @override void dispose() { for (final controller in _controllers.values) { controller.dispose(); } super.dispose(); } void _changed(String key, Object? value) { setState(() { if (value == null) { _answers.remove(key); } else { _answers[key] = value; } _localError = ''; }); } Future _submit() async { if (_sending || !_pending) return; final reason = chatFormAnswerError(_fields, _answers); if (reason.isNotEmpty) { setState(() => _localError = reason); return; } setState(() { _sending = true; _localError = ''; }); final accept = widget.form['actions'] is List && (widget.form['actions'] as List).contains('accept'); await widget.onSubmit( chatVisibleFormAnswers(_fields, _answers), accept ? 'accept' : '', ); if (mounted) setState(() => _sending = false); } Future _action(String action) async { if (_sending || !_pending) return; setState(() { _sending = true; _localError = ''; }); await widget.onSubmit(const {}, action); if (mounted) setState(() => _sending = false); } @override Widget build(BuildContext context) { final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; final body = _body(context, cupertino); final wrapped = cupertino ? DefaultTextStyle.merge( style: CupertinoTheme.of(context).textTheme.textStyle, child: body, ) : body; if (cupertino) { return CupertinoListSection.insetGrouped( backgroundColor: AppColors.groupedBackground, // As the Material card: the transcript row owns the horizontal inset, // so the card lines up with the message bubbles. margin: const EdgeInsets.only(bottom: 12), children: [Padding(padding: const EdgeInsets.all(16), child: wrapped)], ); } return Card( // Keep consecutive cards visually separate; the transcript row only // supplies the horizontal inset. margin: const EdgeInsets.only(bottom: 12), child: Padding(padding: const EdgeInsets.all(16), child: wrapped), ); } Widget _body(BuildContext context, bool cupertino) { final actions = widget.form['actions']; final error = widget.error?.trim().isNotEmpty == true ? widget.error!.trim() : _localError; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( '${widget.form['title'] ?? ''}'.trim().isEmpty ? 'Question' : '${widget.form['title']}'.trim(), style: chatCardTitleStyle(context, cupertino), ), Text(_statusLine(), style: chatCardSecondaryStyle(context, cupertino)), if (error.isNotEmpty) Padding( padding: const EdgeInsets.only(top: 8), child: Semantics( liveRegion: true, child: Text( error, style: chatCardBodyStyle( context, cupertino, )?.copyWith(color: chatCardErrorColor(context, cupertino)), ), ), ), if (_pending) ...chatQuestionFieldWidgets( context: context, fields: _fields, answers: _answers, cupertino: cupertino, controllers: _controllers, onChanged: _changed, ) else ...chatQuestionRecordedAnswers( context: context, form: widget.form, cupertino: cupertino, ), if (_pending) ...[ const SizedBox(height: 12), chatQuestionControls( context: context, cupertino: cupertino, actions: actions, submitLabel: _submitLabel, sending: _sending, onSubmit: _submit, onAction: _action, ), ], ], ); } String _statusLine() { if (_pending) return chatQuestionWaiting; if (widget.form['cancelled'] == true) return chatQuestionExpired; final answers = widget.form['answers']; return answers is Map && answers.isNotEmpty ? chatQuestionAnswered : chatQuestionClosed; } String get _submitLabel { final allExternal = _fields.isNotEmpty && _fields.every((field) => '${field['type'] ?? ''}' == 'external'); return allExternal ? chatQuestionConfirm : chatQuestionSubmit; } }