//
//  ChatBackgroundGenerateInputView.swift

//
//  Created by Leon on 2025/8/26.
//
import UIKit
import Combine
class ChatBackgroundGenerateInputView: CLContainer{
    var bottomView : UIView!
    var coinLabel : CLIconLabel!
    var bottomButton: StyleButton!

    var container: LTScrollContainer!

    var titleView: TitleView!

    // Stackview's subviews
    var styleContainer:UIView!
    var styleTipLabel:UILabel!
    var styleCv:UICollectionView!

    var descriptionTextView: TitleTextView!
    var generate1Button: TextButton!
    
    var referenceLabelsView: TitleAndSubTitleView!

    var datas:[ImageStylePic] = []
    @Published var selectStyleId: String = ""
    var selectStylePrompt: String = ""
    
    @Published var figureDescriptionAIGenerated: String = ""
    @Published var figureDescriptionContent: String = ""
    
    @Published var buttonEnable:Bool = false
    
    private var cancellables = Set<AnyCancellable>()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupData()
        setupEvent()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupData(){
        setupStylesDatas()
    }
    
    private func setupStylesDatas(){
        if let imageStyles = AppDictManager.shared.aiDict?.imageStyleDictList{
            datas = imageStyles
            if let first = datas.first{
                selectStyleId = first.code ?? ""
                selectStylePrompt = first.prompt ?? ""
            }
        }else{
            Hud.showIndicator()
            AppDictManager.shared.loadAIDict {[weak self] ok in
                Hud.hideIndicator()
                if(ok){
                    self?.setupStylesDatas()
                }
            }
        }
    }
    
    private func setupEvent(){
        $buttonEnable.sink {[weak self] enable in
            self?.bottomButton.isEnabled = enable
        }.store(in: &cancellables)
        
        $selectStyleId.sink {[weak self] code in
            guard let `self` = self else {
                return
            }
            
            guard let imageStyles = AppDictManager.shared.aiDict?.imageStyleDictList else{return}
            self.selectStylePrompt = imageStyles.first(where: {$0.code == code})?.prompt ?? ""
            
        }.store(in: &cancellables)
        
        $figureDescriptionContent.sink {[weak self] str in
            self?.descriptionTextView.defaultText = str
        }.store(in: &cancellables)
        
        $figureDescriptionAIGenerated.sink {[weak self] str in
            self?.descriptionTextView.defaultText = str
            self?.figureDescriptionContent = str
        }.store(in: &cancellables)
        
        descriptionTextView.textDidChanged = {[weak self] textField in
            self?.figureDescriptionContent = textField.text.trimmed
        }
        
        Publishers.CombineLatest($figureDescriptionContent, $selectStyleId).map{
            content, selectStyleCode in
            if content.trimmed.count > 0 && selectStyleCode.count > 0{
                return true
            }
            return false
        }.assign(to: &$buttonEnable)
        
        WalletCore.shared.$balance.sink {[weak self] balance in
            if let priceLabel = self?.coinLabel {
                priceLabel.contentLabel.text = balance.displayBalance()
            }
        }.store(in: &cancellables)
        
//#if DEBUG
//figureDescriptionContent = "一个来自古代神话的森林守护者，外形优雅而神秘，皮肤如同古树树皮般带有天然纹理，身上点缀着会发光的藤蔓与花朵。双眸宛如月光湖水，闪烁着宁静的光辉，长发由柔和的苔藓与羽毛交织而成，随风轻盈飘动。她身披由自然能量编织的长袍，衣角化作轻盈的雾气，脚下生长出发光的花草。周身萦绕着漂浮的光点与透明的灵体生物，场景被微光森林与梦幻薄雾笼罩，奇幻插画风格，超高精细，8K 分辨率。"
//#endif
    }
    
    // MARK: - Publish
    func scrollSelectedShow(){
        // 将选中的style的cell滑动显示出来
        if let index = self.datas.firstIndex(where: {$0.code == selectStyleId}){
            // print("currentindex : \(index)")
            self.styleCv.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false)
        }
    }
    
    // MARK: - Helper
    
    private func setupButtonVIPBuyStyle(){
        bottomButton.context(size: .large)
        let buttonString = "Buy VIP +10/Month"
        let aStr = StyleButton.getVIPBlackTitleByWords(words: buttonString)//  getAttributeTitleByWords(words: buttonString)
        bottomButton.setAttributedTitle(aStr, for: .normal)
    }
    
    private func setupViews() {
        bottomView = {
            let v = UIView()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom)
                make.height.equalTo(80)
            }
            return v
        }()
        coinLabel = {
            let v = CLIconLabel()
            bottomView.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalTo(24)
            }
            return v
        }()
        
        bottomButton = {
            let v = StyleButton(type: .custom)
            //v.context(size: .large)
            v.primary(size: .large)
            bottomView.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.trailing.equalToSuperview().offset(-24)
                //make.leading.equalToSuperview().offset(106)
                make.leading.greaterThanOrEqualTo(coinLabel.snp.trailing).offset(16)
            }
            return v
        }()


        container = {
            let v = LTScrollContainer()
            v.stack.spacing = 24
            v.stack.alignment = .leading
            v.scrollView.delegate = self
            addSubview(v)
            v.snp.makeConstraints { make in
                // make.top.equalTo(navigationView.snp.bottom)
                make.top.equalToSuperview().offset(UIWindow.navBarTotalHeight)
                make.leading.trailing.equalToSuperview()
                make.bottom.equalTo(bottomView.snp.top).offset(0)
            }
            return v
        }()
        
        titleView = {
            let v = TitleView()
            v.optionInnerBottomPadding = 16
            v.optionInnerTopPadding = 16
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
            }
            return v
        }()
        container.stack.setCustomSpacing(0, after: titleView)
        
        styleContainer = {
            let v = UIView()
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
            }
            return v
        }()
        
        styleTipLabel = {
            let v = UILabel()
            styleContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.top.equalToSuperview().offset(12)
            }
            v.font = .t.tlm
            v.textColor = .c.ctpn
            v.text = "Style"
            return v
        }()
        
        styleCv = {
            let layout = UICollectionViewFlowLayout()
            layout.scrollDirection = .horizontal
            let size = CGSize(width: 100, height: 100 + 24)
            layout.itemSize = size
            layout.minimumLineSpacing = 12
            layout.minimumInteritemSpacing = 12
            layout.sectionInset = UIEdgeInsets(top: 0, left: CGFloat.lrs, bottom: 0, right: CGFloat.lrs)
            let v = UICollectionView(frame: .zero, collectionViewLayout: layout)
            v.showsHorizontalScrollIndicator = false
            styleContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.top.equalTo(styleTipLabel.snp.bottom).offset(12)
                make.height.equalTo(size.height)
                make.bottom.equalToSuperview()
            }
            v.backgroundColor = .clear
            v.register(RoleFigureStyleCell.self, forCellWithReuseIdentifier: "RoleFigureStyleCell")
            v.dataSource = self
            v.delegate = self
            return v
        }()
        
        descriptionTextView = {
            let v = TitleTextView()
            v.maxLimit = 1000
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()
        
        generate1Button = {
            let v = TextButton()
            v.text = "自动生成"
            descriptionTextView.addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview()
                make.centerY.equalTo(descriptionTextView.titleLabel)
                make.height.equalTo(40)
            }
            return v
        }()

        referenceLabelsView = {
            let v = TitleAndSubTitleView()
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()

        titleView.title = "Create"

        let string = "\(Coin(cents: 7000).thousandthsFormatted) to Create"
        let titleAstr = NSAttributedString.getIconTitleAttributeByWords(words: string, iconImage: UIImage.icon32Diamond, iconSize: CGSize(width: 24, height: 24), textFont: .t.tll, textColor: .white)
        //let titleAstr = StyleButton.getUnlockAttributeTitleByCoin(coin: 7000, string: "to Create")
        
        descriptionTextView.titleLabel.text = "Description"
        descriptionTextView.placeholder = "请描述形象的肤色、服饰、发型、五官、动作、背景等"
        
        bottomButton.setAttributedTitle(titleAstr, for: .normal)
        referenceLabelsView.titleLabel.text = "Reference"
        referenceLabelsView.subLabel.text = "AI will create based on the basic image of the character"
        
        coinLabel.iconImageView.image = UIImage(named: "icon_16_diamond")
        
        coinLabel.contentLabel.text = "-"
    }
}

extension ChatBackgroundGenerateInputView: UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NaviAlphaHandle.changeNaviTitleAlpha(scrollView: scrollView, titleLabel: navigationView?.titleLabel)
    }
}

extension ChatBackgroundGenerateInputView:UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RoleFigureStyleCell", for: indexPath) as! RoleFigureStyleCell
        let item = datas[indexPath.item]
        cell.setupData(data: item)
        cell.setupSelected(selected: item.code == selectStyleId)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let item = datas[indexPath.item]
        selectStyleId = item.code ?? ""
        selectStylePrompt = item.prompt ?? ""
        collectionView.reloadData()
    }
}
