//
//  LNEditInterestPanel.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/19.
//

import Foundation
import UIKit
import SnapKit


class LNEditInterestPanel: LNPopupView {
    private var actegoryViews: [LNAutoFillStackView] = []
    private var curSelected: [LNGameCategoryItemVO] = []
    private let confirmButton = UIButton()
    
    private let maxCount = LNGameMateManager.gameSelectionMaxCount
    private var allInterests: [LNInterestItemView] = []
    
    var handler: (([LNGameCategoryItemVO]) -> Void)?
    
    init(selecteds: [String]) {
        super.init(frame: .zero)
        
        curSelected = selecteds.compactMap({
            LNGameMateManager.shared.gameCategory(for: $0)
        })
        
        setupViews()
        
        updateConfirmButton()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNEditInterestPanel {
    private func updateConfirmButton() {
        if curSelected.isEmpty, confirmButton.isEnabled {
            confirmButton.isEnabled = false
            confirmButton.setBackgroundImage(nil, for: .normal)
        } else if !curSelected.isEmpty, !confirmButton.isEnabled {
            confirmButton.isEnabled = true
            confirmButton.setBackgroundImage(.primary_8, for: .normal)
        }
    }
    
    private func updateList() {
        allInterests.forEach { itemView in
            itemView.isSelected = curSelected.contains(where: { $0.code == itemView.curItem?.code })
            itemView.isEnable = itemView.isSelected || curSelected.count < LNGameMateManager.gameSelectionMaxCount
        }
    }
    
    private func setupViews() {
        container.clipsToBounds = true
        
        let background = UIImageView()
        background.image = .icLoginInterestBg
        container.addSubview(background)
        background.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let titleLabel = UILabel()
        titleLabel.font = .heading_h3
        titleLabel.textColor = .text_5
        titleLabel.text = .init(key: "A00186")
        container.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(16)
        }
        
        let descLabel = UILabel()
        descLabel.text = .init(key: "A00187")
        descLabel.font = .body_s
        descLabel.textColor = .text_4
        descLabel.textAlignment = .center
        container.addSubview(descLabel)
        descLabel.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(titleLabel.snp.bottom).offset(6)
        }
        
        let holder = UIView()
        holder.backgroundColor = .fill
        holder.layer.cornerRadius = 20
        container.addSubview(holder)
        holder.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(descLabel.snp.bottom).offset(12)
        }
        
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 12
        holder.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(14)
        }
        buildCategoryViews().forEach {
            stackView.addArrangedSubview($0)
        }
        
        confirmButton.setTitle(.init(key: "A00185"), for: .normal)
        confirmButton.setTitleColor(.text_1, for: .normal)
        confirmButton.titleLabel?.font = .heading_h3
        confirmButton.setBackgroundImage(.primary_8, for: .normal)
        confirmButton.layer.cornerRadius = 23.5
        confirmButton.clipsToBounds = true
        confirmButton.backgroundColor = .fill_4
        confirmButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            dismiss()
            handler?(curSelected)
        }), for: .touchUpInside)
        container.addSubview(confirmButton)
        confirmButton.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(12)
            make.top.equalTo(holder.snp.bottom).offset(16)
            make.bottom.equalToSuperview().offset(commonBottomInset)
            make.height.equalTo(47)
        }
    }
    
    private func buildCategoryViews() -> [UIView] {
        var views: [UIView] = []
        
        for category in LNGameMateManager.shared.curGameTypes {
            let container = UIView()
            
            let titleLabel = UILabel()
            titleLabel.text = category.name
            titleLabel.font = .heading_h4
            titleLabel.textColor = .text_5
            container.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.top.equalToSuperview()
            }
            
            let multiLineView = LNAutoFillStackView()
            multiLineView.itemSpacing = 8
            multiLineView.spacing = 10
            container.addSubview(multiLineView)
            multiLineView.snp.makeConstraints { make in
                make.horizontalEdges.equalToSuperview()
                make.bottom.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(10)
            }
            
            var itemViews: [UIView] = []
            category.children.forEach { item in
                let itemView = LNInterestItemView()
                itemView.update(item)
                itemView.onTap { [weak self] in
                    guard let self else { return }
                    if curSelected.contains(where: { $0.code == item.code }) {
                        curSelected.removeAll { $0.code == item.code }
                    } else if curSelected.count < LNGameMateManager.gameSelectionMaxCount{
                        curSelected.append(item)
                    }
                    updateList()
                    updateConfirmButton()
                }
                allInterests.append(itemView)
                itemViews.append(itemView)
            }
            multiLineView.update(itemViews)
            
            views.append(container)
        }
        updateList()
        
        return views
    }
}

private class LNInterestItemView: UIView {
    private let titleLabel = UILabel()
    private(set) var curItem: LNGameCategoryItemVO?
    
    var isSelected: Bool = false {
        didSet {
            if isSelected {
                titleLabel.font = .heading_h5
                titleLabel.textColor = .text_6
                backgroundColor = .fill_5
            } else {
                titleLabel.font = .body_s
                titleLabel.textColor = .text_4
                backgroundColor = .fill_1
            }
        }
    }
    
    var isEnable: Bool = true {
        didSet {
            alpha = isEnable ? 1.0 : 0.5
            isUserInteractionEnabled = isEnable
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .fill_1
        layer.cornerRadius = 12
        snp.makeConstraints { make in
            make.height.equalTo(24)
        }
        
        titleLabel.font = .body_s
        titleLabel.textColor = .text_4
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.horizontalEdges.equalToSuperview().inset(11)
        }
    }
    
    func update(_ item: LNGameCategoryItemVO) {
        titleLabel.text = item.name
        curItem = item
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
