//
//  LNLanguageSelectPanel.swift
//  Gami
//
//  Created by OneeChan on 2026/1/29.
//

import Foundation
import UIKit
import SnapKit


class LNLanguageSelectPanel: LNPopupView {
    private var languageItemViews: [LNLanguageSelectItemView] = []
    private let confirmButton = UIButton()
    
    var handler: (([LNLanguageConstsVO]) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func update(curSelect: [LNLanguageConstsVO]) {
        languageItemViews.forEach { itemView in
            itemView.isSelected = curSelect.first(where: { $0.code == itemView.language.code }) != nil
        }
        
        updateConfirm()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNLanguageSelectPanel {
    private func updateConfirm() {
        let enable = languageItemViews.first(where: { $0.isSelected == true }) != nil
        if enable != confirmButton.isEnabled {
            confirmButton.isEnabled = enable
            
            confirmButton.setBackgroundImage(enable ? .primary_8 : nil, for: .normal)
        }
    }
    
    private func setupViews() {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 0
        container.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview().offset(5)
        }
        
        var itemViews: [UIView] = []
        LNConfigManager.shared.commonConfig.commonLanguageConsts.forEach {
            let itemView = LNLanguageSelectItemView(language: $0)
            itemView.onTap { [weak self, weak itemView] in
                guard let self, let itemView else { return }
                itemView.isSelected.toggle()
                updateConfirm()
            }
            
            languageItemViews.append(itemView)
            itemViews.append(itemView)
        }
        
        for index in (1..<itemViews.count).reversed() {
            itemViews.insert(buildLine(), at: index)
        }
        itemViews.forEach {
            stackView.addArrangedSubview($0)
        }
        
        confirmButton.setTitle(.init(key: "A00223"), for: .normal)
        confirmButton.setTitleColor(.text_1, for: .normal)
        confirmButton.titleLabel?.font = .heading_h3
        confirmButton.layer.cornerRadius = 23.5
        confirmButton.clipsToBounds = true
        confirmButton.backgroundColor = .fill_4
        confirmButton.isEnabled = false
        confirmButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            dismiss()
            handler?(languageItemViews.filter({ $0.isSelected }).map({ $0.language }))
        }), for: .touchUpInside)
        container.addSubview(confirmButton)
        confirmButton.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(stackView.snp.bottom).offset(10)
            make.bottom.equalToSuperview().offset(commonBottomInset)
            make.height.equalTo(47)
        }
    }
    
    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
    }
}

private class LNLanguageSelectItemView: UIView {
    let language: LNLanguageConstsVO
    private let titleLabel = UILabel()
    private let checkIc = UIImageView()
    
    var isSelected: Bool = false {
        didSet {
            checkIc.image = isSelected ? .icCheck : .icUncheck
        }
    }
    
    init(language: LNLanguageConstsVO) {
        self.language = language
        super.init(frame: .zero)
        
        snp.makeConstraints { make in
            make.height.equalTo(41)
        }
        
        addSubview(checkIc)
        checkIc.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-16)
        }
        
        titleLabel.text = language.name
        titleLabel.font = .heading_h4
        titleLabel.textColor = .text_5
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
            make.trailing.lessThanOrEqualTo(checkIc.snp.leading).offset(-5)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
