//
//  HeartBeatLevelGridView.swift

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

import UIKit

class HeartBeatLevelGridView: CLContainer {
    var cv: UICollectionView!
    var headView: HeartBeatLevelGridHeadView!
    var headHeight: CGFloat = 386
    var layout = UICollectionViewFlowLayout()
    
    var datas: [HeartbeatLeveLDict] = [HeartbeatLeveLDict]()

    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() {
        let width = floor((UIScreen.width - 24 * 2 - 16) * 0.5)
        let height = 148.0
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: width, height: height)
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 16
        layout.sectionInset = UIEdgeInsets(top: 0, left: 24, bottom: UIWindow.safeAreaBottom, right: 24)

        cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.showsHorizontalScrollIndicator = false
        //        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        cv.contentInsetAdjustmentBehavior = .never
        cv.register(HeartBeatLevelGridCell.self, forCellWithReuseIdentifier: "HeartBeatLevelGridCell")
        cv.register(UICollectionReusableView.self,
                    forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                    withReuseIdentifier: "UICollectionReusableView")
        addSubview(cv)
        cv.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        headView = HeartBeatLevelGridHeadView()
    }

    private func setupData() {
    }

    private func setupEvent() {
        headView.heightChangeBlock = { [weak self] height in
            self?.headHeight = height
            self?.layout.headerReferenceSize = .init(width: UIScreen.width, height: height)
            self?.layout.invalidateLayout()
        }
    }
    
    func config(_ levels: [HeartbeatLeveLDict]?){
        datas = levels ?? []
        cv.reloadData()
    }
}

extension HeartBeatLevelGridView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeartBeatLevelGridCell", for: indexPath) as! HeartBeatLevelGridCell
        let data = datas[indexPath.item]
        cell.config(data)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(
                ofKind: kind,
                withReuseIdentifier: "UICollectionReusableView",
                for: indexPath
            )
            if headView.superview == nil || headView.superview != header {
                headView.removeFromSuperview()
            }

            header.addSubview(headView)
            headView.snp.makeConstraints { make in
                make.top.leading.trailing.equalToSuperview()
                make.bottom.equalToSuperview()
            }

            return header
        }
        return UICollectionReusableView()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: UIScreen.width, height: headHeight)
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NaviAlphaHandle.changeNaviTitleAlpha(scrollView: scrollView, alphaViews: [navigationView?.bgView] ) // navigationView?.titleLabel,
    }
}

class HeartBeatLevelGridCell: UICollectionViewCell {
    var block: UIView!
    var medalIv: UIImageView!
    var intimacyLabel: UILabel!
    var lockIcon: EPIconTertiaryDarkButton!
    var nameLabel: UILabel!
    
    var overlay: GradientView!

    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() {
        block = {
            let v = UIView()
            v.backgroundColor = .c.csbn
            v.layer.cornerRadius = 16
            v.layer.masksToBounds = true
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.top.equalToSuperview()
                make.height.equalTo(120)
            }
            return v
        }()
        
        medalIv = {
            let v = UIImageView()
            v.contentMode = .scaleAspectFill
            block.addSubview(v)
            v.snp.makeConstraints { make in
                //make.edges.equalToSuperview()
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(-6)
                make.bottom.equalToSuperview().offset(6)
            }
            return v
        }()
        
        overlay = {
            let gradient = CLSystemToken.gradient(token: .cob)
            let v = GradientView(colors: gradient.colors(), gradientType: .topToBottom)
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.height.equalTo(36)
                make.leading.trailing.bottom.equalToSuperview()
            }
            return v
        }()

        intimacyLabel = {
            let v = UILabel()
            v.font = .t.tls
            v.textColor = .c.ctsn
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(12)
                make.bottom.equalToSuperview().offset(-8)
            }
            return v
        }()

        lockIcon = {
            let v = EPIconTertiaryDarkButton(radius: .rectangle, iconSize: .small, iconCode: .iconPrivateBorder)
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(8)
                make.trailing.equalToSuperview().offset(-8)
            }
            return v
        }()

        nameLabel = {
            let v = UILabel()
            v.font = .t.tlm
            v.textColor = .text
            v.textAlignment = .center
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.top.equalTo(block.snp.bottom).offset(8)
            }
            return v
        }()
    }

    private func setupData() {
        intimacyLabel.text = "0.5℃"
        nameLabel.text = "Meet"
    }

    private func setupEvent() {
    }
    
    // MARK: Public
    
    func config(_ data: HeartbeatLeveLDict){
        medalIv.loadImage(data.imgUrl)
        
        nameLabel.text = data.name
        lockIcon.isHidden = data.isUnlock.boolValue
        intimacyLabel.text = "\((data.startVal ?? 0.0).formatted(decimal: 1))℃"
        
        if data.isUnlock.boolValue{
            nameLabel.textColor = .text
            intimacyLabel.textColor = .text
        }else{
            nameLabel.textColor = .c.ctpd
            intimacyLabel.textColor = .c.ctsn
        }
    }
}
