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

/// Reusable password field supporting dynamic pairing with confirm password
/// via a shared groupId. Use two instances with the same groupId, one with
/// isConfirm=true. EntityForm will handle cross-field validation and exclude
/// confirm entries from submission.
class PasswordField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final int? maxLength;
  final String? groupId; // Pair password/confirm dynamically
  final bool isConfirm; // Mark this instance as a confirm field

  PasswordField({
    required this.fieldKey,
    required this.label,
    required this.hint,
    this.isRequired = false,
    this.maxLength,
    this.groupId,
    this.isConfirm = false,
  });

  @override
  String? Function(String?)? get validator => (value) {
        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';
        }
        // Cross-field match is handled centrally in EntityForm using groupId
        return null;
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    return ModernTextField(
      controller: controller,
      hint: hint,
      maxLength: maxLength,
      keyboardType: TextInputType.visiblePassword,
      obscureText: true,
      onChanged: onChanged != null ? (_) => onChanged() : null,
      validator: validator,
    );
  }

  @override
  Map<String, dynamic>? get customProperties => {
        if (groupId != null) 'groupId': groupId,
        'isConfirm': isConfirm,
        'isPassword': true,
      };
}
