//
//  RoleHomePagerHeader.swift

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

import UIKit

class RoleHomePagerHeader: UIView {
    var bgIvContainer: UIView!
    var bgIv: UIImageView!
    var overlay: GradientView!

    var userBasicInfoView: UIView!
    var avatarIv: AvatarView!
    var buttonStackH : UIStackView!
    private var iconButton : EPIconTertiaryButton!
    private var editButton: StyleButton!
    var nameLabel: UILabel!

    // tags
    var additionView: UIStackView!
    var ageLabel: CLIconLabel!
    var roleTags: [EPTagLabel] = []

    var heightChangeBlock: ((CGFloat) -> Void)?
    var tapEditAction: (() -> Void)?
    var tapChatAction: ((_ aiId:Int) -> Void)?

    // Data
    var info:AIRoleInfo?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

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

    private func setupViews() {
        bgIvContainer = {
            let v = UIView()
            v.clipsToBounds = true
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.leading.trailing.equalToSuperview()
                make.height.equalTo(264 + UIWindow.navBarHeight)
            }
            return v
        }()

        bgIv = {
            let v = UIImageView()
            v.clipsToBounds = true
            bgIvContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.leading.trailing.equalToSuperview()
                make.height.equalToSuperview().priority(.low)
            }
            return v
        }()

        overlay = {
            let gradient = CLSystemToken.gradient(token: .cob)
            let v = GradientView(colors: [gradient.firstColor!, gradient.secondColor!], gradientType: .topToBottom)
            bgIvContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.bottom.equalToSuperview()
                make.height.equalTo(160)
            }
            return v
        }()

        do {
            userBasicInfoView = {
                let v = UIView()
                addSubview(v)
                v.snp.makeConstraints { make in
                    make.leading.equalToSuperview().offset(24)
                    make.trailing.equalToSuperview().offset(-24)
                    make.top.equalTo(bgIvContainer.snp.bottom)
                    make.height.equalTo(64)
                }
                return v
            }()

            avatarIv = {
                let v = AvatarView()
                userBasicInfoView.addSubview(v)
                v.snp.makeConstraints { make in
                    make.leading.equalToSuperview()
                    make.centerY.equalToSuperview()
                    make.size.equalTo(CGSize(width: 64, height: 64))
                }
                return v
            }()
            
            buttonStackH = {
                let v = UIStackView()
                v.spacing = 12
                v.alignment = .center
                userBasicInfoView.addSubview(v)
                v.snp.makeConstraints { make in
                    make.centerY.equalToSuperview()
                    make.trailing.equalToSuperview()
                }
                return v
            }()
            
            iconButton = {
                let v = EPIconTertiaryButton(radius: .round, iconSize: .small, iconCode: .chat)
                v.addTarget(self, action: #selector(tapChatButton), for: .touchUpInside)
                buttonStackH.addArrangedSubview(v)
                v.isHidden = true
                return v
            }()

            editButton = {
                let v = StyleButton()
                v.addTarget(self, action: #selector(tapOperateButton), for: .touchUpInside)
                v.tertiary(size: .small)
                buttonStackH.addArrangedSubview(v)
                return v
            }()

            nameLabel = {
                let v = UILabel()
                v.textColor = .text
                v.font = .t.ttm
                v.setContentCompressionResistancePriority(UILayoutPriority(744), for: .horizontal)
                userBasicInfoView.addSubview(v)
                v.snp.makeConstraints { make in
                    make.centerY.equalToSuperview()
                    make.leading.equalTo(avatarIv.snp.trailing).offset(12)
                    //make.trailing.equalTo(buttonStackH.snp.leading).offset(-12)
                    make.trailing.lessThanOrEqualTo(buttonStackH.snp.leading).offset(-12)
                }
                return v
            }()
        }

        do {
            additionView = {
                let v = UIStackView()
                v.spacing = 8
                addSubview(v)
                v.snp.makeConstraints { make in
                    make.leading.equalToSuperview().offset(24)
                    make.trailing.lessThanOrEqualToSuperview().offset(-24)
                    make.top.equalTo(userBasicInfoView.snp.bottom).offset(12)
                }
                return v
            }()

            ageLabel = {
                let v = CLIconLabel()
                v.iconImageView.image = UIImage(named: "sex_female_flag")
                v.innerLRPadding = 4
                v.contentLabel.text = "-"
                v.backgroundColor = .c.csen
                v.layer.cornerRadius = 4;
                v.layer.masksToBounds = true
                return v
            }()
        }

        editButton.setTitle("Edit", for: .normal)

//        #warning("test")
//        testData()
    }

    private func testData() {
        bgIv.image = UIImage(named: "egpic")
        bgIv.snp.makeConstraints { make in
            // w:h=1024:1820
            make.width.equalTo(bgIv.snp.height).multipliedBy(1024.0 / 1820.0)
        }
        // avatarIv.image = UIImage(named: "egpic")
        nameLabel.text = "Angelique"

        do {
            let roleTag = EPTagLabel(style: .default, size: .small, text: "Sensibility")
            additionView.addArrangedSubview(roleTag)
        }
    }
    
    func config(info:AIRoleInfo?){
        self.info = info
        guard let data = info else {return}
                       
        bgIv.loadImage(data.homeImageUrl, completionBlock:  {[weak self] result in
            switch result {
            case .success(let success):
                let image = success.image
                self?.bgIv.snp.makeConstraints { make in
                    // w:h=1024:1820
                    make.width.equalTo((self?.bgIv.snp.height)!).multipliedBy(image.size.width / image.size.height)
                }
            case .failure(let failure):
                dlog(failure)
            }
        })
        
        if UserCore.shared.isSelf(id: data.userId){
            editButton.setTitle("Edit", for: .normal)
            editButton.tertiary(size: .small)
            iconButton.isHidden = false
        }else{
            editButton.setTitle("Chat", for: .normal)
            editButton.primary(size: .small)
            iconButton.isHidden = true
        }
        
        avatarIv.bindImageUrl(imgUrl: data.headImg)
        
        nameLabel.text = data.nickname
        
        // Reset
        additionView.removeSubviews()
        
        // Age
        let sex: Sex = data.sex ?? .noncomfirming
        ageLabel.iconImageView.image = sex.icon
        additionView.addArrangedSubview(ageLabel)
        
        if let birthday = data.birthday{
            let date = Date.dateFromMilliseconds(Int64(birthday))
            let age = Date().years(from: date)
            ageLabel.contentLabel.text = "\(age)"
        }
        
//        if !String.realEmpty(str: data.roleName){
//            let roleTag = EPTagLabel(style: .default, size: .small, text: data.roleName!)
//            additionView.addArrangedSubview(roleTag)
//        }
        
        if !String.realEmpty(str: data.characterName){
            let roleTag = EPTagLabel(style: .default, size: .small, text: data.characterName!)
            additionView.addArrangedSubview(roleTag)
        }
        
        if !String.realEmpty(str: data.tagName){
            let roleTag = EPTagLabel(style: .default, size: .small, text: data.tagName!)
            additionView.addArrangedSubview(roleTag)
        }
    }
    
    @objc private func tapOperateButton(){
        guard let data = info, let aiId = data.aiId else {return}
        if UserCore.shared.isSelf(id: data.userId){
            tapEditAction?()
        }else{
            tapChatAction?(aiId)
        }
        
    }
    
    @objc private func tapChatButton(){
        guard let data = info, let aiId = data.aiId else {return}
        tapChatAction?(aiId)
    }
    
    // MARK: - Other

    override func layoutSubviews() {
        super.layoutSubviews()
        let maxY = additionView.frame.maxY + 16
        heightChangeBlock?(maxY)
    }
}
