//
//  RoleFigureGenerateView.swift

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

import UIKit
import Combine
class RoleFigureGenerateView: UIView {
    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 referenceContainer:UIView!
    var referenceTipLabel:UILabel!
    var referenceButton : CommonUploadImageButton!
    
    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 setupViews() {
        bottomButton = {
            let v = StyleButton(type: .custom)
            v.primary(size: .large)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom * 0.5 - 16)
            }
            v.setTitle("Generate", for: .normal)
            return v
        }()
        container = {
            let v = LTScrollContainer()
            v.stack.spacing = 24
            v.stack.alignment = .leading
            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(bottomButton.snp.top).offset(-16)
            }
            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()
            }
            v.title = "Appearance"
            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)
            styleContainer.addSubview(v)
            v.showsHorizontalScrollIndicator = false
            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()
            // 10~500
            v.maxLimit = 1000
//            v.minLimit = 10
            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
        }()
        
        referenceContainer = {
            let v = UIView()
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                //make.leading.equalToSuperview().offset(CGFloat.lrs)
                //make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
            }
            return v
        }()
        
        referenceTipLabel = {
            let v = UILabel()
            referenceContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.top.equalToSuperview()
            }
            v.font = .t.tlm
            v.textColor = .c.ctpn
            v.text = "Reference"
            return v
        }()
        
        let optionalLabel = {
            let v = EPOptionFlagLabel()
            referenceContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalTo(referenceTipLabel.snp.trailing).offset(4)
                make.centerY.equalTo(referenceTipLabel)
            }
            return v
        }()
        optionalLabel.isHidden = false
        
        referenceButton = {
            let v = CommonUploadImageButton()
            referenceContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                //make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.top.equalTo(referenceTipLabel.snp.bottom).offset(8)
                make.height.equalTo(100)
                make.width.equalTo(100)
                make.bottom.equalToSuperview()
            }
            return v
        }()
        
        
        referenceContainer.isHidden = true
        
        descriptionTextView.titleLabel.text = "Description"
        descriptionTextView.placeholder = "请描述形象的肤色、服饰、发型、五官、动作、背景等"
//        descriptionTextView.errorMsg = "只能包含10-500字符"
    }
    
    func setupData(){
        
    }

    private func setupEvent(){
       
        
        $buttonEnable.sink {[weak self] enable in
            self?.bottomButton.isEnabled = enable
        }.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)
        
        $selectStyleId.sink {[weak self] selectStyleId in
            guard let theDatas = self?.datas else{
                return
            }
            for per in theDatas{
                if selectStyleId == per.code ?? ""{
                    self?.selectStylePrompt = per.prompt ?? ""
                }
            }
        }.store(in: &cancellables)
        
        descriptionTextView.textDidChanged = {[weak self] textField in
            self?.figureDescriptionContent = textField.text
        }
        
        Publishers.CombineLatest($figureDescriptionContent, $selectStyleId).map{
            content, selectStyleCode in
            if content.trimmed.count > 0 && selectStyleCode.count > 0{
                return true
            }
            return false
        }.assign(to: &$buttonEnable)
        
//#if DEBUG
//figureDescriptionContent = "beautiful high school girl, elegant rich family daughter, medium academic performance, refined but slightly rebellious look, layered personality, fashionable school uniform with subtle luxury accessories, natural makeup, confident yet thoughtful expression, long silky hair, warm afternoon sunlight, cinematic composition, highly detailed, 8k, ultra realistic, anime-inspired style"
//#endif
        
        setupStylesDatas()
    }
    
    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()
                }
            }
        }
    }
    
    // MARK: - Public
    
    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)
        }
    }
    
}

extension RoleFigureGenerateView: 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()
    }
}

class RoleFigureStyleCell: UICollectionViewCell{
    var block:UIView!
    var iv:UIImageView!
    var titleLabel:UILabel!
    var selectedMark:UIImageView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupViews(){
        block = {
            let v = UIView()
            v.backgroundColor = .c.csen
            v.layer.borderColor = UIColor.c.cpn.cgColor
            v.layer.borderWidth = 0
            v.layer.cornerRadius = 16
            v.layer.masksToBounds = true
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.top.equalToSuperview()
                make.height.equalTo(v.snp.width)
            }
            return v
        }()

        iv = {
            let v = UIImageView()
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalToSuperview()
            }
            return v
        }()

        titleLabel = {
            let v = UILabel()
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.top.equalTo(block.snp.bottom).offset(4)
            }
            v.font = .t.tls
            v.textColor = .c.ctpn
            v.text = "Style"
            v.textAlignment = .center
            return v
        }()

        selectedMark = {
            let v = UIImageView()
            v.image = UIImage(named: "checkmark_tick")
            
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview().offset(-8)
                make.top.equalToSuperview().offset(8)
            }
            v.isHidden = true
            return v
        }()
    }

    func setupSelected(selected:Bool){
        selectedMark.isHidden = !selected
        block.layer.borderWidth = selected ? 2 : 0
    }

    func setupData(data:ImageStylePic){
        titleLabel.text = data.name
        iv.loadImage(data.url)
    }
}


