import 'dart:async';

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

class Otpscreen extends StatefulWidget {

  final String mobileNumber;

  const Otpscreen({
    super.key,
    required this.mobileNumber
  });

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

}

class _OtpscreenState extends State<Otpscreen>
    with CodeAutoFill {

  String otpCode = "";

  bool isLoading = false;

  int seconds = 30;

  bool canResend = false;
  Timer? _timer;

  @override
  void initState(){

    super.initState();

    listenForCode();

    startTimer();

  }

  void startTimer(){

    _timer?.cancel();

    _timer = Timer.periodic(const Duration(seconds:1),(timer){

      if(!mounted){
        timer.cancel();
        return;
      }

      if(seconds>0){

        setState(() {
          seconds--;
        });

      }else{

        setState(() {
          canResend=true;
        });

        timer.cancel();

      }

    });

  }

  @override
  void codeUpdated(){

    setState((){

      otpCode = code!;

    });

    if(otpCode.length==6){

      verifyOtp();

    }

  }

  Future<void> verifyOtp() async{

    if(isLoading) return;

    if(otpCode.length!=6){

      AppSettings.longFailedToast(
          "Enter 6 digit OTP");

      return;

    }

    setState(()=>isLoading=true);

    AppSettings.preLoaderDialog(context);

    bool isOnline =
    await AppSettings.internetConnectivity();

    if(isOnline){

      var payload={

        "phoneVerificationCode":otpCode,

        "phone":widget.mobileNumber

      };

      bool status =
      await AppSettings.verifyPhn(payload);

      Navigator.pop(context);

      if(status){

        Navigator.pushReplacement(

          context,

          MaterialPageRoute(

            builder:(_)=>
                PasswordTextBoxesScreen(
                    mobileNumber:
                    widget.mobileNumber),

          ),

        );

      }
      else{

        AppSettings.longFailedToast(
            "Invalid OTP");

      }

    }
    else{

      Navigator.pop(context);

      AppSettings.longFailedToast(
          "Check internet");

    }

    setState(()=>isLoading=false);

  }

  String maskNumber(String number){

    return "*******${number.substring(7)}";

  }

  Future<void> resendOtp() async{

    if(!canResend) return;

    var payload={
      "mobileNumbers":widget.mobileNumber
    };

    await AppSettings.getOtp(payload);

    setState((){

      seconds=30;
      canResend=false;

    });

    startTimer();

  }

  @override
  void dispose(){

    _timer?.cancel();   // stop timer
    cancel();           // sms autofill cancel

    super.dispose();

  }

  @override
  Widget build(BuildContext context){

    return Scaffold(

      backgroundColor:Colors.white,

      body:SafeArea(

        child:Padding(

          padding:
          const EdgeInsets.all(24),

          child:Column(

            children:[

              const Spacer(),

              Text(

                "Enter OTP",

                style:fontTextStyle(
                    20,
                    Color(0XFF101214),
                    FontWeight.w700),

              ),

              const SizedBox(height:10),

              Text(

                "Code sent to +91 ${maskNumber(widget.mobileNumber)}",

                style:fontTextStyle(
                    12,
                    Color(0XFF7E7F80),
                    FontWeight.w400),

              ),

              const SizedBox(height:40),

              /// OTP BOX
              PinFieldAutoFill(

                codeLength:6,

                currentCode:otpCode,

                onCodeChanged:(code){

                  otpCode=code??"";

                },

                decoration:

                BoxLooseDecoration(

                  radius:
                  const Radius.circular(8),

                  strokeColorBuilder:

                  FixedColorBuilder(
                      primaryColor),

                  textStyle:

                  fontTextStyle(
                      18,
                      Color(0XFF101214),
                      FontWeight.w600),

                ),

              ),

              const SizedBox(height:30),

              /// TIMER
              canResend

                  ? GestureDetector(

                onTap:resendOtp,

                child:Text(

                  "Resend OTP",

                  style:fontTextStyle(
                      14,
                      primaryColor,
                      FontWeight.w600),

                ),

              )

                  : Text(

                "Resend in 00:$seconds",

                style:fontTextStyle(
                    12,
                    Color(0XFF7E7F80),
                    FontWeight.w500),

              ),

              const SizedBox(height:40),

              /// BUTTON
              SizedBox(

                width:double.infinity,

                height:55,

                child:ElevatedButton(

                  style:
                  ElevatedButton.styleFrom(

                    backgroundColor:
                    primaryColor,

                    shape:
                    RoundedRectangleBorder(

                      borderRadius:
                      BorderRadius.circular(24),

                    ),

                  ),

                  onPressed:verifyOtp,

                  child:isLoading

                      ? const CircularProgressIndicator(
                      color:Colors.white)

                      :Text(

                    "Verify",

                    style:fontTextStyle(
                        16,
                        Colors.white,
                        FontWeight.w600),

                  ),

                ),

              ),

              const Spacer(),

            ],

          ),

        ),

      ),

    );

  }

}