//
//  LNGameCategoryFilterPanel.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/25.
//

import Foundation
import UIKit
import SnapKit


protocol LNGameCategoryFilterPanelDelegate: AnyObject {
    func onGameCategoryFilterPanel(panel: LNGameCategoryFilterPanel, didSelect game: LNGameCategoryItemVO, gameType: LNGameTypeItemVO)
}


class LNGameCategoryFilterPanel: UIView {
    private let indicator = UIView()
    
    private var collectionView: UICollectionView?
    
    private var curType: LNGameTypeItemVO?
    weak var delegate: LNGameCategoryFilterPanelDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNGameCategoryFilterPanel: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        curType?.children.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LNGameCategoryFilterCell.className, for: indexPath) as! LNGameCategoryFilterCell
        
        let item = (curType?.children[indexPath.row])!
        cell.icon.sd_setImage(with: URL(string: item.icon))
        cell.label.text = item.name
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: false)
        
        guard let curType else { return }
        let item = curType.children[indexPath.row]
        delegate?.onGameCategoryFilterPanel(panel: self, didSelect: item, gameType: curType)
    }
}

extension LNGameCategoryFilterPanel {
    private func handleClickTab(view: UIView, typeItem: LNGameTypeItemVO) {
        indicator.isHidden = false
        indicator.snp.remakeConstraints { make in
            make.edges.equalTo(view).inset(4)
        }
        UIView.animate(withDuration: 0.25) { [weak self] in
            guard let self else { return }
            indicator.superview?.layoutIfNeeded()
        }
        
        curType = typeItem
        
        collectionView?.reloadData()
    }
    
    private func setupViews() {
        let container = UIView()
        container.layer.cornerRadius = 20
        container.backgroundColor = .fill
        addSubview(container)
        container.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.verticalEdges.equalToSuperview()
        }
        
        let tabView = buildTabView()
        container.addSubview(tabView)
        tabView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(11)
            make.top.equalToSuperview().offset(12)
        }
        
        let listView = buildListView()
        container.addSubview(listView)
        listView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(11)
            make.top.equalTo(tabView.snp.bottom).offset(12)
            make.bottom.equalToSuperview().offset(-12)
        }
    }
    
    private func buildTabView() -> UIView {
        let container = UIStackView()
        container.axis = .horizontal
        container.spacing = 0
        container.distribution = .fillEqually
        container.layer.cornerRadius = 20
        container.backgroundColor = .primary_1
        container.snp.makeConstraints { make in
            make.height.equalTo(40)
        }
        
        indicator.isHidden = true
        indicator.backgroundColor = .fill
        indicator.layer.cornerRadius = 16
        container.addSubview(indicator)
        
        let titles = LNGameMateManager.shared.curGameTypes
        for (index, title) in titles.enumerated() {
            let button = UIButton()
            button.setTitle(title.name, for: .normal)
            button.setTitleColor(.text_5, for: .normal)
            button.titleLabel?.font = .heading_h4
            button.addAction(UIAction(handler: { [weak self, weak button] _ in
                guard let self, let button else { return }
                handleClickTab(view: button, typeItem: title)
            }), for: .touchUpInside)
            
            if index == 0 {
                DispatchQueue.main.async { [weak self, weak button] in
                    guard let self, let button else { return }
                    handleClickTab(view: button, typeItem: title)
                }
            }
            
            container.addArrangedSubview(button)
        }
        
        return container
    }
    
    private func buildListView() -> UIView {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = .init(width: 67, height: 66)
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 20
        layout.minimumInteritemSpacing = 16
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(LNGameCategoryFilterCell.self, forCellWithReuseIdentifier: LNGameCategoryFilterCell.className)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.allowsSelection = true
        collectionView.contentInset = .init(top: 20, left: 0, bottom: 0, right: 0)
        
        self.collectionView = collectionView
        
        return collectionView
    }
}

private class LNGameCategoryFilterCell: UICollectionViewCell {
    let icon = UIImageView()
    let label = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(icon)
        icon.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
            make.width.height.equalTo(50)
        }
        
        label.font = .body_xs
        label.textColor = .text_5
        label.textAlignment = .center
        contentView.addSubview(label)
        label.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
