import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class PinInputField extends StatelessWidget {
  final TextEditingController controller;
  final int length;
  final FormFieldValidator<String>? validator;

  const PinInputField({
    super.key,
    required this.controller,
    this.length = 6,
    this.validator,
  });

  @override
  Widget build(BuildContext context) {
    return FormField<String>(
      validator: validator,
      builder: (FormFieldState<String> state) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              controller: controller,
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(length),
              ],
              obscureText: true,
              obscuringCharacter: '*',
              decoration: InputDecoration(
                border: const OutlineInputBorder(),
                labelText: 'Enter $length-digit PIN',
                counterText: '', // Hide the counter
              ),
              onChanged: (value) {
                state.didChange(value);
              },
            ),
            if (state.hasError)
              Padding(
                padding: const EdgeInsets.only(top: 8.0, left: 12.0),
                child: Text(
                  state.errorText!,
                  style: TextStyle(
                    color: Theme.of(context).colorScheme.error,
                    fontSize: 12,
                  ),
                ),
              ),
          ],
        );
      },
    );
  }
}
