//
//  RoleCharacterSetView.swift

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

import UIKit
import Combine

class RoleCharacterSetView: UIView {
    lazy var birthdayPicker:BirthdayPickerView = BirthdayPickerView()
    
    var backButton: EPIconTertiaryButton!
    var bottomButton: StyleButton!
    var container: LTScrollContainer!
    var titleView: TitleView!
    var stepLabel: UILabel!

    var nicknameTitleView: TitleTextField!
    var sexView: GenderSelectView!
    /// 编辑时展示用，不可操作
    var sexSelectView : CLSelectView!
    var birthdaySelectView: CLSelectView!
    var settingTextView: TitleTextView!
    var generateButton: TextButton!
    
    // Data
    @Published var nickname: String = ""
    /// 用户输入
    @Published var sexSelect: Sex?
    
    @Published var birthdayStr: String?
    @Published var birthdayDate: Date?
    
    @Published var settingContent: String = ""
    @Published var settingAIGenerated: String = ""
    
    @Published var canGoNext : 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(){
        
    }
    
    private func setupEvent(){
        
        
        sexView.$sex.sink {[weak self] sex in
            self?.sexSelect = sex
            dlog("Sex: \(String(describing: sex))")
        }.store(in: &cancellables)
        
        $settingAIGenerated.sink {[weak self] str in
//            self?.settingTextView.textView.text = str
            self?.settingContent = str
        }.store(in: &cancellables)
        
        $birthdayStr.sink {[weak self] birdayStr in
            self?.birthdaySelectView.contentStr = birdayStr
        }.store(in: &cancellables)
        
        $nickname.sink {[weak self] str in
            self?.nicknameTitleView.textfield.text = str
        }.store(in: &cancellables)
        
        nicknameTitleView.textfield.textPublisher.sink {[weak self] str in
            self?.nickname = str ?? ""
        }.store(in: &cancellables)
        
        // Option 2
//        nicknameTitleView.textfield.textDidChanged = {[weak self] textfield in
//            self?.nickname = textfield.text?.trimmed
//        }
        
        $settingContent.sink {[weak self] str in
            self?.settingTextView.defaultText = str
        }.store(in: &cancellables)
        
        Publishers.CombineLatest4($nickname, $sexSelect, $birthdayStr, $settingContent).map{
            nickname, sex, birthdayStr, text in
            if nickname.isValidNickname && sex != nil && (birthdayStr ?? "").count > 0 && text.trimmed.count >= 10{
                return true
            }
            return false
        }.assign(to: &$canGoNext)
        
        $canGoNext.sink {[weak self] can in
            self?.bottomButton.isEnabled = can
        }.store(in: &cancellables)
        
        birthdaySelectView.selectBlock = {[weak self] in
            self?.selectBirthday()
        }
        
        settingTextView.textDidChanged = {[weak self] textfield in
            self?.settingContent = textfield.text
        }
        
        #if DEBUG
        testData()
        #endif
        
        // 创建AI，默认生日
        birthdayStr = "2000-01-01"
    }
    
    func restoreNoneEditableSex(sex: Sex?){
        self.sexSelectView.contentStr = (sex ?? .noncomfirming).localizedText
        self.sexSelectView.isHidden = false
        
        self.sexView.isHidden = true;
        self.sexView.sex = sex
    }
    
    private func testData(){
        nickname = "Monab"
        //sexView.sex = .female
        birthdayStr = "2000-07-09"
        settingContent = "在某一个平凡的清晨阳光透过薄薄的窗帘洒落在房间里空气中漂浮着淡淡的咖啡香气时钟滴答作响仿佛在提醒着新的一天已经开始世界在悄然运转而人们也在各自的节奏里迎接生活有人匆忙穿过街道去赶上地铁有人推开门迎接清风与日光有人依旧在梦中与自己短暂的安宁相伴而这一切都构成了城市每日的序曲生活的美好并不总是轰轰烈烈它常常隐藏在最琐碎的细节里比如早晨一杯热牛奶的温度比如路口遇见陌生人礼貌的点头比如远方的朋友忽然发来的一句问候让你觉得再孤单的日子也有温暖的痕迹我们习惯把目光投向远方幻想着某一天能抵达一个理想的未来却常常忘了眼前的每一分每一秒才是真正的存在当我们追逐着尚未抵达的目标心里常常会生出焦虑觉得自己不够快不够好不够幸运但如果静下心来仔细看看你会发现其实生命从来没有亏待过任何人它总会在不同的阶段以不同的方式让你体验成长与收获也许是一段艰难的经历让你学会坚强也许是一场意外的遇见让你感到世界柔软也许是一份迟来的鼓励让你重新点燃希望人生从不是一条直线而更像是一条蜿蜒的河流它绕过高山经过峡谷有时奔腾有时平缓而我们要做的不是预测下一个转弯会带来什么而是学会在当下的河水里尽情漂流感受每一段风景带来的独特意义很多时候我们被告知要努力要成功要拥有别人眼中的光鲜亮丽于是拼命向前不敢停歇生怕被落下生怕被否定可真正值得珍惜的却往往是那些慢下来的时刻是与家人坐在一起谈笑风生的晚餐是一个人在书桌前静静读完一本书的午后是走在公园小径上不经意抬头看见的那片湛蓝天空这些微小而真实的片段才是支撑我们走下去的力量幸福不是宏大的目标而是一点一滴的积累正如滴水汇聚成河尘埃凝聚成星无数平凡的瞬间堆叠出生命的厚度很多人说他们害怕孤独害怕失败害怕努力没有回报可是如果换一个角度想想孤独是一种与自己对话的机会失败是一次重塑的契机努力没有回报的过程里也藏着你独有的成长轨迹当我们真正理解这些或许就会少一些抱怨多一些笃定少一些焦虑多一些耐心生命的意义从来不是一个标准答案它更像是一场没有剧本的旅行你无法预知下一个站点会遇见什么也无法控制沿途的天气是否晴朗你能做的只是带着一颗开放的心勇敢走下去接受遇见的一切并在其中找到属于自己的答案而当你慢慢这样生活时你会惊讶地发现世界似乎也在悄然回应你给你更多的惊喜和美好我们每个人都在与时间赛跑却也都在与自己和解从青春的轻狂到中年的稳重再到老年的淡然每一个阶段都有它独特的价值与美丽没有什么是完全的遗憾也没有什么是彻底的圆满人生的意义就在于这种不完美中的坚持与探索当我们终于有一天回头去看那些走过的路会发现原来所谓的结果从来没有那么重要真正让人感动的始终是那些一路陪伴的风景和一路成长的自己所以请不要过于焦虑未来也不要过度执着过去珍惜当下的每一个笑容每一次拥抱每一份努力因为它们才是你生命中最真实的财富人生就像是一首没有句号的诗长短不一起承转合我们无法决定开头和结尾却能决定如何书写中间的篇章而这篇章也终将汇成属于你自己的故事无论是精彩还是平凡都是独一无二的存在当你明白这一点你就会更加从容更加勇敢地走向前方"
    }
    
    // MARK: - Action
    private func selectBirthday(){
        if let date = birthdayDate{
            birthdayPicker.setupDefaultSelectDate(date)
        }else if let dateStr = birthdayStr{
            let date = Date(dateString: dateStr, format: "yyyy-MM-dd")
            birthdayPicker.setupDefaultSelectDate(date)
        }
        
        birthdayPicker.show()
        birthdayPicker.tapConfirmAction = {[weak self] date, timestamp in
            // dlog("birthday date:\(date). timestamp:\(timestamp)")
            self?.birthdayDate = date
            self?.birthdayStr = date.toString(dateFormat: "yyyy-MM-dd")
        }
    }
    
    private func setupViews() {
        backButton = {
            let v = EPIconTertiaryButton(radius: .round, iconSize: .large, iconCode: .arrowLeftBorder)
            let size = v.bgImageSize()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom * 0.5 - 16)
                make.size.equalTo(CGSize(width: 88, height: size.height))
            }
            return v
        }()

        bottomButton = {
            let v = StyleButton(type: .custom)
            v.primary(size: .large)
            addSubview(v)
            v.snp.makeConstraints { make in
                // make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.leading.equalTo(backButton.snp.trailing).offset(16)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom * 0.5 - 16)
            }
            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 = 0
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
            }
            return v
        }()

        stepLabel = {
            let v = UILabel()
            v.font = CLSystemToken.font(token: .tlm)
            v.textColor = .c.ctsn
            v.text = "2/4"
            titleView.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalTo(titleView.titleLabel)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()

        nicknameTitleView = {
            let v = TitleTextField()
            container.stack.addArrangedSubview(v)
            // 2-20
            v.minLimit = 2
            v.maxLimit = 20
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()

        sexView = {
            let v = GenderSelectView()
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()
        
        sexSelectView = {
            let v = CLSelectView()
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            v.isHidden = true
            return v
        }()

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

        settingTextView = {
            let v = TitleTextView()
            /// 10~2000
            v.maxLimit = 4000
            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
        }()
        
        generateButton = {
            let v = TextButton()
            v.text = "自动生成"
            settingTextView.addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview()//.offset(-CGFloat.lrs)
                make.centerY.equalTo(settingTextView.titleLabel)
                make.height.equalTo(40)
            }
            return v
        }()

        titleView.title = "Character"
        nicknameTitleView.titleLabel.text = "Nickname"
        nicknameTitleView.placeholder = "对角色的称呼"
        nicknameTitleView.errorMsg = "昵称只能包含2-20字符"
        
        sexSelectView.titleLabel.text = "Sex"
        sexSelectView.showForceNormalSupportMsg("Gender can only modified once")
        sexSelectView.isEnabled = false
        
        birthdaySelectView.titleLabel.text = "Birthday"
        birthdaySelectView.placeholder = "请选择角色生日"
        bottomButton.setTitle("Next", for: .normal)
        settingTextView.titleLabel.text = "Setting"
        settingTextView.placeholder = "请描述角色的背景、性格、身份"
        settingTextView.errorMsg = "设定只能包含10-4000个字符"
    }
}
