//
//  LNOrderQRTabView.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/26.
//

import Foundation
import UIKit
import SnapKit


protocol LNOrderQRTabViewDelegate: AnyObject {
    func onOrderQRTabView(view: LNOrderQRTabView, didChangedType newType: LNOrderSource)
}


class LNOrderQRTabView: UIView {
    private let indicator = UIView()
    private let normal = UIButton()
    private let edit = UIButton()
    
    weak var delegate: LNOrderQRTabViewDelegate?
    
    var curType: LNOrderSource = .normal {
        didSet {
            normal.isSelected = curType == .normal
            edit.isSelected = curType == .custom
            
            indicator.snp.remakeConstraints { make in
                make.edges.equalTo(curType == .normal ? normal : edit)
            }
            UIView.animate(withDuration: 0.25) { [weak self] in
                guard let self else { return }
                layoutIfNeeded()
            }
            delegate?.onOrderQRTabView(view: self, didChangedType: curType)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNOrderQRTabView {
    private func setupViews() {
        backgroundColor = .fill_3
        layer.cornerRadius = 20
        snp.makeConstraints { make in
            make.height.equalTo(40)
        }
        
        indicator.backgroundColor = .fill
        indicator.layer.cornerRadius = 16
        addSubview(indicator)
        
        normal.setTitle(.init(key: "A00160"), for: .normal)
        normal.setTitleColor(.text_5, for: .selected)
        normal.setTitleColor(.text_4, for: .normal)
        normal.titleLabel?.font = .heading_h4
        addSubview(normal)
        normal.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalToSuperview().offset(4)
            make.height.equalTo(32)
        }
        
        edit.setTitle(.init(key: "A00161"), for: .normal)
        edit.setTitleColor(.text_5, for: .selected)
        edit.setTitleColor(.text_4, for: .normal)
        edit.titleLabel?.font = .heading_h4
        addSubview(edit)
        edit.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-4)
            make.height.equalTo(32)
            make.leading.equalTo(normal.snp.trailing).offset(3)
            make.width.equalTo(normal)
        }
        
        normal.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            curType = .normal
        }), for: .touchUpInside)
        edit.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            curType = .custom
        }), for: .touchUpInside)
    }
}
