//
//  LoginVC.swift
//  WOKA
//
//  Created by Bilal on 03/05/2024.
//

import UIKit

class LoginVC: UIViewController {

    @IBOutlet weak var loginBtn: LocalisedElementsButton!
    @IBOutlet weak var createAccountBtn: LocalisedElementsButton!
    @IBOutlet weak var userNameTF: TextFieldShadow!
    @IBOutlet weak var passwordTF: TextFieldShadow!
    @IBOutlet weak var passwordStack: UIStackView!
    @IBOutlet weak var passwordEyeBtn: UIButton!
    
    var vm = LoginVM()
    
    // MARK: - View LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vm.vc = self
        vm.initView()
        
//        self.userNameTF.text = "child1"
//        self.passwordTF.text = "Admin@123"
    }
    
    override func viewDidAppear(_ animated: Bool) {
        /*
         if user has selected the username from forgot username screen update it here.
         */
        if let username = K.GVar.selectedUsername{
            self.userNameTF.text = username
            K.GVar.selectedUsername = nil
        }
    }
    
    @IBAction func loginBtnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addOthersCount()
        guard let userName = userNameTF.text?.trimmingCharacters(in: .whitespaces) , let pass = passwordTF.text?.trimmingCharacters(in: .whitespaces) else{return}
        
        /*
         Check for userName
         */
        if userName.count == 0{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            vcPush.contentLabel = K.ConstantString.enterUserName.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.mainTitleText = "Username".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        
        if userName.count < 2{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            vcPush.contentLabel = "Username is too short.".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.mainTitleText = "Username".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        
        /*
         Check for password
         */
        if pass.count == 0{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            
            vcPush.contentLabel = "Enter your password".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.mainTitleText = "Password".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            
//                vcPush.onDoneBlock = { isDone in }
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        
        if pass.count < 6{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            
            vcPush.contentLabel = "Password is too short.".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.mainTitleText = "Password".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            
//                vcPush.onDoneBlock = { isDone in }
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        vm.loginUser()
    }
    
    @IBAction func createAccountBtnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addOthersCount()
        let sb = UIStoryboard(name: K.StoryBoard.main, bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.OnBoarding.selectAgeVC) as! SelectAgeVC
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func continueGuestBtnTapped(_ sender: UIButton) {
        PersistentStorage.shared.addOthersCount()
        vm.guestLogin()
    }
    
    @IBAction func forgotPasswordBtnTapped(_ sender: UIButton) {
        PersistentStorage.shared.addOthersCount()
        let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.resetPassUserNameVC) as! ResetPassUserNameVC
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func forgotUsername(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addOthersCount()
        let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.emailVC) as! EmailVC
        vc.vm.forgetUsername = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
}


// MARK: - Textfield Delegate

extension LoginVC : UITextFieldDelegate{
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch textField{
        // username - 2,16 , password - 6,16
        case userNameTF:
            if !string.numberAndCharacterAndSpecialChar(){return false}
            return ValidatorClass.sharedInstanec.limitCharacter(length: 16,textField, shouldChangeCharactersIn: range, replacementString: string)
        case passwordTF:
            let currentString = (textField.text ?? "") as NSString
            let newString = currentString.replacingCharacters(in: range, with: string)
            newString.count == 0 ? (textField.rightView?.isHidden = true) : (textField.rightView?.isHidden = false)
            return ValidatorClass.sharedInstanec.limitCharacter(length: 16,textField, shouldChangeCharactersIn: range, replacementString: string)
        default:
            return true
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        switch textField{
        case userNameTF:
            passwordTF.becomeFirstResponder()
        case passwordTF:
            self.view.endEditing(true)
        default:
            break
        }
        return true
    }
}
