//
//  PersonInformationEditController.swift

//
//  Created by Leon on 2025/7/29.
//

import UIKit
import Combine

class PersonInformationEditController: CLViewController<PersonInformationEditView> {
    lazy var birthdayPicker:BirthdayPickerView = BirthdayPickerView()
    
    @Published var buttonEnable:Bool = false
    private var cancellables = Set<AnyCancellable>()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupViews()
        setupDats()
        setupEvents()
    }
    
    private func setupViews() {
        
    }
    
    private func setupDats(){
        
    }
    
    private func setupEvents(){
        container.bottomButton.addTarget(self, action: #selector(tapBottomButton), for: .touchUpInside)
        
        $buttonEnable.sink {[weak self] enable in
            self?.container.bottomButton.isEnabled = enable;
        }.store(in: &cancellables)
        
        Publishers.CombineLatest(container.$birthdayDate.prepend(nil), container.$nickname.prepend(nil)).map{
             date, name in
            guard let birthdayDate = date, let nickname = name else{
                return false
            }
            
            if Date().years(from: birthdayDate) < 18{
                return false
            }
            
            if !nickname.isValidNickname {
                return false
            }
            
            return true
        }.assign(to: &$buttonEnable)
    }
    
    @objc func tapBottomButton(){
        guard let user = UserCore.shared.user, let nickname = container.nickname, let birthdayDate = container.birthdayDate else{
            return
        }
        
        let timestamp = birthdayDate.timeStamp
        
        if let oldNickname = user.nickname, nickname != oldNickname{
            Hud.showIndicator()
            UserOperator.checkname(name: nickname) {[weak self] nicknameOK in
                if nicknameOK{
                    self?.doModify(userId: user.userId, nickname: nickname, timestamp: timestamp)
                }else{
                    Hud.hideIndicator()
                }
            }
        }else{
            Hud.showIndicator()
            doModify(userId: user.userId, nickname: nickname, timestamp: timestamp)
        }
    }

    
    private func doModify(userId: Int, nickname:String, timestamp: Int){
        var params = [String:Any]()
        params.updateValue(userId, forKey: "userId")
        params.updateValue(nickname, forKey: "nickname")
        params.updateValue(timestamp, forKey: "birthday")
        
        
        UserProvider.request(UserAPI.userInfoEdit(params: params), modelType: Bool.self) {[weak self] result in
            Hud.hideIndicator()
            switch result{
            case .success:
                UserCore.shared.user?.nickname = nickname
                UserCore.shared.user?.birthday = Int64(timestamp)
                NotificationCenter.post(name: .userInfoUpdated)
                UserCore.shared.refreshUserInfo(block: nil)
                self?.close()
            case .failure:
                break
            }
        }
    }

}
