//
//  MeetMatchedController.swift

//
//  Created by Leon on 2025/9/10.
//

import UIKit

class MeetMatchedController: CLBaseViewController {
    var bgImageView: CLImageView!
    var effectView: UIVisualEffectView!

    var titleWordsContainer: UIView!
    var nameAndAgeLabel: CLLabel!
    var likeAndCountLabel: CLIconLabel!

    var bottomButtonsStackV: UIStackView!
    var chatButton: StyleButton!
    var cancelButton: StyleButton!

    // -- 中间部分
    var middleContainer: UIView!
    var middleStackV: UIStackView!
    // - Avatar
    var avatarsContainer: UIView!
    var avatarsStackH: UIStackView!
    var leftAvatar: CLImageView!
    var rightAvatar: CLImageView!
    var heartIcon: UIImageView!
    // - Gift （可选）
    var giftIcon: UIImageView!
    // 赠送的礼物数量（可选
    var giftCountBadge: BadgeView!
    // - Matched
    var matchedContainer: UIView!
    var matchedLabel: ColorLabel!
    // - Desc
    var descLabel: CLLabel!
    
    // - Data
    var card: MeetCard?
    var info: MeetMatchInfo?
    
    // 可选
    var gift: GiftDictModel?
    // 礼物数量
    var giftCount: Int = 0
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        setupViews()
        setupDatas()
        setupEvents()
    }

    private func setupViews() {
        navigationView.backButton.isHidden = true
        navigationView.bgView.alpha = 0
        
        bgImageView = {
            let v = CLImageView()
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()

        effectView = {
            let v = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
            v.alpha = 1
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()

        titleWordsContainer = {
            let v = UIView()
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalTo(navigationView.snp.bottom)
                make.height.equalTo(60)
            }
            return v
        }()

        nameAndAgeLabel = {
            let v = CLLabel()
            v.font = .t.ttm
            v.textAlignment = .center
            titleWordsContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.trailing.equalToSuperview().offset(-16)
                make.top.equalToSuperview()
            }
            return v
        }()

        likeAndCountLabel = {
            let v = CLIconLabel()
            v.iconSize = CGSize(width: 20, height: 20)
            v.iconImageView.image = MWIconFont.image(fromIcon: .like, size: CGSize(width: 20, height: 20), color: .white)
            v.contentLabel.font = .t.tnds
            v.contentLabel.text = "-"
            titleWordsContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.bottom.equalToSuperview()
                make.centerX.equalToSuperview()
            }
            return v
        }()

        bottomButtonsStackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.spacing = 24
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(48)
                make.trailing.equalToSuperview().offset(-48)
                make.bottom.equalToSuperview().offset(-16 - UIWindow.safeAreaBottom * 0.5)
            }
            return v
        }()

        chatButton = {
            let v = StyleButton()
            v.primary(size: .large)
            v.addTarget(self, action: #selector(chatButtonAction), for: .touchUpInside)
            bottomButtonsStackV.addArrangedSubview(v)
            return v
        }()

        cancelButton = {
            let v = StyleButton()
            v.tertiary(size: .large)
            v.addTarget(self, action: #selector(cancelButtonAction), for: .touchUpInside)
            bottomButtonsStackV.addArrangedSubview(v)
            return v
        }()

        middleContainer = {
            let v = UIView()
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalTo(titleWordsContainer.snp.bottom)
                make.bottom.equalTo(bottomButtonsStackV.snp.top).offset(0)
            }
            return v
        }()

        middleStackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.alignment = .center
            middleContainer.addSubview(v)
            v.snp.makeConstraints { make in
                //make.centerX.equalToSuperview()
                make.leading.equalToSuperview().offset(48)
                make.trailing.equalToSuperview().offset(-48)
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        avatarsContainer = {
            let v = UIView()
            middleStackV.addArrangedSubview(v)
//            v.snp.makeConstraints { make in
//                make.height.equalTo(128)
//            }
            return v
        }()
        
        avatarsStackH = {
            let v = UIStackView()
            v.axis = .horizontal
            v.spacing = 16
            avatarsContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
                make.height.equalTo(128)
            }
            return v
        }()
        
        leftAvatar = {
            let v = CLImageView()
            v.cornerRadius = 64
            avatarsStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.width.equalTo(128)
                make.height.equalTo(128)
            }
            return v
        }()

        rightAvatar = {
            let v = CLImageView()
            v.cornerRadius = 64
            avatarsStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.width.equalTo(128)
                make.height.equalTo(128)
            }
            return v
        }()

        heartIcon = {
            let v = UIImageView()
            v.image = UIImage(named: "chat_level_heart")
            avatarsContainer.addSubview(v)
            v.snp.makeConstraints { make in
//                make.centerX.equalToSuperview()
                make.center.equalToSuperview()
                make.size.equalTo(CGSize(width:60, height: 60))
            }
            return v
        }()

        giftIcon = {
            let v = UIImageView()
            v.image = UIImage(named: "chat_level_gift")
            middleStackV.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width:72, height: 72))
            }
            return v
        }()
        
        giftCountBadge = {
            let v = BadgeView()
            giftIcon.addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(4)
            }
            return v
        }()

        matchedContainer = {
            let v = UIView()
            middleStackV.addArrangedSubview(v)
            return v
        }()

        matchedLabel = {
            let v = ColorLabel()
            v.applyGradient(.theme)
            v.font = .t.tdxl
            v.textColor = .white
            matchedContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(24)
                make.bottom.equalToSuperview()
            }
            return v
        }()

        descLabel = {
            let v = CLLabel()
            v.font = .t.tbm
            v.textAlignment = .center
            v.textColor = .white
            v.numberOfLines = 2
            middleStackV.addArrangedSubview(v)
            return v
        }()

//        view.backgroundColor = .clear
        
        chatButton.setTitle("Chat", for: .normal)
        cancelButton.setTitle("Cancel", for: .normal)
        matchedLabel.text = "Matched"
        
//        #warning("test")
//        testData()
    }
    
    private func testData(){
        nameAndAgeLabel.text = "Angelique, 28"
        giftCountBadge.badgeValue = 99
        descLabel.text = "Thank you for your 99 gift names"
        likeAndCountLabel.contentLabel.text = "1.2k"
    }

    private func setupDatas() {
        
        rightAvatar.loadImage(UserCore.shared.user?.headImage)
        
        // 配置数据
        configCardData()
        configGiftData()
    }

    private func setupEvents() {
    }

    // MARK: - Data Configuration
    
    /// 配置卡片数据
    private func configCardData() {
        
        if let data = self.card {
            // 配置姓名和年龄
            if let nickname = data.nickname, let age = data.age {
                nameAndAgeLabel.text = "\(nickname), \(age)"
                
            } else if let nickname = data.nickname {
                nameAndAgeLabel.text = nickname
            }
            
            descLabel.text = "You and \(data.nickname ?? "-") are moved by each other"
            
            // 配置点赞数
            if let likedCount = data.likedCount {
                let displayCount = String.displayNumber(NSNumber(value: likedCount), scale: 1)
                likeAndCountLabel.contentLabel.text = displayCount
            }
            
            bgImageView.loadImage(data.imageUrl)
            leftAvatar.loadImage(data.headImg)
        }
        else if let data = info{
            if let nickname = data.nickname, let birthday = data.birthday {
                let date = Date.dateFromMilliseconds(Int64(birthday))
                let ageYears = Date().years(from: date)
                nameAndAgeLabel.text = "\(nickname), \(ageYears)"
                
            } else if let nickname = data.nickname {
                nameAndAgeLabel.text = nickname
            }
            
            descLabel.text = "You and \(data.nickname ?? "-") are moved by each other"
            
            // 配置点赞数
            if let likedCount = data.likedCount {
                let displayCount = String.displayNumber(NSNumber(value: likedCount), scale: 1)
                likeAndCountLabel.contentLabel.text = displayCount
            }
            
            bgImageView.loadImage(data.homeImageUrl)
            leftAvatar.loadImage(data.headImg)
        }
    }
    
    /// 配置礼物数据
    private func configGiftData() {
        guard let gift = gift else {
            // 如果没有礼物，隐藏礼物相关UI
            giftIcon.isHidden = true
            giftCountBadge.isHidden = true
            return
        }
        
        // 显示礼物图标
        giftIcon.isHidden = false
        giftIcon.loadImage(gift.icon, bgColor: .clear)
        
        // 配置礼物数量徽章
        if giftCount > 0 {
            giftCountBadge.isHidden = false
            giftCountBadge.badgeValue = giftCount
        } else {
            giftCountBadge.isHidden = true
        }
        
        // 更新描述文本，包含礼物信息
        if let giftName = gift.name, giftCount > 0 {
            let giftText = "Thank you for your \(giftCount) \(giftName)"
            descLabel.text = giftText
        }else if let giftName = gift.name{
            let giftText = "Thank you for your \(giftName)"
            descLabel.text = giftText
        }
    }
    
    /// 公共方法：配置页面数据
    func configData(card: MeetCard?, gift: GiftDictModel?, giftCount: Int = 0) {
        self.card = card
        self.gift = gift
        self.giftCount = giftCount
        
        // 重新配置数据
        configCardData()
        configGiftData()
    }

    // MARK: - Action

    @objc func chatButtonAction() {
        guard let aiId = card?.aiId else{
            dismiss(animated: false)
            return
        }
        self.dismiss(animated: true) {
            AppRouter.goChatVC(aiId: aiId)
        }
    }

    @objc func cancelButtonAction() {
//        self.removeFromParent()
//        self.view.removeFromSuperview()
        close()
    }
}
