//
//  HeartBeatLevelGridHeadView.swift

//
//  Created by Leon on 2025/8/16.
//

import UIKit

class HeartBeatLevelGridHeadView: UIView{
    var bgIv : UIImageView!
    var avatarsHeartContainer:UIView!
    //var heartView : UIImageView! // 后面换成lottie
    var heartWave: HeartBeatAnimationView!
    
    var leftAvatar: CLImageView!
    var rightAvatar: CLImageView!
    
    var itemStackV: UIStackView!
    var statesStackH : UIStackView! // 1. in itemStackV
    var levelLabel : UILabel!
    var line: CLLine!
    var heartBeatLabel : UILabel!
    
    var progressStateContainer: UIView! // 2. in itemStackV
    var progressStateLabel: UILabel!
    
    var leftStackV : UIStackView! // 3. in itemStackV
    var heartBeatRankStateLabel: LineSpaceLabel!
    var retrieveContainer: UIView!
    var retrieveLabel: UILabel!
    var retrieveButton: TextButton!
    
    var heightChangeBlock: ((CGFloat) -> Void)?
    
    var data: AIUserHeartBeatRelation?
    
    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() {
        clipsToBounds = true
//        bgIv = {
//            let v = UIImageView()
//            v.image = UIImage(named: "heart_beat_level_bg")
//            addSubview(v)
//            v.snp.makeConstraints { make in
//                make.leading.top.trailing.equalToSuperview()
//                make.height.equalTo(v.snp.width).multipliedBy(393.0/400.0)
//            }
//            return v
//        }()
        
        heartWave = {
            let v = HeartBeatAnimationView()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.top.trailing.equalToSuperview()
            }
            return v
        }()
        
        avatarsHeartContainer = {
            let v = UIView()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.height.equalTo(120)
                make.leading.equalToSuperview().offset(24)
                make.trailing.equalToSuperview().offset(-24)
                make.top.equalToSuperview().offset(UIWindow.navBarTotalHeight + 12)
            }
            return v
        }()
//        heartView = {
//            let v = UIImageView()
//            v.image = UIImage(named: "heart_wave")
//            avatarsHeartContainer.addSubview(v)
//            v.snp.makeConstraints { make in
////                make.centerY.equalToSuperview()
//                make.center.equalToSuperview()
//            }
//            return v
//        }()
        
        leftAvatar = {
            let v = CLImageView(frame: .zero)
            let wh = 64.0
            v.layer.cornerRadius = wh*0.5
            v.layer.masksToBounds = true
            v.backgroundColor = .c.csbn
            avatarsHeartContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                //make.top.equalToSuperview().offset(134)
                make.size.equalTo(CGSize(width: wh, height: wh))
                make.centerX.equalToSuperview().offset(-108)
            }
            return v
        }()
        
        rightAvatar = {
            let v = CLImageView(frame: .zero)
            let wh = 64.0
            v.layer.cornerRadius = wh*0.5
            v.layer.masksToBounds = true
            v.backgroundColor = .c.csbn
            avatarsHeartContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: wh, height: wh))
                make.centerY.equalTo(leftAvatar)
                make.centerX.equalToSuperview().offset(108)
            }
            return v
        }()
        
        itemStackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.spacing = 16
            v.alignment = .center
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalTo(avatarsHeartContainer.snp.bottom)
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()
        
        statesStackH = {
            let v = UIStackView()
            v.spacing = 16
            v.alignment = .center
            itemStackV.addArrangedSubview(v)
            return v
        }()
        
        levelLabel = {
            let v = UILabel()
            v.font = .t.tndm
            v.textColor = .text
            statesStackH.addArrangedSubview(v)
            return v
        }()
        
        line = {
            let v = CLLine()
            v.backgroundColor = .c.con
            statesStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.width.equalTo(1)
                make.height.equalTo(18)
            }
            return v
        }()
        line.isHidden = false
        
        heartBeatLabel = {
            let v = UILabel()
            v.font = .t.tndm
            v.textColor = .text
            statesStackH.addArrangedSubview(v)
            return v
        }()
        
        progressStateContainer = {
            let v = UIView()
            itemStackV.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.height.equalTo(24)
                make.leading.trailing.equalToSuperview()
            }
            return v
        }()
        
        progressStateLabel = {
            let v = UILabel()
            v.font = .t.tds
            v.textColor = .text
            progressStateContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
            }
            
            let leftLine = {
                let line1 = UIView()
                line1.backgroundColor = .c.con
                progressStateContainer.addSubview(line1)
                line1.snp.makeConstraints { make in
                    make.leading.equalToSuperview().offset(0)
                    make.trailing.equalTo(v.snp.leading).offset(-12)
                    make.centerY.equalTo(v)
                    make.height.equalTo(1)
                }
                return line1
            }()
            
            let rightLine = {
                let line2 = UIView()
                line2.backgroundColor = .c.con
                progressStateContainer.addSubview(line2)
                line2.snp.makeConstraints { make in
                    make.trailing.equalToSuperview().offset(0)
                    make.leading.equalTo(v.snp.trailing).offset(12)
                    make.centerY.equalTo(v)
                    make.height.equalTo(1)
                }
                return line2
            }()
            leftLine.isHidden = false
            rightLine.isHidden = false
            
            return v
        }()
        
        leftStackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.spacing = 24
            itemStackV.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
            }
            return v
        }()
        
        heartBeatRankStateLabel = {
            let v = LineSpaceLabel()
            v.textColor = .text
            let typo = CLSystemToken.typography(token: .tbs)
            v.textAlignment = .center
            v.config(typo)
            leftStackV.addArrangedSubview(v)
            return v
        }()
        
        retrieveContainer = {
            let v = UIView()
            v.backgroundColor = .c.csbn
            v.layer.cornerRadius = 12
            v.layer.masksToBounds = true
            leftStackV.addArrangedSubview(v)
            v.isHidden = true
            return v
        }()
        
        retrieveButton = {
            let v = TextButton()
            v.titleLabel?.font = .t.tls
            retrieveContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.trailing.equalToSuperview().offset(-16)
            }
            return v
        }()
        
        retrieveLabel = {
            let v = UILabel()
            v.font = .t.tbs
            v.textColor = .text
            retrieveContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.top.equalToSuperview().offset(16)
                make.bottom.equalToSuperview().offset(-16)
                make.trailing.lessThanOrEqualTo(retrieveButton.snp.leading).offset(-12)
            }
            return v
        }()
        
        
        progressStateLabel.text = "· Meet ·"
        retrieveButton.text = "Retrieve"
    }
    
    
    
    private func setupData(){
        // testData()
    }
    
    private func testData(){
        heartBeatLabel.text = "35.6℃"
        levelLabel.text = "Lv.1"
        heartBeatRankStateLabel.text = "8 days of acquaintance | Heartbeat score more than 99.99% of the interlocutors"
        retrieveLabel.text = "Deducted cardiac value: -35.0℃"
    }
    
    private func setupEvent(){
        
    }
    
    // MARK: Public
    func config(_ relation: AIUserHeartBeatRelation?){
        data = relation
        guard let info = relation else{
            return
        }
        
        // 波浪
        let heartPercent = info.getHeartbeatWavePercent()
        heartWave.percent = heartPercent
        
        //..
        leftAvatar.loadImage(info.aiHeadImg)
        rightAvatar.loadImage(info.userHeadImg)
        
        
        
        
        if info.heartbeatLevel != nil{ // 有心动等级
            levelLabel.isHidden = false
            line.isHidden = false
            levelLabel.text = info.heartbeatLevel?.localizedText
            
            let value = info.formatHeartBeatVal()
            let heartBeatValueAStr = value.withAttributes([.font(UIFont.t.tndm)])
            let ranges = value.matchStrRange(AIUserHeartBeatRelation.unitOfHeartBeatVal())
            if let range = ranges.first{
                let att = [NSAttributedString.Key.font: UIFont.t.tnms]
                heartBeatValueAStr.addAttributes(att, range: range)
            }
            heartBeatLabel.attributedText = heartBeatValueAStr
            
            if info.isShow.boolValue{
                progressStateContainer.isHidden = false
                progressStateLabel.text = "· \(info.heartbeatLevel?.relationType.localizedText ?? "") · "
            }else{
                progressStateContainer.isHidden = true
            }
        }else{
            levelLabel.isHidden = true
            line.isHidden = true
            
            let value = "0℃"
            let heartBeatValueAStr = value.withAttributes([.font(UIFont.t.tndm)])
            let ranges = value.matchStrRange(AIUserHeartBeatRelation.unitOfHeartBeatVal())
            if let range = ranges.first{
                let att = [NSAttributedString.Key.font: UIFont.t.tnms]
                heartBeatValueAStr.addAttributes(att, range: range)
            }
            heartBeatLabel.attributedText = heartBeatValueAStr
            
            progressStateContainer.isHidden = false
            progressStateLabel.font = .t.tts
            progressStateLabel.text = "No intention yet"
        }

        // 描述
        let days = info.dayCount ?? 0
        let heartBeatScore = info.heartbeatScore ?? 0.999999
        heartBeatRankStateLabel.text = "\(days) days of acquaintance | Heartbeat score more than \(heartBeatScore.formatted(decimal: 2, asPercent: true)) of the interlocutors"
        
        // 扣减值、扣减区域
        let subtractHeartbeatVal = info.fixedSubtractHeartbeatVal
        if subtractHeartbeatVal > 0{
            retrieveContainer.isHidden = false
            let fixDisplay = info.fixedSubtractHeartbeatValDisplay
            retrieveLabel.text = "Deducted cardiac value: -\(fixDisplay)"
        }
        
        layoutIfNeeded()
    }
    
    // MARK: Other
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let maxY = itemStackV.frame.maxY + 16
        heightChangeBlock?(maxY)
    }
}
