//
//  ProfileVM.swift
//  WOKA
//
//  Created by Bilal on 05/06/2024.
//

import UIKit
import Alamofire

class ProfileVM{
    
    weak var vc : ProfileVC!
    var gender = Int()
    
    func initView(){
        vc.boyView.roundCorner(radius: 25)
        vc.girlView.roundCorner(radius: 25)
        vc.fullNameTF.roundCorner()
        vc.emailTF.roundCorner()
        vc.fullNameTF.addRightButton(title: nil, tintColor: UIColor.appColor(.TextDarkBlue)!, btnImage: UIImage(named: "EditPencilIcon"), target: self, action: #selector(editNameClicked))
        
        vc.fullNameTF.delegate = self.vc
        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()
        addTapGesture()
        setUserData()
        hindiEnglishLanguage()
        
        vc.dob.isEnabled = false
        /*
         Depnding on user type limit the date
         */
//        if AuthFunc.shareInstance.getUserType() == 2{
//            vc.dob.minimumDate = Calendar.current.date(byAdding: .year, value: -150, to: Date())
//            vc.dob.maximumDate = Calendar.current.date(byAdding: .year, value: -16, to: Date())
//        }else{
//            vc.dob.minimumDate = Calendar.current.date(byAdding: .year, value: -16, to: Date())
//            vc.dob.maximumDate = Calendar.current.date(byAdding: .year, value: -3, to: Date())
//        }
        
        enableDisableNextBtn(enable: false)
    }
    
    func hindiEnglishLanguage(){
        if AuthFunc.shareInstance.languageSelected == .hindi{
            let loc = Locale(identifier: "hi")
            self.vc.dob.locale = loc
        }
        vc.fullNameTF.placeholder = K.AuthenticationStringConstant.enterChildName.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
    }
    
    @objc func editNameClicked(){
        PersistentStorage.shared.addOthersCount()
        vc.fullNameTF.becomeFirstResponder()
    }
    
    func checkChanges(name : String?){
        guard let data = AuthFunc.shareInstance.userData else{return}
        
        if let name {
            if name.trimmingCharacters(in: .whitespaces).lowercased() != data.fullname?.lowercased() { // || gender == data.gender
                enableDisableNextBtn(enable: true)
            } else{
                enableDisableNextBtn(enable: false)
            }
        }else{
            if let genderData = data.genderData ,let id = genderData.id {
                if gender == id{
                    enableDisableNextBtn(enable: false)
                }else{
                    enableDisableNextBtn(enable: true)
                }
            }else{
                enableDisableNextBtn(enable: true)
            }
        }        
    }
    
    private func enableDisableNextBtn(enable : Bool){
        if enable{
            vc.nextBtn.alpha = 1
            vc.nextBtn.isEnabled = true
        }else{
            vc.nextBtn.alpha = 0.7
            vc.nextBtn.isEnabled = false
        }
    }
    
    func setUserData(){
        guard let data = AuthFunc.shareInstance.userData else{return}
        gender = 0 // default
        if let genderData = data.genderData{
            if genderData.id == 1{ // girl
                gender = genderData.id ?? 1
            }else if genderData.id == 2{ //boy
                gender = genderData.id ?? 2
            }
        }else{
            gender = 0
        }

        vc.fullNameTF.text = data.fullname
        vc.userNameLabel.text = data.username
        vc.emailTF.text = data.email

        if let date = data.birthdate{
            let formattedDate = DateFormatterLib.dateMods(dateStr: date, dateCurrentFormat: .yyyy_MM_dd, dateReturnFormat: .yyyy_MM_dd, stringOrDate: .date).1
            vc.dob.date = formattedDate ?? Date()
        }
        //set the first name as the name
        if let avatar = data.avtarURL{
            //https://wokaland.com/admin/storage/app/public/uploads/avtar/avatar2.png?d=1716889852
            vc.avatarImage.imageURL(avatar,color: .white)
        }
        
        setGender()
    }
    
    private func addTapGesture(){
        vc.boyView.addTapGesture {
            self.boyBtnTapped()
        }
        vc.girlView.addTapGesture {
            self.girlBtnTapped()
        }
    }
    
    // MARK: - Update Profile API CALL

    func updateUserData(){
        let params: Parameters = [
            "fullname": vc.fullNameTF.text!,
            "email": vc.emailTF.text!,
            "gender": gender, //2->boy 1-> girl
        ]
        
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi",
                                     "access-token" : AuthFunc.shareInstance.getAccessToken()]

        Utilities.startProgressHUD(msg: "Updating")
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.SideBarNav.update_profile, method: .post ,parameters: params,headers: headers) {(result : Result<BaseResponseModel<UserDataDM>, 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 ?? "Updated profile", time: 1.5) { [weak self] in
                        guard let self, let data = data.data?.result else{return}
                        AuthFunc.shareInstance.userData?.fullname = vc.fullNameTF.text
                        AuthFunc.shareInstance.userData?.genderData?.id = gender
                        AuthFunc.shareInstance.userData?.genderData?.genderName = (gender == 1 ? "Boy" : "Girl")
                        
//                        AuthFunc.shareInstance.userData = data
                        self.enableDisableNextBtn(enable: false)
//                        self.vc.navigationController?.popViewController(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)
            }
        }
    }
    
    // MARK: - Gender Handler

    func boyBtnTapped() {
        // Apply click effect animation
        PersistentStorage.shared.addOthersCount()
        gender = 2
        
        //check if userdata has same gender
        if let data = AuthFunc.shareInstance.userData {
            if let genderData = data.genderData, let id = genderData.id{
                if id == 2{
                    enableDisableNextBtn(enable: false)
                }else{
                    enableDisableNextBtn(enable: true)
                }
            }else{
                enableDisableNextBtn(enable: true)
            }
        }

        UIView.animate(withDuration: 0.1, animations: {
            self.vc.boyView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        }) { _ in
            UIView.animate(withDuration: 0.1) {
                self.vc.boyView.transform = .identity
                self.setGender()
            }
        }
    }
    
    func girlBtnTapped() {
        PersistentStorage.shared.addOthersCount()
        gender = 1

        //check if userdata has same gender
        if let data = AuthFunc.shareInstance.userData {
            if let genderData = data.genderData, let id = genderData.id{
                if id == 1{
                    enableDisableNextBtn(enable: false)
                }else{
                    enableDisableNextBtn(enable: true)
                }
            }else{
                enableDisableNextBtn(enable: true)
            }
        }
        
        // Apply click effect animation
        UIView.animate(withDuration: 0.1, animations: {
            self.vc.girlView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        }) { _ in
            UIView.animate(withDuration: 0.1) {
                self.vc.girlView.transform = .identity
                self.setGender()
            }
        }
    }
    
    func setGender(){
        let alphaComp = 0.6
        switch gender{
        case 2:
            vc.boyView.backgroundColor = UIColor.white
            vc.girlView.backgroundColor = UIColor.white.withAlphaComponent(alphaComp)
        case 1:
            vc.girlView.backgroundColor = UIColor.white
            vc.boyView.backgroundColor = UIColor.white.withAlphaComponent(alphaComp)
        default:
            vc.girlView.backgroundColor = UIColor.white.withAlphaComponent(alphaComp)
            vc.boyView.backgroundColor = UIColor.white.withAlphaComponent(alphaComp)
        }
    }
}
