//
//  ChatButtleCollectionCell.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/10/30.
//

import UIKit
import SnapKit

struct SubButtleRow: RowModel {
    let subItems: [ChatButtleRow]
    var cellReuseID: String { "ChatButtleCollectionCell" }
    func cellHeight(tableWidth: CGFloat) -> CGFloat {
        let maxDisplayCount = 4
        let displayCount = min(subItems.count, maxDisplayCount)
        return CGFloat(displayCount) * 58 // 每行40高度
    }
}

// MARK: - 数据模型
struct ChatButtleItem {
    let id: String
    let name: String
    let price: Int?
    enum Kind { case `default`, vip, premium }
    enum Status { case selected, available, locked, gettable }
    let kind: Kind
    let status: Status
}

// MARK: - RowModel
struct ChatButtleRow: RowModel {
    let id: String
    let name: String
    let price: Int?
    enum Kind { case `default`, vip, premium }
    enum Status { case selected, available, locked, gettable }
    let kind: Kind
    let status: Status
    
    let items: [ChatButtleRow] = []
    var cellReuseID: String { "ChatButtleCollectionCell" }
    func cellHeight(tableWidth: CGFloat) -> CGFloat {
        let columns: CGFloat = 3
        let spacing: CGFloat = 8
        let horizontalPadding: CGFloat = 40 // container 左右各 20
        let availableWidth = tableWidth - horizontalPadding
        _ = (availableWidth - spacing * (columns - 1)) / columns // width 未用到，但保留用于后续等比计算
        let itemHeight: CGFloat = 120
        let rows = ceil(CGFloat(items.count) / columns)
        let displayRows = min(rows, 4.5)
        let total = displayRows * itemHeight + (displayRows - 1) * spacing + 5
        return total
    }
}

// MARK: - 容器 Cell
class ChatButtleCollectionCell: UITableViewCell, CellConfigurable {
    private var items: [ChatButtleRow] = []
    private var selectedId: String?
    private let widthItem: CGFloat = ((UIScreen.width * 0.84 - 60.0) / 3.0 - 1.0)
    private var heightConstraint: Constraint?
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        layout.itemSize = CGSizeMake(widthItem, widthItem * 110.0 / 87.0)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        layout.scrollDirection = .vertical
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.delegate = self
        cv.dataSource = self
        cv.showsVerticalScrollIndicator = false
        cv.register(ChatButtleCard.self, forCellWithReuseIdentifier: "ChatButtleCard")
        cv.layer.cornerRadius = 15
        cv.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        return cv
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        backgroundColor = .clear
        selectionStyle = .none
        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.bottom.equalToSuperview().inset(2.5)
            heightConstraint = make.height.equalTo(0).constraint
        }
    }
    
    func configure(with row: RowModel) {
        guard let r = row as? SubButtleRow else { return }
        items = r.subItems
        if let first = items.first(where: { $0.status == .selected || $0.status == .available }) {
            selectedId = first.id
        }
        collectionView.reloadData()
        updateHeight()
    }
    
    private func updateHeight() {
        let columns: CGFloat = 3
        let spacing: CGFloat = 10
        let availableWidth = UIScreen.width * 0.84 - 60.0
        _ = (availableWidth - spacing * (columns - 1)) / columns
        let itemHeight: CGFloat = widthItem * 110.0 / 87.0
        let rows = ceil(CGFloat(items.count) / columns)
        let displayRows = min(rows, 4.5)
        let total = displayRows * itemHeight + (displayRows - 1) * spacing + 5
        heightConstraint?.update(offset: total)
        layoutIfNeeded()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        updateHeight()
    }
}

// MARK: - CollectionView
extension ChatButtleCollectionCell: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { items.count }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChatButtleCard", for: indexPath) as! ChatButtleCard
        let item = items[indexPath.item]
        cell.configure(with: item, selected: item.id == selectedId)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let item = items[indexPath.item]
        guard item.status == .available || item.status == .gettable else { return }
        selectedId = item.id
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let columns: CGFloat = 3
        let spacing: CGFloat = 10
        let availableWidth = UIScreen.width * 0.84 - 60.0
        let itemWidth = (availableWidth - spacing * (columns - 1)) / columns
        return CGSize(width: itemWidth, height: widthItem * 110.0 / 87.0)
    }
}

// MARK: - 卡片
//class ChatButtleCard: UICollectionViewCell {
//    private lazy var container: UIView = {
//        let v = UIView()
//        v.backgroundColor = UIColor(hex: "#1A1A2E")
//        v.layer.cornerRadius = 12
//        return v
//    }()
//    private lazy var bubble: UIView = {
//        let v = UIView()
//        v.backgroundColor = .white
//        v.layer.cornerRadius = 20
//        return v
//    }()
//    private lazy var hiLabel: UILabel = {
//        let l = UILabel()
//        l.text = "hi"
//        l.textColor = .black
//        l.font = UIFont.systemFont(ofSize: 14, weight: .medium)
//        return l
//    }()
//    private lazy var title: UILabel = {
//        let l = UILabel()
//        l.textColor = .white
//        l.font = UIFont.systemFont(ofSize: 12, weight: .medium)
//        l.textAlignment = .center
//        return l
//    }()
//    private lazy var vipBadge: UILabel = {
//        let l = UILabel()
//        l.text = "VIP"
//        l.textColor = .black
//        l.font = UIFont.systemFont(ofSize: 10, weight: .bold)
//        l.backgroundColor = UIColor(hex: "#FFD700")
//        l.textAlignment = .center
//        l.layer.cornerRadius = 8
//        l.clipsToBounds = true
//        l.isHidden = true
//        return l
//    }()
//    private lazy var lockIcon: UIImageView = {
//        let v = UIImageView(image: UIImage(systemName: "lock.fill"))
//        v.tintColor = UIColor(hex: "#999999")
//        v.isHidden = true
//        return v
//    }()
//    private lazy var getButton: UIButton = {
//        let b = UIButton(type: .custom)
//        b.setTitle("Get", for: .normal)
//        b.setTitleColor(.white, for: .normal)
//        b.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .bold)
//        b.backgroundColor = UIColor(hex: "#8B5CF6")
//        b.layer.cornerRadius = 8
//        b.isHidden = true
//        return b
//    }()
//    private lazy var highlight: UIView = {
//        let v = UIView()
//        v.layer.borderWidth = 2
//        v.layer.borderColor = UIColor(hex: "#8B5CF6").cgColor
//        v.layer.cornerRadius = 12
//        v.isHidden = true
//        return v
//    }()
//    
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        setup()
//    }
//    required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
//    
//    private func setup() {
//        contentView.addSubview(container)
//        container.addSubview(bubble)
//        container.addSubview(hiLabel)
//        container.addSubview(title)
//        container.addSubview(vipBadge)
//        container.addSubview(lockIcon)
//        container.addSubview(getButton)
//        container.addSubview(highlight)
//        
//        container.snp.makeConstraints { make in make.edges.equalToSuperview() }
//        bubble.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.centerY.equalToSuperview().offset(-10)
//            make.width.height.equalTo(40)
//        }
//        hiLabel.snp.makeConstraints { make in make.center.equalTo(bubble) }
//        title.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.bottom.equalToSuperview().offset(-12)
//            make.left.right.equalToSuperview().inset(6)
//        }
//        vipBadge.snp.makeConstraints { make in
//            make.top.left.equalToSuperview().offset(8)
//            make.width.equalTo(24)
//            make.height.equalTo(16)
//        }
//        lockIcon.snp.makeConstraints { make in
//            make.top.right.equalToSuperview().inset(8)
//            make.width.height.equalTo(12)
//        }
//        getButton.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.bottom.equalToSuperview().offset(-8)
//            make.width.equalTo(60)
//            make.height.equalTo(24)
//        }
//        highlight.snp.makeConstraints { make in make.edges.equalToSuperview() }
//    }
//    
//    func configure(with item: ChatButtleItem, selected: Bool) {
//        title.text = item.name
//        vipBadge.isHidden = item.kind != .vip
//        lockIcon.isHidden = item.status != .locked
//        getButton.isHidden = item.status != .gettable
//        highlight.isHidden = !selected && item.status != .gettable
//        if item.kind == .premium { title.textColor = UIColor(hex: "#0066FF") } else if item.kind == .vip { title.textColor = UIColor(hex: "#FF8C00") } else { title.textColor = .white }
//        title.isHidden = item.status == .gettable
//    }
//}

//
//  ChatButtleCollectionCell.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/10/30.
//

class ChatButtleCard: UICollectionViewCell {

    lazy var statusImgView: UIImageView = {
        let imgView = UIImageView()
        imgView.backgroundColor = .blue
        return imgView
    }()
    
    lazy var stoneImgView: UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "role_chat_buttle_stone"))
        return imgView
    }()
    
    lazy var stoneLa: UILabel = {
        let lab = UILabel()
        lab.font = UIFont.boldSystemFont(ofSize: 12)
        lab.textColor = UIColor(hex: "#D7E7FF")
        lab.text = "12"
        return lab
    }()
    
    lazy var lockImgView: UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "role_chat_buttle_lock"))
        return imgView
    }()
    
    lazy var hiImgView: UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "role_chat_buttle_chat"))
        return imgView
    }()
    
    lazy var hiLab: UILabel = {
        let lab = UILabel()
        lab.text = "hi"
        lab.textColor = UIColor(hex: "#333333")
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textAlignment = .center
        return lab
    }()
    
    lazy var vipImgView: UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "role_chat_buttle_vip"))
        return imgView
    }()
    
    lazy var nameLab: UILabel = {
        let lab = UILabel()
        lab.font = UIFont.boldSystemFont(ofSize: 12)
        lab.text = "Default"
        lab.textColor = .white
        lab.textAlignment = .center
        return lab
    }()
    
    lazy var getBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor(hex: "#8A48FF")
        btn.setTitle("Get", for: .normal)
        btn.cornerRadius = 12.5
        btn.addTarget(self, action: #selector(getBtnTap), for: .touchUpInside)
        return btn
    }()
    
    lazy var stoneStackView: UIStackView = {
        let stackView = UIStackView(arrangedSubviews: [stoneImgView, stoneLa])
        stackView.axis = .horizontal
        stackView.spacing = 5
        stackView.alignment = .fill
        stackView.distribution = .fill
        return stackView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupData()
        setupEvent()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func getBtnTap() {
        
    }
    
    func configure(with item: ChatButtleRow, selected: Bool) {
        nameLab.text = item.name
        vipImgView.isHidden = item.kind != .vip
        lockImgView.isHidden = item.status != .locked
        getBtn.isHidden = item.status != .gettable
//        highlight.isHidden = !selected && item.status != .gettable
        if item.kind == .premium { nameLab.textColor = UIColor(hex: "#0066FF") } else if item.kind == .vip { nameLab.textColor = UIColor(hex: "#FF8C00") } else { nameLab.textColor = .white }
        nameLab.isHidden = item.status == .gettable
    }
    
    func setupViews() {
        self.backgroundColor = .gray
        self.cornerRadius = 10
        contentView.addSubview(vipImgView)
        contentView.addSubview(statusImgView)
        contentView.addSubview(stoneStackView)
        contentView.addSubview(lockImgView)
        contentView.addSubview(hiImgView)
        hiImgView.addSubview(hiLab)
        contentView.addSubview(nameLab)
        contentView.addSubview(getBtn)
        
        vipImgView.snp.makeConstraints { make in
            make.top.left.equalToSuperview().inset(5)
        }
        
        stoneStackView.snp.makeConstraints { make in
            make.left.top.equalToSuperview().inset(5)
        }
        
        statusImgView.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(5)
            make.centerY.equalTo(stoneStackView.snp.centerY)
            make.width.height.equalTo(13)
        }
        
        hiImgView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(statusImgView.snp.bottom).offset(10)
        }
        
        hiLab.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
        }
        
        lockImgView.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(5)
            make.centerY.equalTo(stoneStackView.snp.centerY)
        }
        
        nameLab.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.left.equalToSuperview().inset(5)
            make.top.equalTo(hiImgView.snp.bottom).offset(15)
            make.bottom.equalToSuperview().inset(10).priority(.low)
        }
    }
    
    func setupData() {}
    
    func setupEvent() {}
}
