import 'package:flutter/material.dart';

import 'package:pweb/pages/settings/widgets/base.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


class TextEditTile extends BaseEditTile<String> {
  const TextEditTile({
    super.key,
    required super.icon,
    required super.title,
    required super.valueGetter,
    required super.valueSetter,
    required super.errorSituation,
    required this.hintText,
  });

  final String hintText;

  @override
  Widget buildView(BuildContext context, String? value) {
    final locs = AppLocalizations.of(context)!;
    final display = (value ?? '').isEmpty ? locs.notSet : value!;
    return Text(
      display,
      semanticsLabel: (value ?? '').isEmpty ? locs.notSet : '$title: $display',
    );
  }

  @override
  Widget buildEditor(
    BuildContext context,
    String? initial,
    void Function(String) onSave,
    VoidCallback onCancel,
    bool isSaving,
  ) {
    final controller = TextEditingController(text: initial ?? '');
    return Row(
      children: [
        Expanded(
          child: TextField(
            controller: controller,
            autofocus: true,
            decoration: InputDecoration(
              hintText: hintText,
              isDense: true,
              contentPadding: const EdgeInsets.symmetric(vertical: 8, horizontal: 6),
            ),
            onSubmitted: (_) => onSave(controller.text.trim()),
          ),
        ),
        const SizedBox(width: 8.0),
        AnimatedSwitcher(
          duration: const Duration(milliseconds: 200),
          child: isSaving
            ? const SizedBox(
                width: 18,
                height: 18,
                child: CircularProgressIndicator(strokeWidth: 2),
              )
            : Row(
                key: const ValueKey('actions'),
                children: [
                  Tooltip(
                    message: AppLocalizations.of(context)!.ok,
                    child: IconButton(
                      icon: const Icon(Icons.check),
                      onPressed: () => onSave(controller.text.trim()),
                      visualDensity: VisualDensity.compact,
                    ),
                  ),
                  Tooltip(
                    message: AppLocalizations.of(context)!.cancel,
                    child: IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: onCancel,
                      visualDensity: VisualDensity.compact,
                    ),
                  ),
                ],
              ),
        ),
      ],
    );
  }
}
