//
//  IMMoreItemView.swift

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

import UIKit
import Combine

enum IMMoreMenuType: Int {
    case picture = 0
    case phone = 1
    case share = 2
}

protocol IMMoreItemViewDelegate: AnyObject {
    func imMoreItemView(view: IMMoreItemView, tapType: IMMoreMenuType)
}

class IMMoreItemView: UIView {
    weak var delegate: IMMoreItemViewDelegate?

    var bgView: UIView!
    var cv: UICollectionView!
    var layout = UICollectionViewFlowLayout()
    
    override var isHidden: Bool{
        didSet{
            cv.reloadData()
        }
    }
    
    static let heightOfMoreItemView = 206.0
    
    private var cancellables = Set<AnyCancellable>()

    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() {
        backgroundColor = .c.csbn
        
        bgView = {
            let v = UIView()
            v.backgroundColor = backgroundColor
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalToSuperview().offset(UIWindow.safeAreaBottom + 16)
            }
            return v
        }()
        
        cv = {
            let itemsInRow = 4.0
            let width = floor((UIScreen.width - 24.0 * 2 - 16.0 * (itemsInRow - 1)) * (1 / itemsInRow))
            let height = width + 24
            layout.scrollDirection = .vertical
            layout.itemSize = CGSize(width: width, height: height)
            layout.minimumLineSpacing = 16
            layout.minimumInteritemSpacing = 16
            layout.sectionInset = UIEdgeInsets(top: 16, left: 24, bottom: UIWindow.safeAreaBottom + 16, right: 24)

            cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
            cv.backgroundColor = .clear
            cv.showsHorizontalScrollIndicator = false
            cv.delegate = self
            cv.dataSource = self
            cv.contentInsetAdjustmentBehavior = .never
            cv.register(IMMoreItemGridCell.self, forCellWithReuseIdentifier: "IMMoreItemGridCell")
            addSubview(cv)
            cv.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalToSuperview()
                make.height.equalTo(IMMoreItemView.heightOfMoreItemView) // 240
            }
            return cv
        }()
    }

    private func setupData() {
    }

    private func setupEvent() {
        IMAIViewModel.shared.$aiIMInfo.sink {[weak self] user in
            self?.cv.reloadData()
        }.store(in: &cancellables)
    }
}

extension IMMoreItemView: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        3
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "IMMoreItemGridCell", for: indexPath) as! IMMoreItemGridCell
        if let type = IMMoreMenuType(rawValue: indexPath.item) {
            cell.config(type: type)
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let type = IMMoreMenuType(rawValue: indexPath.item) else {
            return
        }
        
        let level = IMAIViewModel.shared.aiIMInfo?.aiUserHeartbeatRelation?.heartbeatLevel
        
        switch type {
        case .picture:
            if let theLevel = level, theLevel.isGreaterOrEqual(to: .level2){
                delegate?.imMoreItemView(view: self, tapType: type)
            }else{
                AppRouter.goAIHeartBeatLevelPage(aiId: IMAIViewModel.shared.aiId)
            }
        case .phone:
            if let theLevel = level, theLevel.isGreaterOrEqual(to: .level4){
                delegate?.imMoreItemView(view: self, tapType: type)
            }else{
                AppRouter.goAIHeartBeatLevelPage(aiId: IMAIViewModel.shared.aiId)
            }
        case .share:
            delegate?.imMoreItemView(view: self, tapType: type)
        }
    }
}

class IMMoreItemGridCell: UICollectionViewCell {
    var block: UIView!
    var icon: UIImageView!
    var itemLabel: CLLabel!
    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.cseln
            v.cornerRadius = 16
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.height.equalTo(v.snp.width)
                make.top.equalToSuperview()
            }
            return v
        }()

        icon = {
            let v = UIImageView()
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.center.equalToSuperview()
                make.size.equalTo(CGSize(width: 28, height: 28))
            }
            return v
        }()

        itemLabel = {
            let v = CLLabel()
            v.textAlignment = .center
            v.font = .t.tls
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.top.equalTo(block.snp.bottom).offset(4)
            }
            return v
        }()
    }

    private func setupData() {
    }

    private func setupEvent() {
    }

    func config(type: IMMoreMenuType) {
        let level = IMAIViewModel.shared.aiIMInfo?.aiUserHeartbeatRelation?.heartbeatLevel ?? .level1
        
        switch type {
        case .picture:
            icon.image = MWIconFont.image(fromIcon: .iconUploadimg, size: CGSize(width: 28, height: 28), color: .white)
            if level.isGreaterOrEqual(to: .level2){
                itemLabel.text = "Picture"
            }else{
                itemLabel.text = "Lv2.unlock"
            }
        case .phone:
            icon.image = MWIconFont.image(fromIcon: .call, size: CGSize(width: 28, height: 28), color: .white)
            if level.isGreaterOrEqual(to: .level4){
                itemLabel.text = "Voice Call"
            }else{
                itemLabel.text = "Lv4.unlock"
            }
        case .share:
            icon.image = MWIconFont.image(fromIcon: .shareBorder, size: CGSize(width: 28, height: 28), color: .white)
            itemLabel.text = "Share"
        }
    }
}
