//
//  ChatPersonalSettingController.swift

//
//  Created by Leon on 2025/8/17.
//

import UIKit
import Combine
class ChatPersonalSettingController: CLViewController<ChatPersonalSetting> {
    lazy var birthdayPicker: BirthdayPickerView = BirthdayPickerView()
    
    var setting: IMChatSetting?
    
    @Published var buttonEnable:Bool = false
    private var cancellables = Set<AnyCancellable>()
    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
        setupDatas()
        setupEvents()
    }

    private func setupViews() {
        navigationView.alpha0Title = "My Chat Persona"
        navigationView.setupNaviRightStyleButton()
        navigationView.styleMainButton.setTitle("Save", for: .normal)
        navigationView.styleMainButton.addTarget(self, action: #selector(tapNaviSaveButton), for: .touchUpInside)
    }

    private func setupDatas() {
    }

    private func setupEvents() {
        container.birthdaySelectView.selectBlock = { [weak self] in
            self?.selectBirthday()
        }
        
        navigationView.tapBackButtonAction = { [weak self] in
            if self?.container.editFlag ?? false{
                self?.alertToExitNotSaved()
            }else{
                self?.close()
            }
        }
        
        $buttonEnable.sink {[weak self] enable in
            self?.navigationView.styleMainButton.isEnabled = enable
        }.store(in: &cancellables)
        
        Publishers.CombineLatest4(container.$whoIm.prepend(nil), container.$birthdayDate.prepend(nil), container.$nickname.prepend(nil), container.$editFlag.prepend(false)).map{ [weak self]
            whoIm, date, name, editFlag in
            guard let birthdayDate = date, let nickname = name else{
                return false
            }
            
            if Date().years(from: birthdayDate) < 18{
                return false
            }
            
            if !nickname.isValidNickname {
                return false
            }
            
            if let content = whoIm{
                if content.trimmed.count > 0 && content.count < 10{
                    return false
                }
            }
            
            // Add: 没有更改.判断方法1， 直接判断container.editFlag
//            if  let oldNickname = self?.setting?.nickname, let oldBirthday = self?.setting?.birthday, let oldWhoIm = self?.setting?.whoAmI{
//                if oldNickname == name && birthdayDate.timeStamp == oldBirthday && whoIm == oldWhoIm{
//                    return false
//                }
//            }
            guard editFlag else{
                return false
            }
            
            return true
        }.assign(to: &$buttonEnable)
        
        container.config(setting)
    }

    private func selectBirthday() {
        if let date = container.birthdayDate{
            birthdayPicker.setupDefaultSelectDate(date)
        }else if let dateStr = container.birthdayStr{
            let date = Date(dateString: dateStr, format: "yyyy-MM-dd")
            birthdayPicker.setupDefaultSelectDate(date)
        }
        
        birthdayPicker.show()
        birthdayPicker.tapConfirmAction = { [weak self] date, timestamp in
            dlog("birthday date:\(date). timestamp:\(timestamp)")
            self?.container.birthdayDate = date
            self?.container.birthdayStr = date.toString(dateFormat: "yyyy-MM-dd")
            self?.container.editFlag = true
        }
        
        
    }
    
    // MARK: - Action
    @objc private func tapNaviSaveButton(){
        guard let newNickname = container.nickname, let before = container.nickname else{
            return
        }
        
        Hud.showIndicator()
        if newNickname != before {
            UserOperator.checkname(name: newNickname) {[weak self] nicknameOK in
                if nicknameOK{
                    self?.doSaveChatSetting()
                }else{
                    Hud.hideIndicator()
                }
            }
        }else{
            doSaveChatSetting()
        }
        
    }
    
    // MARK: - Functions
    
    private func doSaveChatSetting(){
        guard let aiId = setting?.aiId else {return}
        var params = [String:Any]()
        
        let nickname = container.nickname
        let birthday = container.birthdayDate!.timeStamp
        let whoAmI = container.whoIm
        
        params.updateValue(aiId, forKey: "aiId")
        params.updateValue(nickname ?? "-", forKey: "nickname")
        params.updateValue(birthday, forKey: "birthday")
        params.updateValue(whoAmI ?? "", forKey: "whoAmI")
        
       
        AIRoleProvider.request(.chatSetup(params: params), modelType: EmptyModel.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                Hud.toast(str: "保存成功")
                NotificationCenter.post(name: .chatPersonaUpdated)
                self?.navigationController?.popViewController(animated: true)
            case .failure:
                break
            }
        }
    }
    
    @objc private func alertToExitNotSaved() {
        view.endEditing(true)
        let alert = Alert(title: "Save edited content", text: "Edits will not be saved after exiting. Are you sure you want to continue?")
        let action1 = AlertAction(title: "Give up", actionStyle: .confirm) { [weak self] in
            self?.close()
        }
        let action2 = AlertAction(title: "Cancel", actionStyle: .cancel)
        alert.addAction(action1)
        alert.addAction(action2)
        alert.show()
    }
}
