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

import UIKit
import Alamofire

class EmailVM{
    
    weak var vc : EmailVC!
    
    var forgetUsername : Bool?
    let dropDownModule = DropDown()
    var dataSource = [String]()
    
    func initView(){
        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()
        vc.enterEmailTF.roundCorner()
        vc.userType.roundCorner()
        
        // Set up text field delegate
        vc.enterEmailTF.delegate = vc.self
        vc.userType.delegate = vc.self
        
        vc.enterEmailTF.addRightButton(title: "", tintColor: UIColor.red, btnImage: UIImage(systemName: "exclamationmark.circle.fill"), target: self, action: #selector(validationIconTapped))
        vc.enterEmailTF.rightView?.isHidden = true
        
        self.vc.wokaLogoTopConstriant.constant = CheckPhoneHomeBtnOrNotch.shareInstance.topConstriant()
        
        //Checking UserType to update the text
        if AuthFunc.shareInstance.userType == .adult{
            vc.enterEmailTF.placeholder = K.AuthenticationStringConstant.enterEmail.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.emailVerifyLabel.isHidden = true
            vc.beSafeLabel.text = K.AuthenticationStringConstant.safeAbove.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.emailLabel.text = K.AuthenticationStringConstant.emailAbove.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        }else{
            vc.enterEmailTF.placeholder = K.AuthenticationStringConstant.enterParentsEmail.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.beSafeLabel.text = K.AuthenticationStringConstant.safeBelow.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.emailLabel.text = K.AuthenticationStringConstant.emailBelow.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        }        
        
        
        if forgetUsername != nil{ // if user is coming from forget username
            vc.userTypeStack.isHidden = false
            vc.beSafeLabel.text = K.AuthenticationStringConstant.forgotUsername.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.userType.delegate = self.vc
            dataSource = ["I am above 16 years" , "I am below 16 years"]
            vc.userType.addRightButton(title: "", tintColor: UIColor.appColor(.TextDarkBlue)!, btnImage: UIImage(named: "SupportBottomArrow"),rightPadding: 15, target: self, action: #selector(dropDownTapped))
            initDropDown()
        }
    }
    
    // this func will initialize the dropdown menu
    func initDropDown(){
        dropDownModule.anchorView = vc.userType
        dropDownModule.dataSource = dataSource
        dropDownModule.cornerRadius = 10
        dropDownModule.bottomOffset = CGPoint(x: 0, y:(dropDownModule.anchorView?.plainView.bounds.height)!)
        dropDownModule.topOffset = CGPoint(x: 0, y:-(dropDownModule.anchorView?.plainView.bounds.height)!)
        dropDownModule.direction = .bottom
        dropDownModule.textFont = FontCustom.shareInstance.customFont(fontName: .Exo2_Medium, size: 16)
        dropDownModule.shadowColor = UIColor.appColor(.TextDarkBlue)!
        dropDownModule.backgroundColor = .white
        dropDownModule.shadowOffset = CGSize(width: 0, height: 1)
        dropDownModule.separatorColor = UIColor.lightGray
        dropDownModule.width = vc.userType.frame.width - 40
        dropDownModule.selectionBackgroundColor = UIColor.appColor(.TextDarkBlue)!
        dropDownModule.selectedTextColor = UIColor.white
        dropDownModule.selectionAction = { [weak self] (index: Int, item: String) in
            self?.vc.userType.text = item
        }
    }
    
    @objc func dropDownTapped(){
        self.vc.enterEmailTF.resignFirstResponder()
        self.dropDownModule.show()
    }
    
    // Function to handle tap on validation icon
    @objc func validationIconTapped() {
        let errorView = errorViews.object(forKey: vc.enterEmailTF)
        if let errorView = errorView {
            errorView.isHidden.toggle()
        }
    }
    
    // MARK: - After all checks do the api call

    func getUserName(){
        let params: Parameters = ["email": vc.enterEmailTF.text!,
            "user_type": dropDownModule.indexForSelectedRow == 0 ? 2 : 1]
        let header : HTTPHeaders = ["device-id" : AuthFunc.shareInstance.getDeviceUUID(),
                                    "Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]
        
        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.forgot_username, method: .post ,parameters: params, headers: header) {(result : Result<BaseResponseModel<[UserNameDM]>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let dataResult = data.data else{return}
                    let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
                    let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.usernameCheckVC) as! UsernameCheckVC
                    vc.userData = dataResult
                    self.vc.navigationController?.pushViewController(vc, animated: true)
                default:
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription, time: 2)
            }
        }
    }
    
    func checkEmail(){
        let params: Parameters = [
            "email": vc.enterEmailTF.text!,
            "user_type": "2"
        ]
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]

        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.check_exist_email, method: .post ,parameters: params,headers: headers) {(result : Result<BaseResponseModel<UserDataDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0:
                    /*
                     user exists
                     */
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    /*
                     Create New Account
                     Send OTP
                     Start updating the user Reg data
                     */
                    
                    self.sendOTP()
                default:
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    func sendOTP(){
        
        let params: Parameters = [
            "email": vc.enterEmailTF.text!,
            "user_type": AuthFunc.shareInstance.userType == .adult ? "2" :"1"
        ]
        
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]
        Utilities.startProgressHUD()
        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()
                    /*
                     Set both guardian and normal email
                     */
                    AuthFunc.shareInstance.regData.email = self.vc.enterEmailTF.text!
                    if AuthFunc.shareInstance.userType == .kid{
                        AuthFunc.shareInstance.regData.guardian_email = self.vc.enterEmailTF.text!
                    }
                    
                    guard let uniqueString = data.data?.unique_string else{
                        self.vc.toast(msg: K.ConstantString.unRecognised , time: 1)
                        return
                    }
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 1) {
                        self.navigateToOTP(validateString: uniqueString)
                    }
                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)
            }
        }
    }
    
    private func navigateToOTP(validateString : String){
        let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.oTPVC) as! OTPVC
        vc.vm.validateString = validateString
        self.vc.navigationController?.pushViewController(vc, animated: true)
    }
}
