//
//  PhotoBrowserControllerExtChatBackground.swift

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

extension PhotoBrowserController{
    
    // MARK: Chatbackground Set
    func createChatBackgroundSetViews(){
        bottomGradientContainer.isHidden = false
        
        setDefaultEntry = {
            let v = RolePhotoSetDefaultEntryView()
            v.setupChatBackgroundSetMode()
            bottomGradientOperateStackV.addArrangedSubview(v)
            return v
        }()
        
        setBackgroundDisableButton = {
            let v = StyleButton()
            v.contrastTertiaryLight(size: .large)
            v.isEnabled = false
            v.setTitle("Set background", for: .normal)
            bottomGradientOperateStackV.addArrangedSubview(v)
            return v
        }()
        
        moreButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .more)
            v.addTarget(self, action: #selector(tapNaviMoreInChatBackgroud(sender:)), for: .touchUpInside)
            titleView.rightStackH.addArrangedSubview(v)
            titleView.paddingRightForRightStack = 16
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
            }
            v.isHidden = true
            return v
        }()
        
        setupChatBackgroundEvents()
    }
    
    // MARK: Events
    func setupChatBackgroundEvents(){
        setDefaultEntry.setButton.addTarget(self, action: #selector(tapSetChatBackgrondDefaultButton), for: .touchUpInside)
    }
    
    
    // MARK: Action
    @objc func tapNaviMoreInChatBackgroud(sender: UIButton) {
        let pop = CLPopoverListView()
        let rect = view.convert(sender.frame, from: sender.superview)
        pop.setupDeletePopover(rect.insetBy(dx: 0.0, dy: -6.0), inView: view) { [weak self] in
            self?.doDeleteChatBackground()
        }
    }
    
    private func doDeleteChatBackground(){
        
//        #warning("test")
//        self.imageModels.remove(at: self.currentIndex)
//        if self.imageModels.isEmpty {
//            PhotoBrowserManager.shared.hidePhotoBrowser()
//        } else {
//            if self.currentIndex >= self.imageModels.count {
//                self.currentIndex -= 1
//            }
//            self.setupViews()
//            self.reloadCountLabel(hidden: false)
//        }
//        return
        
        let imageModel = imageModels[currentIndex]
        guard let background = imageModel.chatBackground, let backgroundId = background.backgroundId, backgroundId > 0 else{
            return
        }
        Hud.showIndicator()
        AIRoleProvider.request(.deleteChatBackground(backgroundId: backgroundId), modelType: EmptyModel.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                guard let `self` = self else {
                    return
                }
                self.imageModels.remove(at: self.currentIndex)
                if self.imageModels.isEmpty {
                    PhotoBrowserManager.shared.hidePhotoBrowser()
                } else {
                    if self.currentIndex >= self.imageModels.count {
                        self.currentIndex -= 1
                    }
                    self.setupViews()
                    self.reloadCountLabel(hidden: false)
                    self.reloadStates(index: currentIndex)
                }
                NotificationCenter.post(name: .chatSettingBackgroundListUpdated)
                if background.isSelected.boolValue{
                    NotificationCenter.post(name: .chatSettingUpdated)
                }
            case .failure:
                break
            }
        }
    }
    
    @objc private func tapSetChatBackgrondDefaultButton(){
        let imageModel = imageModels[currentIndex]
        
        guard let aiUid = imageModel.aiId else{
            return
        }
        
        Hud.showIndicator()
        var params = [String: Any]()
        params.updateValue(aiUid, forKey: "aiId")
        
        if let background = imageModel.chatBackground, let backgroundId = background.backgroundId, backgroundId > 0{
            params.updateValue(backgroundId, forKey: "backgroundId")
        }
        
        AIRoleProvider.request(.setDefaultChatBackground(params: params), modelType: EmptyModel.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                //NotificationCenter.post(name: .chatSettingBackgroundListUpdated)
                self?.resetAndMarkSelectedBackground(imgUrl: imageModel.imageUrl)
                
                PhotoBrowserManager.shared.hidePhotoBrowser()
                NotificationCenter.post(name: .chatSettingBackgroundChanged)
                NotificationCenter.post(name: .chatSettingUpdated)
            case .failure:
                break
            }
        }
    }
    
    // MARK: Helper
    private func resetAndMarkSelectedBackground(imgUrl: String?){
        guard let selectedUrl = imgUrl else{return}
        for per in imageModels {
            if let perImgurl = per.chatBackground?.imgUrl, perImgurl == selectedUrl{
                per.chatBackground?.isSelected = true
            }else{
                per.chatBackground?.isSelected = false
            }
        }
        reloadStates(index: currentIndex)
    }
}
