//
//  LNSortedEditView.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/14.
//

import Foundation
import UIKit
import SnapKit


enum LNSortedType: Int, CaseIterable {
    case none = -1
    case up = 0
    case down = 1
    
    var text: String {
        switch self {
        case .none: .init(key: "A00008")
        case .up: .init(key: "A00009")
        case .down: .init(key: "A00010")
        }
    }
}


protocol LNSortedEditViewDelegate: AnyObject {
    func sortedEditView(view: LNSortedEditView, sortedTypeChanged: LNSortedType)
}


class LNSortedEditView: UIView {
    let titleLabel = UILabel()
    private let icon = UIImageView()
    
    weak var delegate: LNSortedEditViewDelegate?
    var curType: LNSortedType = .none {
        didSet {
            guard oldValue != curType else { return }
            icon.image = switch curType {
            case .none: .icSortedNone
            case .up: .icSortedUp
            case .down: .icSortedDown
            }
            delegate?.sortedEditView(view: self, sortedTypeChanged: curType)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNSortedEditView {
    private func setupViews() {
        titleLabel.textColor = .text_4
        titleLabel.font = .body_xs
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        icon.image = .icSortedNone
        addSubview(icon)
        icon.snp.makeConstraints { make in
            make.top.bottom.trailing.equalToSuperview()
            make.leading.equalTo(titleLabel.snp.trailing)
        }
        
        onTap { [weak self] in
            guard let self else { return }
            curType = switch curType {
            case .none : .up
            case .up: .down
            case .down: .none
            }
        }
    }
}


#if DEBUG

import SwiftUI

struct LNSortedEditViewPreview: UIViewRepresentable {
    func makeUIView(context: Context) -> some UIView {
        let container = UIView()
        container.backgroundColor = .lightGray
        
        let view = LNSortedEditView()
        view.titleLabel.text = "some thing"
        container.addSubview(view)
        view.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        return container
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) { }
}

#Preview(body: {
    LNSortedEditViewPreview()
})
#endif

