import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:otp_timer_button/otp_timer_button.dart';
import 'package:pinput/pinput.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sms_autofill/sms_autofill.dart';
import '../../Controller/Authentication/Authcontroller.dart';
import '../../Helper/Constants/Colorconstants.dart';
import '../../Helper/Logger.dart';
import '../../Helper/toast.dart';
import '../Home/Homeview.dart';
import 'Usercreate/Usercreateview.dart';

class OTPVerification extends StatelessWidget {
  final String otp;
  final int authmode;
  final bool? logInStatus;
  // final int? activeStatus;

  OTPVerification({super.key, this.otp="",this.authmode=0, this.logInStatus});

  final AuthController authController = AuthController();

  final defaultPinTheme = PinTheme(
    width: 60,
    height: 56,
    textStyle: const TextStyle(fontSize: 20, color: Colors.black, fontWeight: FontWeight.w600),
    decoration: BoxDecoration(
      border: Border.all(color:  ColorConstants.primaryColor),
      borderRadius: BorderRadius.circular(10),
    ),
  );


  @override
  Widget build(BuildContext context) {
    return GetBuilder<AuthController>(
      initState: (_) {
        // authController.loginController.reset();
       },
        builder: (controller) {
          return Scaffold(
            backgroundColor: ColorConstants.secondaryColor,
            body: Column(
              children: [
                SizedBox(height: 20,),
                Container(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.elliptical(40, 40),
                        topRight: Radius.elliptical(40, 40)),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 20, vertical: 10),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(
                          height: 20,
                        ),
                        Row(
                          children: [
                            InkWell(
                                onTap: () {
                                  Get.back();

                                   },
                                child: Icon(Icons.arrow_back, color: Colors.grey[700],
                                ),
                            ),
                            SizedBox(width: 10,),
                            Text("Verification",
                                style: TextStyle(
                                    fontSize: 30,
                                    fontFamily: "Lato",
                                    fontWeight: FontWeight.bold,
                                    color: Colors.grey[700])),
                          ],
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                        Text("Please enter your 6 digit One-Time-Password",
                            style: TextStyle(
                                fontWeight: FontWeight.normal,
                                fontFamily: "Lato",
                                color: Colors.grey[600])),
                        const SizedBox(
                          height: 40,
                        ),
                        Center(
                          child: Padding(
                            padding: const EdgeInsets.only(left: 20, right: 20),
                            child: SizedBox(
                              width: 400,
                              child: PinFieldAutoFill(
                                controller: TextEditingController(text: controller.otpController.text), // Correct usage
                                textInputAction: TextInputAction.done,
                                onCodeChanged: (code) async {
                                  SharedPreferences prefs = await SharedPreferences.getInstance();
                                  if (controller.resendOtp == code) {
                                    if (authmode == 1) {
                                      code = controller.resendOtp ?? '';
                                    }
                                    if (logInStatus == true) {
                                      logger.i('Login status : $logInStatus');
                                      prefs.setString('tenantContactNo', controller.contactNo ?? '');
                                      prefs.setString('userFcmToken', controller.userFcmToken ?? '');
                                      Get.to(() =>  HomeView(selectedIndex: 0));
                                    } else {
                                      if (code == controller.resendOtp) {
                                        Get.to(() => CreateUserView(
                                          phNumber: controller.loginPhoneNumberController.text,),
                                        );
                                      }
                                      else{
                                        controller.otpController.clear();
                                        Toast.showToast('Please Enter Valid Otp');
                                      }
                                    }
                                  }
                                },
                                keyboardType:TextInputType.number ,
                                autoFocus: true,
                                onCodeSubmitted: (code){
                                  if(code != controller.resendOtp){
                                    controller.otpController.clear();
                                    logger.i('otpCompleted ${controller.resendOtp}');
                                    Toast.showToast('Please Enter Valid Otp');
                                  }
                                },
                                decoration: BoxLooseDecoration(
                                  textStyle: const TextStyle(fontSize: 20, color: Colors.black),
                                  radius:  const Radius. circular(8.0),
                                  strokeColorBuilder: FixedColorBuilder(Colors.black.withOpacity(0.3)),
                                ),
                              ),
                            ),
                          ),
                          // Padding(
                          //   padding: const EdgeInsets.only(left: 20, right: 20),
                          //   child: Pinput(
                          //     defaultPinTheme: defaultPinTheme,
                          //     pinContentAlignment: Alignment.center,
                          //
                          //     length: 6,
                          //     autofocus: true,
                          //     keyboardType: TextInputType.number,
                          //     androidSmsAutofillMethod:  AndroidSmsAutofillMethod.smsUserConsentApi,
                          //     pinAnimationType: PinAnimationType.fade,
                          //     controller: controller.otpController,
                          //     pinputAutovalidateMode: PinputAutovalidateMode.onSubmit,
                          //     animationDuration: const Duration(milliseconds: 300),
                          //     // Pass it here
                          //     onChanged: (text) async{
                          //       SharedPreferences prefs = await SharedPreferences.getInstance();
                          //       // controller.smsOtp = text;
                          //       // Check if the entered text is a valid phone number
                          //       if (controller.resendOtp == text) {
                          //         if(authmode == 1){
                          //           text = controller.resendOtp??'';
                          //         }
                          //         if(logInStatus == true){
                          //           prefs.setString('tenantContactNo',controller.contactNo ?? '');
                          //           prefs.setString('tenantFcmToken', controller.userFcmToken ?? '');
                          //           logger.i('Inside the login true status');
                          //           Get.to(()=>HomeView(selectedIndex: 0));
                          //         }else{
                          //           logger.i('Inside the login false status');
                          //           Get.to(() => CreateUserView(phNumber: controller.loginPhoneNumberController.text,));
                          //           // showModalBottomSheet(
                          //           //     context: Get.context!,
                          //           //     isDismissible: true,
                          //           //     backgroundColor: ColorConstants.secondaryColor,
                          //           //     shape: const RoundedRectangleBorder(
                          //           //       borderRadius: BorderRadius.only(
                          //           //           topLeft: Radius.circular(20.0), topRight: Radius.circular(20)),
                          //           //     ),
                          //           //     builder: (context) {
                          //           //       return Column(
                          //           //         mainAxisAlignment: MainAxisAlignment.start,
                          //           //         crossAxisAlignment: CrossAxisAlignment.center,
                          //           //         children: [
                          //           //           SizedBox(
                          //           //             height: Get.height * 0.3,
                          //           //             // width: Get.width * 0.10,
                          //           //             child: Padding(
                          //           //               padding: const EdgeInsets.only(bottom: 0),
                          //           //               child: Center(child: Lottie.asset('assets/images/nodatafound.json',)),
                          //           //             ),
                          //           //           ),
                          //           //           const SizedBox(height: 15,),
                          //           //           SizedBox(
                          //           //             width: Get.width*0.85,
                          //           //             child:  Center(
                          //           //               child: Text(
                          //           //                 "Oops, we couldn't find your account. Instead, would you like to create a new one?",
                          //           //                 style: TextStyle(
                          //           //                     fontSize: 18,
                          //           //                     fontFamily: "Inter",
                          //           //                     fontWeight: FontWeight.normal,
                          //           //                     color: ColorConstants.blackColor),
                          //           //                 maxLines: 3,
                          //           //                 textAlign: TextAlign.center,
                          //           //
                          //           //               ),
                          //           //             ),
                          //           //           ),
                          //           //           const Spacer(),
                          //           //           Row(
                          //           //             mainAxisAlignment: MainAxisAlignment.center,
                          //           //             crossAxisAlignment: CrossAxisAlignment.center,
                          //           //             children: [
                          //           //               InkWell(
                          //           //                 onTap: (){
                          //           //                   Get.to(CreateUserView(phNumber: controller.loginPhoneNumberController.text,));
                          //           //                 },
                          //           //                 child: Container(
                          //           //                   height: Get.height*0.06,
                          //           //                   width: Get.width*0.4,
                          //           //                   decoration: BoxDecoration(color: ColorConstants.primaryColor,borderRadius: BorderRadius.circular(10),),
                          //           //                   child:  Center(child: Text('Create Account',style: TextStyle(color: ColorConstants.secondaryColor,fontSize: 16,))),
                          //           //                 ),
                          //           //               ),
                          //           //               const SizedBox(width: 10,),
                          //           //               InkWell(
                          //           //                 onTap: (){
                          //           //                   Get.back();
                          //           //                 },
                          //           //                 child: Container(
                          //           //                   height: Get.height*0.06,
                          //           //                   width: Get.width*0.4,
                          //           //                   decoration: BoxDecoration(color: ColorConstants.primaryColor,borderRadius: BorderRadius.circular(10),),
                          //           //                   child:  Center(child: Text('Cancel',style: TextStyle(color: ColorConstants.secondaryColor,fontSize: 16,))),
                          //           //                 ),
                          //           //               ),
                          //           //             ],
                          //           //           ),
                          //           //           const SizedBox(height: 20,)
                          //           //
                          //           //
                          //           //         ],
                          //           //       );
                          //           //     }
                          //           //     );
                          //         }
                          //       }
                          //     },
                          //     onCompleted:(text){
                          //       if( text != controller.resendOtp){
                          //         controller.otpController.clear();
                          //         print('textonCompleted $text');
                          //         print('otpCompleted ${controller.resendOtp}');
                          //         Toast.showToast('Please Enter Valid Otp');
                          //       }
                          //
                          //     },
                          //
                          //
                          //   ),
                          // ),
                        ),
                        const SizedBox(
                          height: 20,
                        ),
                        controller.authmode == 1 ?Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container()
                          ],
                        ):Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text("Didn't receive the code? ",
                                style: TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontFamily: "Lato",
                                    color: Colors.grey[600])),
                            OtpTimerButton(
                              controller: controller.otpTimerController,
                              onPressed: () {
                                controller.otpTimerController.startTimer();
                                controller.textEditingController.clear();
                                controller.codeSent = true;
                                controller.sendSmsOtp(controller.loginPhoneNumberController.text.trim());
                                controller.update();
                              },
                              text:  Text('Resend Again',style: TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontFamily: "Lato",
                                  color: ColorConstants.primaryColor
                              ),),
                              duration: 60,
                              buttonType: ButtonType.text_button,
                              textColor: ColorConstants.primaryColor,
                              // backgroundColor: ColorConstants.primaryColor,
                            )

                          ],
                        ),
                        const SizedBox(
                          height: 40,
                        ),

                        //submit(),
                      ],
                    ),
                  ),
                ),
                // const Spacer(),
                // Container(
                //   height: Get.height * 0.1,
                //   width: Get.width,
                //   decoration: const BoxDecoration(
                //       image: DecorationImage(
                //           image: AssetImage(
                //             AssetConstants.nearleAppbarBottom,
                //           ),
                //           fit: BoxFit.fill),
                //       // color: ColorConstants.primaryColor,
                //       borderRadius: BorderRadius.only(
                //           bottomLeft: Radius.elliptical(2, 2),
                //           bottomRight: Radius.elliptical(2, 2))),
                // ),
              ],
            ),
          );
        }
    );
  }
}
