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

class OTPTextField extends StatefulWidget {
  final int length;
  final ValueChanged<String> onSubmitted;

  const OTPTextField({
    super.key,
    required this.length,
    required this.onSubmitted,
  });

  @override
  _OTPTextFieldState createState() => _OTPTextFieldState();
}

class _OTPTextFieldState extends State<OTPTextField> {
  late List<FocusNode> focusNodes;
  late List<TextEditingController> controllers;

  @override
  void initState() {
    super.initState();
    focusNodes = List.generate(widget.length, (index) => FocusNode());
    controllers =
        List.generate(widget.length, (index) => TextEditingController());
  }

  @override
  void dispose() {
    for (var controller in controllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.ltr,
      child: Row(
        children: List.generate(
          widget.length,
          (index) => Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 7),
              child: Center(
                child: TextFormField(
                    cursorColor: config.ui.mainGreen,
                    style: const TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.bold,
                        fontSize: 20),
                    controller: controllers[index],
                    focusNode: focusNodes[index],
                    keyboardType: TextInputType.number,
                    textInputAction: index < widget.length - 1
                        ? TextInputAction.next
                        : TextInputAction.done,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(RegExp('[0-9]'))
                    ],
                    textAlign:
                        TextAlign.center, // Center the text within the box.
                    onChanged: (value) {
                      if (value.length == 1) {
                        if (index < widget.length - 1) {
                          focusNodes[index].unfocus();
                          FocusScope.of(context)
                              .requestFocus(focusNodes[index + 1]);
                        } else {
                          focusNodes[index].unfocus();
                        }
                      } else if (value.isEmpty) {
                        if (index > 0) {
                          focusNodes[index].unfocus();
                          FocusScope.of(context)
                              .requestFocus(focusNodes[index - 1]);
                        }
                      }
                      if (isInputValid()) {
                        String otp = controllers
                            .map((controller) => controller.text)
                            .join();
                        widget.onSubmitted(otp);
                      }
                    },
                    decoration: InputDecoration(
                        fillColor: Colors.white.withOpacity(.5),
                        filled: true,
                        border: OutlineInputBorder(
                          borderRadius:
                              BorderRadius.circular(12), // Add border radius
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                          borderSide: BorderSide(
                            color: config
                                .ui.mainGreen, // Change focus color to yellow
                          ),
                        ))),
              ),
            ),
          ),
        ),
      ),
    );
  }

  bool isInputValid() {
    return controllers.every((controller) => controller.text.length == 1);
  }
}
