//
//  OTPVM.swift
//  WOKA
//
//  Created by MacBook Pro on 29/04/24.
//

import UIKit
import Alamofire

class OTPVM{
    
    weak var vc : OTPVC!
    var validateString = String()
    
    //if user name is not null then the user has forgot the pass.
    var userName : String?
    
    var timer: Timer?
    var remainingTime: TimeInterval = 10 * 60 // 10 minutes in seconds

    func initView(){
        startTimer()
        let color1 = #colorLiteral(red: 0.144693464, green: 0.1426281333, blue: 0.6686832905, alpha: 1)
        let color2 = #colorLiteral(red: 0.6901960784, green: 0.2745098039, blue: 0.7568627451, alpha: 1)
        vc.nextBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        vc.nextBtn.roundCorner()
        
        self.vc.wokaLogoTopConstriant.constant = CheckPhoneHomeBtnOrNotch.shareInstance.topConstriant()
        tfMod(textField: [vc.tf1, vc.tf2, vc.tf3, vc.tf4])
        
        if AuthFunc.shareInstance.userType == .adult{
            vc.codeSentLabel.text = "Please Get the OTP Sent to Your  Email".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.enterCodeLabel.text = "PLEASE ENTER THE OTP".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.requestThemLabel.text = "Don’t forget to check your JUNK/SPAM folder".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        }else{
            vc.codeSentLabel.text = "Please Get the Code Sent to Your Parent’s Email".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.enterCodeLabel.text = "PLEASE ENTER THE CODE".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.requestThemLabel.text = "Request them for the verfication code to activate your account".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        }
    }
    
    private func tfMod(textField : [UITextField]){
        for i in textField{
            i.roundCorner(radius: i.frame.height / 2)
            i.delegate = vc.self
            i.textContentType = .oneTimeCode
            i.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged)
        }
    }
    
    // MARK: - Timer Handling
    
    func startTimer() {
        vc.resendOTPBtn.isHidden = true
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc func updateTimer() {
        if remainingTime > 0 {
            remainingTime -= 1
            updateTimerLabel()
        } else {
            timer?.invalidate()
            vc.resendOTPBtn.isHidden = false
            vc.otpValidTillLabel.isHidden = true
            // Timer ended, perform any action you want here
        }
    }
    
    func updateTimerLabel() {
        let minutes = Int(remainingTime) / 60
        let seconds = Int(remainingTime) % 60
        let timeString = String(format: "%02d:%02d", minutes, seconds)
        vc.otpValidTillLabel.isHidden = false
        let text1 = "OTP is valid for".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        let text2 = "Min".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        vc.otpValidTillLabel.text = text1 + "  \(timeString)  " + text2
    }
    
    // MARK: - OTP Validation
    
    func validateOTP(){
        let otp = vc.tf1.text! + vc.tf2.text! + vc.tf3.text! + vc.tf4.text!
        
        if otp.count != 4{
            self.vc.toast(msg: "Please enter code!".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), time: 1.8)
            return
        }
        
        if let userName{
            validateForgotPassOTP(otp: otp, userName: userName)
        }else{
            validateNormalOTP(otp: otp)
        }
        
    }
    
    func validateNormalOTP(otp : String){
        let params: Parameters = [
            "unique_string":  validateString,
            "otp": otp
        ]
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]

        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.validate_otp, method: .post ,parameters: params,headers: headers) {(result : Result<BaseResponseModel<UserEmailVerifyDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0: // some error
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1: // Success
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 1) {
                        self.navigate()
                    }
                default:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: K.ConstantString.unRecognised , time: 1)
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    func validateForgotPassOTP(otp : String, userName : String){
        let params: Parameters = [
            "username": userName,
            "otp": otp
        ]
        
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]

        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.forgot_password_verify_otp, method: .post ,parameters: params,headers: headers) {(result : Result<BaseResponseModel<ForgotPassDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0: // some error
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1: // Success
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 1) {
                        let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
                        let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.newPasswordVC) as! NewPasswordVC
                        vc.vm.userName = userName
                        self.vc.navigationController?.pushViewController(vc, animated: true)
                    }
                default:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: K.ConstantString.unRecognised , time: 1)
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    func resendOTP(){
        let params: Parameters = [
            "email": AuthFunc.shareInstance.regData.email!,
            "user_type": AuthFunc.shareInstance.userType == .adult ? "2" :"1"
        ]
        
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]
        Utilities.startProgressHUD(msg: "Sending OTP...")
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.user_email_verification, method: .post ,parameters: params,headers: headers) {(result : Result<BaseResponseModel<UserEmailVerifyDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0: // some error
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1: // Success
                    Utilities.dismissProgressHUD()
                    if let string = data.data?.unique_string{
                        self.validateString = string
                    }
                    self.emptyTF(tf: [self.vc.tf1,self.vc.tf2,self.vc.tf3,self.vc.tf4])
                    self.startTimer()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                default:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: K.ConstantString.unRecognised , time: 1)
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    func getLinkedChild(){
        let params: Parameters = [
            "email": AuthFunc.shareInstance.regData.email!,
        ]
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]

        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.get_linked_child, method: .post ,parameters: params, headers: headers) {(result : Result<BaseResponseModel<LinkedChildDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0: // some error
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                    let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
                    let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.userDetailsRegisterVC) as! UserDetailsRegisterVC
                    self.vc.navigationController?.pushViewController(vc, animated: true)
                case 1: // Success
                    Utilities.dismissProgressHUD()
                    guard let result = data.data?.result else{
                        self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                        return
                    }
                    
                    let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
                    let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.linkedChildVC) as! LinkedChildVC
                    vc.vm.linkedChilds = result
                    self.vc.navigationController?.pushViewController(vc, animated: true)
                default:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: K.ConstantString.unRecognised , time: 1)
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    func navigate(){
        /*
         if parent is doing registeration please check if he has any child linked
         */
        if AuthFunc.shareInstance.userType == .adult{
            self.getLinkedChild()
            return
        }
        
        switch self.vc.navigateCheck{
        case .newPass:
            let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
            let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.newPasswordVC) as! NewPasswordVC
            self.vc.navigationController?.pushViewController(vc, animated: true)
        case .registeration:
            let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
            let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.userDetailsRegisterVC) as! UserDetailsRegisterVC
            self.vc.navigationController?.pushViewController(vc, animated: true)
        }
    }

    // MARK: - TextField OTp handling

    func textFieldDidChange(_ textField: UITextField, otpCode: String) {
          if textField.textContentType == UITextContentType.oneTimeCode{
              //here split the text to your four text fields
              if otpCode.count == 4, Int(otpCode) != nil {
                  vc.tf1.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 0)])
                  vc.tf2.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 1)])
                  vc.tf3.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 2)])
                  vc.tf4.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 3)])
                  
//                  let textFields = [vc.tf1,vc.tf2,vc.tf3,vc.tf4]
//                  for i in 0..<textFields.count{
//                      textFields[i].layer.borderColor = UIColor.GREEN_COLOR.cgColor
//                  }
              } else {
                  textField.text = ""
              }
              textField.resignFirstResponder()
          }
    }
    
    func emptyTF(tf : [UITextField]){
        DispatchQueue.main.async {
            for i in tf{
                i.text = ""
            }
        }
    }
    
    @objc func textFieldDidChange(textField: UITextField){
        let text = textField.text
        if  text?.count == 1 {
            switch textField{
            case vc.tf1:
                vc.tf2.becomeFirstResponder()
            case vc.tf2:
                vc.tf3.becomeFirstResponder()
            case vc.tf3:
                vc.tf4.becomeFirstResponder()
            case vc.tf4:
                vc.tf4.resignFirstResponder()
            default:
                break
            }
        }
        if  text?.count == 0 {
            switch textField{
            case vc.tf1:
                vc.tf1.becomeFirstResponder()
            case vc.tf2:
                vc.tf1.becomeFirstResponder()
            case vc.tf3:
                vc.tf2.becomeFirstResponder()
            case vc.tf4:
                vc.tf3.becomeFirstResponder()
            default:
                break
            }
        }
    }
}
