import 'package:flutter/material.dart';
import 'base_field.dart';
import '../../../shared/widgets/inputs/modern_text_field.dart';

/// Custom text input field implementation (preferred over legacy TextField)
class CustomTextField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final int? maxLength;
  final TextInputType? keyboardType;
  final Map<String, dynamic>? customProperties;
  final String? Function(String?)? customValidator;

  CustomTextField({
    required this.fieldKey,
    required this.label,
    required this.hint,
    this.isRequired = false,
    this.maxLength,
    this.keyboardType,
    this.customProperties,
    this.customValidator,
  });

  @override
  String? Function(String?)? get validator => (value) {
        // Custom validator (e.g., range checks)
        if (customValidator != null) {
          final err = customValidator!(value);
          if (err != null) return err;
        }
        if (isRequired && (value == null || value.isEmpty)) {
          return '$label is required';
        }
        if (maxLength != null && value != null && value.length > maxLength!) {
          return '$label must be less than $maxLength characters';
        }
        return null;
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    final bool isPassword = customProperties?['isPassword'] == true;
    return ModernTextField(
      controller: controller,
      hint: hint,
      maxLength: maxLength,
      keyboardType: keyboardType,
      obscureText: isPassword,
      onChanged: onChanged != null ? (_) => onChanged() : null,
      validator: validator,
    );
  }
}
