//
//  EmailVC.swift
//  WOKA
//
//  Created by Bilal on 26/04/2024.
//

import UIKit

class EmailVC: UIViewController {
    
    @IBOutlet weak var nextBtn: LocalisedElementsButton!
    @IBOutlet weak var enterEmailTF: UITextField!
    @IBOutlet weak var wokaLogoTopConstriant: NSLayoutConstraint!
    @IBOutlet weak var userType: UITextField!
    @IBOutlet weak var userTypeStack: UIStackView!
    
    @IBOutlet weak var beSafeLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!
    @IBOutlet weak var emailVerifyLabel: LocalisedElementsLabel!
    
    var vm = EmailVM()
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vm.vc = self
        vm.initView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
        
        if self.isMovingFromParent {
            // Back button was pressed
            PersistentStorage.shared.addOthersCount()
        }
        
        enterEmailTF.hideError()
    }
    
    @IBAction func nextBtnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addOthersCount()
        
        /*
         If child registers dont call api to check email, directly hit sendotp and navigate to otp screen
         if parent registers check if the email exist or not and then hit sendotp
         */
        DispatchQueue.main.async { [weak self] in
            guard let self else{return}
            //validate email fiirst
            let emailValidate = EmailValidation(email: enterEmailTF.text!).validate()
            if  emailValidate != .isCorrect{
                enterEmailTF.rightView?.isHidden = false
                enterEmailTF.setError(emailValidate.rawValue.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), show: true)
                Utilities.dismissProgressHUD()
                return
            }
            
            if vm.forgetUsername != nil{
                if userType.text == ""{
                    self.toast(msg: K.ConstantString.userType, time: 1.5)
                    return
                }
                Utilities.startProgressHUD()
                vm.getUserName()
                return
            }
            
            /*
             as per the user type
             */
            Utilities.startProgressHUD()
            switch AuthFunc.shareInstance.userType{
                //if parent verify the email
            case .adult:
                vm.checkEmail()
                // if kid then directly send the otp by checking the format of email
            case .kid:
                vm.sendOTP()
            }

        }
    }
}


// MARK: - TextField Delegate

extension EmailVC : UITextFieldDelegate{
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
        switch textField{
        case enterEmailTF:
            if let rightView = textField.rightView {
                // Hide the right view
                rightView.isHidden = true
                
                // Check if the right view is hidden
                if rightView.isHidden {
                    // If hidden, hide the associated error view
                    if let errorView = errorViews.object(forKey: enterEmailTF) {
                        errorView.isHidden = true
                    }
                }
            }
            
            return ValidatorClass.sharedInstanec.limitCharacter(length: 255,textField, shouldChangeCharactersIn: range, replacementString: string)
        case userType:
            return false
        default:
            return true
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == userType{
            userType.resignFirstResponder()
        }
    }

}


extension UITextField{
    func hideError(){
        if let rightView = self.rightView {
            // Hide the right view
            rightView.isHidden = true
            
            // Check if the right view is hidden
            if rightView.isHidden {
                // If hidden, hide the associated error view
                if let errorView = errorViews.object(forKey: self) {
                    errorView.isHidden = true
                }
            }
        }
    }
}
