import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:timer_count_down/timer_controller.dart';

import '../../../core/config/server_response.dart';
import '../../../core/constants/app_contants.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../core/enums/request_constants.dart';
import '../../../core/utils/SessionCache.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../models/AuthenticationRequest.dart';
import '../../../models/LoginResponseModel.dart';
import '../../../models/VerifyLoginOtpRequest.dart';
import '../../../models/resend_ot_login_model.dart';
import '../../../routes/app_pages.dart';
import '../../user_profile/controllers/user_profile_controller.dart';


class OTPScreenController extends GetxController {
  final AppRepositories repository = Get.find<AppRepositories>();
  BuildContext context = Get.context as BuildContext;
  TextEditingController pinPutController = TextEditingController();
  AuthenticationRequest firstStepData = AuthenticationRequest.empty();

  RxBool isResend = false.obs;
  bool loginUsingFingerPrint = false;
  CountdownController countdownController = CountdownController(autoStart: true);

  @override
  Future<void> onReady() async {
    super.onReady();
    var arguments = Get.arguments;
    firstStepData = (arguments != null ? arguments[AppConstants.SIGN_UP_FIRST_STEP_DATA] ?? AuthenticationRequest.empty() : AuthenticationRequest.empty());
    loginUsingFingerPrint = arguments[1] ?? false;
    pinPutController.text = "";
  }

  Future<void> validatePinAndNavigate() async {
    if (pinPutController.text.isEmpty) {
      Toasty.error("Please input and then proceed");
      return;
    }
    if (pinPutController.text.length != 6) {
      Toasty.error("Please enter a valid OTP");
      return;
    }

    VerifyLoginOtpRequest request = VerifyLoginOtpRequest(
      email: firstStepData.email,
      password: firstStepData.password,
      obpPincode: pinPutController.text,
      channelCode: RequestConstants.channelCode,
      porOrgacode: RequestConstants.porOrgacode,
    );

    ServerResponse response = await repository.validateLoginPin(request);
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }

    LoginResponseModel model = LoginResponseModel.fromJson(response.response);

    SessionCache.instance.userInfo.name = model.name.toString();
    SessionCache.instance.userInfo.cmpCuststatus = model.cmpCuststatus.toString();
    SessionCache.instance.userInfo.plcLocalcode = RequestConstants.plcLocacode.toString();
    SessionCache.instance.userInfo.cmpCustlastlogin = model.cmpCustlastlogin.toString();
    SessionCache.instance.userInfo.cmpCustcode = model.cmpCustcode.toString();
    SessionCache.instance.userInfo.jwtToken = model.jwtToken.toString();
    SessionCache.instance.userInfo.cmpUserId = firstStepData.email;
    SessionCache.instance.userInfo.cmpCustpassword = firstStepData.password;
    SessionCache.instance.userInfo.channelCode = RequestConstants.channelCode;
    SessionCache.instance.userInfo.porOrgacode = RequestConstants.porOrgacode;
    SessionCache.instance.userInfo.pctCstycode = RequestConstants.pctCstycode;
    SessionCache.instance.userInfo.isKycVerified = model.isKycVerified;
    SessionCache.instance.userInfo.isTranPinSet = model.isTranPinSet;
    UserProfileController.cmpCustImage.value = model.cmpCustImage??"";

    if (!SessionCache.instance.userInfo.isTranPinSet) {
      Get.offAndToNamed(Routes.CREATE_TRANSACTION_PIN);
      return;
    }
    Get.offAndToNamed(Routes.DASHBOARD_SCREEN,
      arguments: {'loginUsingFingerPrint': loginUsingFingerPrint});
  }

  ///uco/changeTransactionPin
  void resenOtp() async {
    if (!isResend.value) {
      Fluttertoast.showToast(msg: "Please wait for 1 minute");
      return;
    }

    var responce = await repository.resentOtpLoginSignUp(
      ResendOtpLoginModel(
        userRole: 'USER',
        channelCode: RequestConstants.channelCode,
        porOrgacode: RequestConstants.porOrgacode,
        email: firstStepData.email,
        isOtpRequire: false,
        phone: '',
        pinType: 'C_TRANPIN',
        username: firstStepData.email,
      ),
    );

    if (responce.isError) {
      Fluttertoast.showToast(msg: responce.errorMsg);
      return;
    }

    isResend.value = false;

    countdownController.setOnRestart(
      () {},
    );

    countdownController.restart();

    Fluttertoast.showToast(msg: "OTP send successfully");
  }

  void updateResend(bool send) {
    isResend.value = send;
  }
}

String getTime(int totalSeconds) {
  int minutes = totalSeconds ~/ 60;
  int seconds = totalSeconds % 60;
  return '$minutes : $seconds';
}
