//
//  UserIntrestVM.swift
//  WOKA
//
//  Created by MacBook Pro on 30/04/24.
//

import UIKit
import Alamofire

class UserIntrestVM{
    
    weak var vc : UserIntrestVC!
    var intrestTopics = [IntrestTopicDM.Result]()
    
    // This will become true only if parent is adding child
    var createChildAccount : Bool?
    
    func initView(){
        if AuthFunc.shareInstance.languageSelected == .hindi{
            let loc = Locale(identifier: "hi")
            self.vc.datePicker.locale = loc
        }

        //set default gender to 0
        AuthFunc.shareInstance.regData.gender = 0
        
        /*
         Setting the minimum and maximum date as per user type
         */
        if AuthFunc.shareInstance.userType == .adult && createChildAccount == false{
            vc.datePicker.minimumDate = Calendar.current.date(byAdding: .year, value: -150, to: Date())
            vc.datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: -16, to: Date())
            vc.boyText.text = "MALE".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.GirlText.text = "FEMALE".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            
            /*
             If user type is adult then no need to show intrest
             */
            self.vc.intrestStackView.isHidden = true
            self.vc.selectAsManyYouWant.isHidden = true
        }else{
            vc.datePicker.minimumDate = Calendar.current.date(byAdding: .year, value: -16, to: Date())
            vc.datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: -3, to: Date())
            vc.boyText.text = "BOY".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vc.GirlText.text = "GIRL".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            
            /*
             If user type is child get the intrest and show all
             */
            setupCell()
            getIntrests()
        }
        
        vc.fullName.text = (AuthFunc.shareInstance.regData.full_name != nil && AuthFunc.shareInstance.regData.full_name != "") ? AuthFunc.shareInstance.regData.full_name : "Guardian"

        let bottomPadding: CGFloat = 60 // Adjust this value as needed
        // Get the current content inset
        var contentInset = vc.scrollView.contentInset

        // Add bottom padding
        contentInset.bottom = bottomPadding

        // Set the updated content inset
        vc.scrollView.contentInset = contentInset
        
        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()
        
        // Add tap gesture recognizer to the view
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(boyBtnTapped))
        vc.boyView.addGestureRecognizer(tapGesture)
        
        // Add tap gesture recognizer to the view
        let tapGesture2 = UITapGestureRecognizer(target: self, action: #selector(girlBtnTapped))
        vc.girlView.addGestureRecognizer(tapGesture2)
        
        /*
         Setup Gender Stack for selection
         */
        setGender()
    }
    
    func setGender(){
        let alphaComp = 0.6
        switch AuthFunc.shareInstance.regData.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)
        }
    }
    
    @objc func boyBtnTapped() {
        PersistentStorage.shared.addOthersCount()
        // Apply click effect animation
        AuthFunc.shareInstance.regData.gender = 2
        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()
            }
        }
    }
    
    @objc func girlBtnTapped() {
        PersistentStorage.shared.addOthersCount()
        AuthFunc.shareInstance.regData.gender = 1

        // 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 setupCell(){
        vc.collectionView.register(UINib(nibName: K.CellIdentifier.Authentication.yourIntrestCell, bundle: nil), forCellWithReuseIdentifier: K.CellIdentifier.Authentication.yourIntrestCell)
        vc.collectionView.delegate = self.vc
        vc.collectionView.dataSource = self.vc
    }
    
    // MARK: - Get Intrests
    
    func getIntrests(){
        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]

        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.interest_topic_listing, method: .post,headers : headers) {(result : Result<BaseResponseModel<IntrestTopicDM>, 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()
                    if let intrests = data.data?.result{
                        self.intrestTopics = intrests
                        self.vc.collectionView.reloadData()
                        
                        /*
                         Set the collectionview height
                         */
                        let height = self.vc.collectionView.collectionViewLayout.collectionViewContentSize.height
                        self.vc.contentHeight.constant = height
                        self.vc.view.layoutIfNeeded()
                    }
                    
//                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                default:
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription, time: 2)
            }
        }
    }
}
