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

class LinkPhoneCodeInput extends StatefulWidget {
  const LinkPhoneCodeInput({
    super.key,
    this.length = 6,
    required this.onCodeChanged,
  });

  final int length;
  final ValueChanged<String> onCodeChanged;

  @override
  State<LinkPhoneCodeInput> createState() => _LinkPhoneCodeInputState();
}

class _LinkPhoneCodeInputState extends State<LinkPhoneCodeInput> {
  late final List<TextEditingController> _controllers;
  late final List<FocusNode> _focusNodes;

  @override
  void initState() {
    super.initState();
    _controllers = List<TextEditingController>.generate(
      widget.length,
      (_) => TextEditingController(),
    );
    _focusNodes = List<FocusNode>.generate(widget.length, (_) => FocusNode());
  }

  @override
  void dispose() {
    for (final controller in _controllers) {
      controller.dispose();
    }
    for (final node in _focusNodes) {
      node.dispose();
    }
    super.dispose();
  }

  void _onDigitChanged(int index, String value) {
    if (value.length > 1) {
      final single = value.characters.last;
      _controllers[index].text = single;
      _controllers[index].selection = TextSelection.fromPosition(
        TextPosition(offset: single.length),
      );
    }

    if (value.isNotEmpty && index < widget.length - 1) {
      _focusNodes[index + 1].requestFocus();
    } else if (value.isEmpty && index > 0) {
      _focusNodes[index - 1].requestFocus();
    }

    final code = _controllers.map((c) => c.text).join();
    widget.onCodeChanged(code);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      spacing: 8,
      children: List<Widget>.generate(widget.length, (int i) {
        return Expanded(
          child: TextField(
            controller: _controllers[i],
            focusNode: _focusNodes[i],
            keyboardType: TextInputType.number,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly],
            textAlign: TextAlign.center,
            decoration: const InputDecoration(
              hintText: '0',
              counterText: '',
              border: OutlineInputBorder(),
            ),
            maxLength: 1,
            onChanged: (value) => _onDigitChanged(i, value),
          ),
        );
      }),
    );
  }
}
