import 'package:flutter/material.dart';

import 'package:email_validator/email_validator.dart';


class EmailFieldController {
  final TextEditingController textController;
  final ValueNotifier<bool> isValid;

  EmailFieldController({
    TextEditingController? controller,
  })  : textController = controller ?? TextEditingController(),
        isValid = ValueNotifier<bool>(false);

  String get text => textController.text;

  void setText(String value) {
    textController.text = value;
    onChanged(value);
  }

  bool _isValidEmail(String? value) {
    final trimmed = value?.trim() ?? '';
    if (trimmed.isEmpty) {
      return false;
    }
    return EmailValidator.validate(trimmed);
  }

  String? validate(String? value, String invalidMessage) {
    final result = _isValidEmail(value) ? null : invalidMessage;
    isValid.value = result == null;
    return result;
  }

  void onChanged(String? value) {
    isValid.value = _isValidEmail(value);
  }

  void dispose() {
    textController.dispose();
    isValid.dispose();
  }
}
