//
//  RolePhotoGenerateView.swift

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

import UIKit
import Combine

class RolePhotoGenerateView: UIView {
    var bottomButton: StyleButton!
    var tipStackH: UIStackView!
    var tipIcon: UIImageView!
    var tipLabel: ColorLabel!
    var tipNormalLabel: CLLabel!

    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 contentIsOKToSubmit:Bool = false
    @Published var createState: AlbumCreationState?
    
    
    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(){
        $contentIsOKToSubmit.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.textView.text = str
            self?.figureDescriptionContent = str
        }.store(in: &cancellables)
        
        descriptionTextView.textDidChanged = {[weak self] textField in
            self?.figureDescriptionContent = textField.text
        }
        
        Publishers.CombineLatest3($figureDescriptionContent, $selectStyleId, $createState).map{
            content, selectStyleCode, state in
            if content.trimmed.count > 0 && selectStyleCode.count > 0{
                return true
            }
            
            if state == .nonMemberNoQuota || state == .vipUserNoQuota {
                return true
            }
            
            return false
        }.assign(to: &$contentIsOKToSubmit)
        
//#if DEBUG
//figureDescriptionContent = "一个高度拟真的人形 AI，造型流畅而未来感十足，金属质感的皮肤上有柔和发光的电路纹路，拥有富有表现力的合成眼睛，眼眸中散发柔和光芒，身穿极简高科技服饰并带有全息细节，周围环绕着漂浮的数据流和抽象几何图案，电影级灯光，超精细，8K 分辨率"
//#endif
    }
    
    // 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)
        }
    }
    
    // MARK: - Helper
    
    private func setupButtonVIPBuyStyle(){
        bottomButton.context(size: .large)
        let buttonString = "Buy VIP +10/Month"
        let aStr = getAttributeTitleByWords(words: buttonString)
        bottomButton.setAttributedTitle(aStr, for: .normal)
    }
    
    private func setupButtonNormalStyle(string: String){
        bottomButton.primary(size: .large)
        bottomButton.setAttributedTitle(nil, for: .normal)
        bottomButton.setTitle(string, for: .normal)
    }
    
    private func getAttributeTitleByWords(words: String) -> NSAttributedString {
        
        let text = " \(words)"
        let attributedString = NSMutableAttributedString()
        if let iconImage = MWIconFont.image(fromIcon: .iconVip, size: CGSize(width: 24, height: 24), color: .black) { // 替换为你的图标名称
            let attachment = NSTextAttachment()
            attachment.image = iconImage

            let iconSize = CGSize(width: 24, height: 24) // 调整为你需要的大小
            attachment.bounds = CGRect(origin: .init(x: 0, y: -4), size: iconSize)

            let iconAttributedString = NSAttributedString(attachment: attachment)
            attributedString.append(iconAttributedString)
        }

        // 添加文字并设置样式
        let textAttributedString = text.withAttributes([
            .font(.t.tbsl), // 设置字体
            .textColor(.black),
        ])
        attributedString.append(textAttributedString)
        return attributedString
    }
    
    // MARK: - UI
    
    private func setupViews() {
        bottomButton = {
            let v = StyleButton(type: .custom)
            //v.context(size: .large)
            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)
            }
            return v
        }()

        tipStackH = {
            let v = UIStackView()
            v.spacing = 8
            v.alignment = .center
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.greaterThanOrEqualToSuperview().offset(24)
                make.trailing.lessThanOrEqualToSuperview().offset(-24)
                make.centerX.equalToSuperview()
                make.bottom.equalTo(bottomButton.snp.top).offset(-16)
            }
            return v
        }()

        tipIcon = {
            let v = UIImageView()
            v.image = UIImage(named: "vip_flag_16")
            tipStackH.addArrangedSubview(v)
            v.isHidden = true
            return v
        }()

        tipLabel = {
            let v = ColorLabel()
            v.applyGradient(.vip)
            v.font = .t.tls
            // v.textAlignment = .center
            tipStackH.addArrangedSubview(v)
            v.isHidden = true
            return v
        }()
        
        tipNormalLabel = {
            let v = CLLabel()
            v.font = .t.tls
            tipStackH.addArrangedSubview(v)
            v.isHidden = true
            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(tipLabel.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()
            }
            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()
            // 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
        }()

        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"
        tipLabel.text = "VIP Remaining Times 0/10"
        descriptionTextView.titleLabel.text = "Description"
        descriptionTextView.placeholder = "请描述形象的肤色、服饰、发型、五官、动作、背景等"
        //descriptionTextView.errorMsg = "只能包含10-500字符"
        bottomButton.setTitle("Submit", for: .normal)
        referenceLabelsView.titleLabel.text = "Reference"
        referenceLabelsView.subLabel.text = "AI will create based on the basic image of the character"
    }
}

enum AlbumCreationState: Equatable {
    case freeUserWithQuota(Int)   // 免费用户且有剩余次数 (freeNum)
    case vipUserWithQuota(Int)    // 会员用户且有剩余次数 (memberNum)
    case buyerWithQuota(Int)      // 购买用户且有剩余次数 (buyNum)
    case nonMemberNoQuota         // 非会员，次数用尽
    case vipUserNoQuota           // 会员用户，次数用尽
}

// MARK: 处理
extension RolePhotoGenerateView{
    
    
    func getCreationState(freeNum: Int, memberNum: Int, buyNum: Int, isMember: Bool) -> AlbumCreationState {
        if freeNum > 0 {
            return .freeUserWithQuota(freeNum)
        } else if memberNum > 0 {
            return .vipUserWithQuota(memberNum)
        } else if buyNum > 0 {
            return .buyerWithQuota(buyNum)
        } else if !isMember {
            return .nonMemberNoQuota
        } else {
            return .vipUserNoQuota
        }
    }
    
    @discardableResult
    func handleCreationUI(freeNum: Int, memberNum: Int, buyNum: Int, isMember: Bool) -> AlbumCreationState {
        let state = getCreationState(freeNum: freeNum, memberNum: memberNum, buyNum: buyNum, isMember: isMember)

        tipIcon.isHidden = true
        tipLabel.isHidden = true
        tipNormalLabel.isHidden = true
        
        let totalLeftUseNum = freeNum + memberNum + buyNum
        
        switch state {
        case .freeUserWithQuota(let free):
            print("🎨免费用户，还剩 \(free) 次") // 彩色vip + create
            // Top:
            tipIcon.isHidden = false
            tipLabel.isHidden = false
            tipLabel.text = "Non-members have 10 free creations (\(totalLeftUseNum))"
            setupButtonNormalStyle(string: "Create")

        case .vipUserWithQuota(let vip):
            print("🎨会员用户，还剩 \(vip)/10 次") //  白色。+ Create
            tipNormalLabel.isHidden = false
            tipNormalLabel.text = "VIP Remaining Times (\(totalLeftUseNum))"
            tipNormalLabel.textColor = .c.ctpn
            setupButtonNormalStyle(string: "Create")
            
        case .buyerWithQuota(let buy):  // 白色+ Create
            print("🎨购买用户，还剩 \(buy) 次")
            tipNormalLabel.isHidden = false
            tipNormalLabel.textColor = .c.ctpn
            tipNormalLabel.text = "VIP Remaining Times (\(totalLeftUseNum))"
            setupButtonNormalStyle(string: "Create")
        case .nonMemberNoQuota:
            print("🎨非会员，次数已用完，提示开通会员")
            tipIcon.isHidden = false
            tipLabel.isHidden = false
            tipLabel.text = "Non-members have 10 free creations (\(0))"
            // -> 开通会员
            setupButtonVIPBuyStyle()
        case .vipUserNoQuota:
            print("🎨会员用户，次数已用完，提示购买额外次数")
            tipNormalLabel.isHidden = false
            tipNormalLabel.textColor = .c.cwvn
            tipNormalLabel.text = "VIP Remaining Times (0)"
            
            // -> 购买次数
            setupButtonNormalStyle(string: "Buy Times")
        }
        
        createState = state
        return state
    }

    
}

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