import 'package:component_library/component_library.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:form_fields/src/error_messages.dart';
import 'package:reactive_forms/reactive_forms.dart';

class ReactiveInputField<T> extends StatefulWidget {
  const ReactiveInputField({
    Key? key,
    required this.name,
    required this.label,
    required this.placeholder,
    required this.obscureText,
    required this.textInputType,
    this.suffixIcon,
    this.suffix,
    this.prefix,
    this.prefixIcon,
    this.inputFormatters,
    this.customErrorMessages,
  }) : super(key: key);

  final String name;
  final String label;
  final String placeholder;
  final Widget? suffixIcon;
  final Widget? suffix;
  final Widget? prefix;
  final Widget? prefixIcon;
  final bool obscureText;
  final TextInputType textInputType;
  final List<TextInputFormatter>? inputFormatters;
  final Map<String, String>? customErrorMessages;

  @override
  State<ReactiveInputField> createState() => _ReactiveInputFieldState();
}

class _ReactiveInputFieldState<T> extends State<ReactiveInputField<T>> {
  @override
  Widget build(BuildContext context) {
    return ReactiveValueListenableBuilder<T>(
      formControlName: widget.name,
      builder: (context, control, child) {
        return InputField(
          label: widget.label,
          onChange: (value) {
            control.value = value as T?;
          },
          placeholder: widget.placeholder,
          textInputType: widget.textInputType,
          obscureText: widget.obscureText,
          errorMessage: ErrorMessages.getUiErrorMessage(
            control: control,
            label: widget.label,
          ),
          inputFormatters: widget.inputFormatters,
          prefix: widget.prefix,
          prefixIcon: widget.prefixIcon,
          suffix: widget.suffix,
          suffixIcon: widget.suffixIcon,
          isDisabled: control.disabled,
          isTouched: control.touched,
          isError: control.hasErrors,
        );
      },
    );
  }
}
