//
//  RetrieveHeartbeatSheet.swift

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

import UIKit

class RetrieveHeartbeatSheet: EGPopBaseView {
    var closeButton: EPIconTertiaryButton!
    var heartWave : HeartBeatAnimationView!
    var titleLabel:UILabel!
    
    
    var stackV : UIStackView!
    // content 1: numberscontent
    var priceLabel: UILabel!
    
    var quantityContentLabel: UILabel!
    
    // content 3: total Price
    var totalPriceLabel: UILabel!
    
    var button:StyleButton!
    
    var aiId: Int?
    // @Requrired
    var data: AIUserHeartBeatRelation?
    
    init() {
        super.init(direction: .bottom)
        contentView.backgroundColor = .c.cbd
        contentLength = 444 + UIWindow.safeAreaBottom
        
        closeButton = {
            let v = EPIconTertiaryButton(radius: .round, iconSize: .small, iconCode: .delete)
            v.addTarget(self, action: #selector(bgButtonPressed), for: .touchUpInside)
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(20)
                make.size.equalTo(v.bgImageSize())
                make.trailing.equalToSuperview().offset(-16)
            }
            return v
        }()
        
        heartWave = {
            let v = HeartBeatAnimationView()
            contentView.insertSubview(v, at: 0)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(-84)
            }
            return v
        }()

        titleLabel = {
            let v = UILabel()
            contentView.addSubview(v)
            v.text = "Retrieve heart value"
            v.font = .t.tts
            v.textColor = .text
            v.textAlignment = .center
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(24)
                make.trailing.equalToSuperview().offset(-24)
                make.top.equalToSuperview().offset(156)
            }
            v.numberOfLines = 0
            return v
        }()
        
        stackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.spacing = 0
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(24)
                make.trailing.equalToSuperview().offset(-24)
                make.top.equalTo(titleLabel.snp.bottom).offset(24)
            }
            return v
        }()
        
        do{
            let priceView = {
                let v = UIView()
                stackV.addArrangedSubview(v)
                v.snp.makeConstraints { make in
                    make.height.equalTo(48)
                }
                return v
            }()
            
            let tipLabel = {
                let label = UILabel()
                label.font = .t.tll
                label.textColor = .text
                priceView.addSubview(label)
                label.snp.makeConstraints { make in
                    make.leading.equalToSuperview()
                    make.centerY.equalToSuperview()
                }
                return label
            }()
            tipLabel.text = "Unit price"
            
            priceLabel = {
                let v = UILabel()
                v.font = .t.tll
                v.textColor = .text
                priceView.addSubview(v)
                v.snp.makeConstraints { make in
                    make.trailing.equalToSuperview()
                    make.centerY.equalToSuperview()
                }
                return v
            }()

            let coinIv = {
                let v = UIImageView()
                priceView.addSubview(v)
                v.snp.makeConstraints { make in
                    make.trailing.equalTo(priceLabel.snp.leading).offset(-8)
                    make.centerY.equalToSuperview()
                }
                return v
            }()
            coinIv.image = UIImage(named: "icon_16_diamond")
        }

        setupQuantityView()

        do{
            let priceView = {
                let v = UIView()
                stackV.addArrangedSubview(v)
                v.snp.makeConstraints { make in
                    make.height.equalTo(48)
                }
                return v
            }()
            
            let tipLabel = {
                let label = UILabel()
                label.font = .t.tll
                label.textColor = .text
                priceView.addSubview(label)
                label.snp.makeConstraints { make in
                    make.leading.equalToSuperview()
                    make.centerY.equalToSuperview()
                }
                return label
            }()
            tipLabel.text = "Total"
            
            totalPriceLabel = {
                let v = UILabel()
                v.font = .t.tll
                v.textColor = .text
                priceView.addSubview(v)
                v.snp.makeConstraints { make in
                    make.trailing.equalToSuperview()
                    make.centerY.equalToSuperview()
                }
                v.text = "0"
                return v
            }()

            let coinIv = {
                let v = UIImageView()
                v.image = UIImage(named: "icon_16_diamond")
                priceView.addSubview(v)
                v.snp.makeConstraints { make in
                    make.trailing.equalTo(totalPriceLabel.snp.leading).offset(-8)
                    make.centerY.equalToSuperview()
                }
                return v
            }()
            coinIv.isHidden = false
        }


        button = {
            let v = StyleButton()
            v.primary(size: .large)
            contentView.addSubview(v)
            v.setTitle("Purchase", for: .normal)
            v.addTarget(self, action: #selector(operateAction), for: .touchUpInside)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(24)
                make.trailing.equalToSuperview().offset(-24)
                //make.top.equalTo(titleLabel.snp.bottom).offset(24)
                make.bottom.equalToSuperview().offset(-16-UIWindow.safeAreaBottom*0.5)
            }
            return v
        }()

        let price = 5
        let priceLabelText = "\(price)"
        priceLabel.text = priceLabelText
        
        setupEvent()
        
//#warning("test")
//        testData()
    }

    private func setupQuantityView(){
        let quantityView = {
            let v = UIView()
            stackV.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.height.equalTo(72)
            }
            return v
        }()
        
        let quantityLabel = {
            let v = UILabel()
            v.font = .t.tll
            v.textColor = .text
            quantityView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        quantityContentLabel = {
            let v = UILabel()
            v.font = .t.tll
            v.textColor = .text
            quantityView.addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview()
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        quantityLabel.text = "Quantity"
        quantityContentLabel.text = "-℃"

    }
    
    private func setupEvent(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChanged(noti:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
    }

    private func testData(){
        let price = 5
        let priceLabelText = "\(price)"
        //let coinLabelText = "\(coin) Coins"
        priceLabel.text = priceLabelText
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Public
    override func show() {
        super.show()
    }
    
    func config(_ data: AIUserHeartBeatRelation?){
        self.data = data
        
            // 单价
        let unitPrice = data?.price ?? 500
        let unitCoin = Coin(cents: unitPrice)
        priceLabel.text = unitCoin.formatted
        
        let heartPercent = data?.getHeartbeatWavePercent() ?? 0.1
        heartWave.percent = heartPercent
        
        quantityContentLabel.text = data?.fixedSubtractHeartbeatValDisplay ?? "-"
        
        let quality = data?.fixedSubtractHeartbeatVal ?? 0
        let price = quality * Double(unitPrice)
        
        var fixPrice = price * 0.01
        if fixPrice > 1{
            fixPrice = floor(fixPrice)
        }else{
            fixPrice = max(1, fixPrice)
        }
        
        let coin = Coin(usd: fixPrice)
        totalPriceLabel.text =  coin.formatted
    }
    
    // MARK: - Action
    @objc func operateAction(){
//        guard let aiId = data
        guard let subtractHeartbeatVal = data?.subtractHeartbeatVal, let theAiId = aiId else{
            return
        }
        Hud.showIndicator()
        
        AIRoleProvider.request(.heartBeatPurchase(aiId: theAiId, heartBeatVal: subtractHeartbeatVal), modelType: EmptyModel.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                NotificationCenter.post(name: .aiRoleRelationInfoUpdated)
                self?.dismiss()
            case .failure:
                break
            }
        }
    }
    
    @objc func keyboardWillChanged(noti: Notification) {
        guard let userInfo = noti.userInfo else { return }
        //let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
        let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        
        if endFrame.origin.y >= UIScreen.main.bounds.height {
            bottomKeyboardHeight = 0
            refreshLPositon()
        }else{
            bottomKeyboardHeight = endFrame.height
            refreshLPositon()
        }
    }

}
