//
//  LNUserSearchTabsView.swift
//  Gami
//
//  Created by OneeChan on 2026/3/19.
//

import Foundation
import UIKit
import SnapKit


class LNUserSearchTabsView: UIView {
    private let stackView = UIStackView()
    private let indicator = UIImageView(image: .primary_7)
    private var buttons: [UIButton] = []
    
    var onSelect: ((LNUserSearchTab) -> Void)?
    private var selectedTab: LNUserSearchTab = .overview
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func update(selected: LNUserSearchTab, animated: Bool) {
        selectedTab = selected
        
        for (index, button) in buttons.enumerated() {
            let isSelected = index == selected.rawValue
            button.setTitleColor(isSelected ? .text_5 : .text_2, for: .normal)
            button.titleLabel?.font = isSelected ? .heading_h3 : .heading_h4
            if isSelected {
                indicator.snp.remakeConstraints { make in
                    make.centerX.equalTo(button)
                    make.top.equalTo(button.titleLabel!.snp.bottom)
                    make.width.equalTo(23)
                    make.height.equalTo(2)
                }
            }
        }
        
        let updates = { self.layoutIfNeeded() }
        if animated {
            UIView.animate(withDuration: 0.22, delay: 0, options: [.curveEaseInOut]) {
                updates()
            }
        } else {
            updates()
        }
    }
}

extension LNUserSearchTabsView {
    private func setupViews() {
        backgroundColor = .white
        
        stackView.axis = .horizontal
        stackView.spacing = 20
        stackView.alignment = .center
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(4)
            make.bottom.equalToSuperview().offset(-10)
        }
        
        for tab in LNUserSearchTab.allCases {
            let button = UIButton(type: .system)
            button.tag = tab.rawValue
            button.tintColor = .clear
            button.setTitle(tab.title, for: .normal)
            button.titleLabel?.font = .heading_h4
            button.addAction(UIAction(handler: { [weak self] _ in
                self?.onSelect?(tab)
            }), for: .touchUpInside)
            buttons.append(button)
            stackView.addArrangedSubview(button)
        }
        
        indicator.layer.cornerRadius = 1
        indicator.clipsToBounds = true
        addSubview(indicator)
    }
}
