//
//  LNBottomSheetMenu.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/12.
//

import Foundation
import UIKit
import SnapKit

class LNBottomSheetMenu: LNPopupView {
    let stackView = UIStackView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func update(_ menus: [String], handler: @escaping (Int, String) -> Void) {
        guard !menus.isEmpty else { return }
        
        stackView.arrangedSubviews.forEach {
            stackView.removeArrangedSubview($0)
            $0.removeFromSuperview()
        }
        
        var itemViews: [UIView] = []
        for (index, menu) in menus.enumerated() {
            let view = UIView()
            view.snp.makeConstraints { make in
                make.height.equalTo(50)
            }
            view.onTap { [weak self] in
                guard let self else { return }
                handler(index, menu)
                dismiss()
            }
            
            let titleLabel = UILabel()
            titleLabel.text = menu
            titleLabel.font = .heading_h4
            titleLabel.textColor = .text_5
            view.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { make in
                make.center.equalToSuperview()
            }
            
            itemViews.append(view)
        }
        
        for index in (1..<itemViews.count).reversed() {
            itemViews.insert(buildLine(), at: index)
        }
        
        itemViews.forEach {
            stackView.addArrangedSubview($0)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNBottomSheetMenu {
    private func setupViews() {
        stackView.axis = .vertical
        stackView.spacing = 0
        
        container.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(commonBottomInset)
        }
    }
    
    private func buildLine() -> UIView {
        let container = UIView()
        
        let line = UIView()
        line.backgroundColor = .fill_2
        container.addSubview(line)
        line.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview()
            make.height.equalTo(1)
            make.horizontalEdges.equalToSuperview().inset(16)
        }
        
        return container
    }
}
