//
//  PersonInformationEditView.swift

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

import UIKit
import DateToolsSwift
import Combine

class PersonInformationEditView: UIView{
    lazy var birthdayPicker:BirthdayPickerView = BirthdayPickerView()
    
    var bottomButton: StyleButton!

    var container: LTScrollContainer!
    var titleView: TitleView!
    var nicknameTitleField: TitleTextField!
    var sexView : CLSelectView!
    var birthdaySelectView: CLSelectView!
    
    // Data
    
    @Published var nickname: String?
    @Published var birthdayDate: Date?
    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)
            }
            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
        }()
        
        nicknameTitleField = {
            let v = TitleTextField()
            v.maxLimit = 20
            v.minLimit = 2
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()
        
        sexView = {
            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
        }()
        
        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
        }()
        
        titleView.title = "login.personal.information".localized()

        nicknameTitleField.titleLabel.text = "nickname".localized()
        nicknameTitleField.placeholder = "Nickname"
        
        sexView.titleLabel.text = "Sex"
        sexView.showForceNormalSupportMsg("Gender can only modified once")
        sexView.isEnabled = false

        birthdaySelectView.titleLabel.text = "Birthday"
        birthdaySelectView.placeholder = "Birthday"

        bottomButton.setTitle("Submit", for: .normal)
        
    }
    
    private func setupData(){
        guard let user = UserCore.shared.user else{return}
        
        nickname = user.nickname
        if let timestamp = user.birthday{
            birthdayDate = Date.dateFromMilliseconds(timestamp)
        }
        
        self.sexView.contentStr = user.sex.localizedText
        
//        nicknameTitleField.textfield.text = user.nickname
//        if let birthdayStr = user.birthday {
//            let date = Date(dateString: birthdayStr, format: "yyyy-mm-dd")
//            let formated = date.toString(dateFormat: "dd MMM, yyyy")
//            birthdaySelectView.contentStr = formated
//        }
    }
    
    private func setupEvent(){
        birthdaySelectView.selectBlock = {[weak self] in
            self?.selectBirthday()
        }
        
        $nickname.sink { [weak self] str in
            self?.nicknameTitleField.textfield.text = str
        }.store(in: &cancellables)
        
        $birthdayDate.sink {[weak self] date in
            guard let validDate = date else{return}
            let years = Date().years(from:validDate)
            if years < 18{
                self?.birthdaySelectView.showErrorMsg("Must be at least 18 years old.")
            }else{
                self?.birthdaySelectView.hideErrorInfo()
            }
            let formated = validDate.toString(dateFormat: "dd MMM, yyyy")
            self?.birthdaySelectView.contentStr = formated
        }.store(in: &cancellables)
        
        nicknameTitleField.textfield.textPublisher.sink {[weak self] str in
            self?.nickname = str?.trimmed
        }.store(in: &cancellables)
    }
    
    private func selectBirthday(){
        if let birthdayTimestamp = UserCore.shared.user?.birthday{
            let date = Date.dateFromMilliseconds(birthdayTimestamp)
            birthdayPicker.setupDefaultSelectDate(date)
        }
        birthdayPicker.show()
        
        birthdayPicker.tapConfirmAction = {[weak self] date, timestamp in
            dlog("birthday date:\(date). timestamp:\(timestamp)")
            // self?.birthdayStr = date.toString(dateFormat: "yyyy-MM-dd")
            self?.birthdayDate = date
        }
    }
}
