//
//  ChatBackgroundGridController.swift

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

import UIKit

class ChatBackgroundGridController: CLViewController<ChatBackgroundGridView> {
    var aiId : Int?
    var selectBgUrl: String?
    
    var backgrounds: [IMChatBackground]?
    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
        setupDatas()
        setupEvents()
    }
    

    private func setupViews() {
        navigationView.alpha0Title = "Chat Background"
        navigationView.setupBackButtonCloseIcon()
    }
    
    private func setupDatas(){
        container.aiId = aiId
        loadBgList()
        
        guard let aiInfo = IMAIViewModel.shared.aiIMInfo else{return}
        
        let level = aiInfo.aiUserHeartbeatRelation?.heartbeatLevel ?? .level1
        container.headView.setupCreateMode(create: level.isGreaterOrEqual(to: .level10))
        
        if selectBgUrl == nil{
            loadChatSetting()
        }
        
    }
    
    private func loadChatSetting(){
        guard let theId = aiId else{return}
        Hud.showIndicator()
        AIRoleProvider.request(.chatSetupGet(aiId: theId), modelType: IMChatSetting.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success(let model):
                if let select = model?.backgroundImg{
                    self?.selectBgUrl = select
                    self?.container.config(self?.backgrounds, selectBgUrl: self?.selectBgUrl)
                }
            case .failure:
                break
            }
        }
    }
    
    private func loadBgList(){
        guard let theAiId = aiId else{
            return
        }
        Hud.showIndicator()
        AIRoleProvider.request(.getChatBackgroundList(aiId: theAiId), modelType: [IMChatBackground].self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success(let model):
                self?.backgrounds = model
                self?.container.config(model, selectBgUrl: self?.selectBgUrl)
            case .failure:
                break
            }
        }
    }
    
    private func setupEvents(){
        container.bottomButton.addTarget(self, action: #selector(tapBottomButton), for: .touchUpInside)
        container.headView.operateButton.addTarget(self, action: #selector(tapUnlockOrCreateNewBg), for: .touchUpInside)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notifyBackgroundListUpated), name: AppNotificationName.chatSettingBackgroundListUpdated.notificationName, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(notifyBackgroundUpdated), name: AppNotificationName.chatSettingBackgroundChanged.notificationName, object: nil)
    }
    
    // MARK: - Action
    @objc private func tapBottomButton(){
        guard let theAiId = aiId else{
            return
        }
        
        var params = [String:Any]()
        params.updateValue(theAiId, forKey: "aiId")
        
        if let selectModel = container.selectBgModel, let id = selectModel.backgroundId{
            params.updateValue(id, forKey: "backgroundId")
        }
        
        Hud.showIndicator()
        AIRoleProvider.request(.setDefaultChatBackground(params: params), modelType: EmptyModel.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                NotificationCenter.post(name: .chatSettingBackgroundChanged)
                NotificationCenter.post(name: .chatSettingUpdated)
                self?.close(dismissFirst: true)
            case .failure:
                break
            }
        }
        
    }
    
    @objc private func tapUnlockOrCreateNewBg(){
        guard let aiInfo = IMAIViewModel.shared.aiIMInfo else{return}
        
        if let level = aiInfo.aiUserHeartbeatRelation?.heartbeatLevel, level.isGreaterOrEqual(to: .level10) {
            let vc = ChatBackgroundGenerateController()
            vc.aiId = aiId
            presentNaviRootVc(vc: vc)
        }else{ 
            AppRouter.goAIHeartBeatLevelPage(aiId: aiInfo.aiId)
        }
    }
    
    
    
    // MARK: - Noti
    
    @objc private func notifyBackgroundListUpated(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {[weak self] in
            self?.loadBgList()
        }
    }
    
    @objc private func notifyBackgroundUpdated(){

        close(dismissFirst: true)
    }
}
