import 'package:flutter/material.dart';
import 'package:supplier_new/signup/password_textbox_screen.dart';

import '../common/settings.dart';

class Otpscreen extends StatefulWidget {
  var mobileNumber;
  Otpscreen({
    this.mobileNumber
  });

  @override
  State<Otpscreen> createState() => _OtpscreenState();
}

class _OtpscreenState extends State<Otpscreen> {
  final List<TextEditingController> _controllers = List.generate(6, (index) => TextEditingController());
  final FocusNode _focusNode = FocusNode();

  @override
  void dispose() {
    _controllers.forEach((controller) => controller.dispose());
    _focusNode.dispose();
    super.dispose();
  }

  void _submitOtp() {
    final otp = _controllers.map((controller) => controller.text).join();
    print("Entered OTP: $otp");
    // Add OTP validation or submission logic here
  }


  String maskMobileNumber(String number) {
    if (number.length < 3) return number; // Handle invalid numbers
    final stars = '*' * (number.length - 3);
    final lastThree = number.substring(number.length - 3);
    return '$stars$lastThree';
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(children: <Widget>[
          /*Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage("images/backgroundimage.png"),
                fit: BoxFit.cover,
              ),
            ),
          ),*/
          GestureDetector(
              onTap: () {
                FocusScope.of(context).requestFocus(new FocusNode());
              },
              child: SafeArea(
                  child: SingleChildScrollView(
                      child: Padding(
                        padding: EdgeInsets.fromLTRB(24, 0, 24, 0),
                        child: Column(children: <Widget>[
                          SizedBox(height:MediaQuery.of(context).size.height * .2,),

                          Container(

                            child:  Text(
                              'Enter confirmation code',
                              style: fontTextStyle(16,Color(0XFF101214),FontWeight.w800),
                            ),
                          ),
                          SizedBox(height:MediaQuery.of(context).size.height * .02,),
                          Container(

                            child:  Text(
                              'A 6-digit code was sent to +91${maskMobileNumber(widget.mobileNumber)}',
                              style: fontTextStyle(12,Color(0XFF7E7F80),FontWeight.w400),
                            ),
                          ),
                          SizedBox(height:MediaQuery.of(context).size.height * .040,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: List.generate(6, (index) {
                              return SizedBox(
                                width: 50,
                                child: TextFormField(
                                  cursorColor:primaryColor,
                                  controller: _controllers[index],
                                  focusNode: index == 0 ? _focusNode : null,
                                  maxLength: 1,
                                  textAlign: TextAlign.center,
                                  style:  fontTextStyle(14,Color(0XFF101214),FontWeight.w400),
                                  keyboardType: TextInputType.number,
                                  decoration: textFormFieldDecoration(Icons.ice_skating, ''),
                                  onChanged: (value) {
                                    if (value.isNotEmpty && index < 5) {
                                      FocusScope.of(context).nextFocus();
                                    } else if (value.isEmpty && index > 0) {
                                      FocusScope.of(context).previousFocus();
                                    }
                                  },
                                ),
                              );
                            }),
                          ),

                          SizedBox(height:MediaQuery.of(context).size.height * .08,),
                          GestureDetector(
                            onTap: (){

                            },
                            child: Text('Resend code',style:fontTextStyle(12,Color(0XFF1D7AFC),FontWeight.w600),),
                          ),
                          SizedBox(height:MediaQuery.of(context).size.height * .024,),
                          Container(
                              width: double.infinity,
                              height: MediaQuery.of(context).size.height * .06,
                              child: ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  foregroundColor: Colors.white,
                                  backgroundColor: primaryColor,
                                ),
                                onPressed: () async{
                                AppSettings.preLoaderDialog(context);

                                bool isOnline = await AppSettings.internetConnectivity();
                                if(isOnline){
                                  final otp = _controllers.map((controller) => controller.text).join();

                                  if(otp.length==6){
                                    var phoneVerifyPayload = new Map<String, dynamic>();

                                    phoneVerifyPayload["phoneVerificationCode"] = otp.toString();
                                    phoneVerifyPayload["phone"] = widget.mobileNumber.toString();

                                    bool verifyPhnStatus = await AppSettings.verifyPhn(phoneVerifyPayload);
                                    if (verifyPhnStatus) {
                                      Navigator.of(context, rootNavigator: true).pop();
                                      //AppSettings.longSuccessToast("User SignUp Successfully");
                                      Navigator.push(
                                          context,
                                          new MaterialPageRoute(
                                              builder: (__) => new PasswordTextBoxesScreen(mobileNumber: widget.mobileNumber,)));
                                      /* await Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (context) => const Login()),
                                        );*/

                                    } else {
                                      Navigator.of(context, rootNavigator: true).pop();
                                      AppSettings.longFailedToast("Phone verification failed");
                                    }
                                  }
                                  else{
                                    Navigator.of(context, rootNavigator: true).pop();
                                    AppSettings.longFailedToast("Please enter 6 digit otp code");
                                  }


                                }
                                else{
                                  Navigator.of(context,rootNavigator: true).pop();
                                  AppSettings.longFailedToast("Please Check internet");
                                }






                                },
                                child: Text('Continue',style:fontTextStyle(12,Color(0XFFFFFFFF),FontWeight.w600),),
                              )),

                        ]),
                      )))),
        ]));
  }
}
