//
//  LNMoneyNotEnoughAlertView.swift
//  Gami
//
//  Created by OneeChan on 2026/3/30.
//

import Foundation
import UIKit
import SnapKit


class LNMoneyNotEnoughAlertView: LNCommonAlertView {
    private var exchangeType:LNCurrencyType?
    private let remainButton = UIButton()
    var exchangeHandler: (() -> Void)?
    
    func update(_ currency: LNCurrencyType, exchange: LNCurrencyType? = nil) {
        if let exchange, let exchangeType = LNExchangeType.map(from: exchange, to: currency) {
            titleLabel.text = .init(key: "B00132", currency.name(lowcase: true))
            
            messageLabel.font = .heading_h4
            messageLabel.textColor = .text_4
            messageLabel.attributedText = buildRemainString(exchangeType: exchange)
            
            if let rate = exchangeType.rate {
                subMessageLabel.attributedText = buildExchangeString(from: currency, fromValue: "1", exchange: exchange, exchangeValue: rate.toDisplay)
            }
            
            showConfirm(.init(key: "A00262")) { [weak self] in
                guard let self else { return }
                dismiss()
                if remainButton.isSelected {
                    LNUserDefaults[.remainExchange] = curTime
                }
                exchangeHandler?()
            }
            showCancel()
            
            remainButton.setTitle(String(key: "B00134"), for: .normal)
            remainButton.setImage(.icCheck, for: .selected)
            remainButton.setImage(.icUncheck, for: .normal)
            remainButton.setTitleColor(.text_4, for: .normal)
            remainButton.titleLabel?.font = .body_s
            remainButton.imageEdgeInsets = .init(top: 0, left: 0, bottom: 0, right: 8)
            remainButton.addAction(UIAction(handler: { [weak remainButton] _ in
                guard let remainButton else { return }
                remainButton.isSelected.toggle()
            }), for: .touchUpInside)
            buttonViews.addArrangedSubview(remainButton)
        } else {
            titleLabel.text = .init(key: "B00131", currency.name(lowcase: true))
            showConfirm { [weak self] in
                guard let self else { return }
                dismiss()
                let panel = LNPurchasePanel()
                panel.update(currency)
                panel.popup(self)
            }
            showCancel()
        }
    }
    
    func buildRemainString(exchangeType: LNCurrencyType) -> NSMutableAttributedString {
        let icon = NSTextAttachment(image: exchangeType.icon)
        icon.bounds = .init(x: 0, y: -4, width: 19, height: 19)
        let text = String(key: "B00133", exchangeType.name(lowcase: true), exchangeType.currentValue.toDisplay)
        let attrString = NSMutableAttributedString(string: text)
        let iconRange = (text as NSString).range(of: "{icon}")
        attrString.replaceCharacters(in: iconRange, with: .init(attachment: icon))
        
        return attrString
    }
    
    func buildExchangeString(from: LNCurrencyType, fromValue: String,
                             exchange: LNCurrencyType, exchangeValue: String) -> NSMutableAttributedString {
        let text = String(key: "B00138", fromValue, exchangeValue)
        let attrString = NSMutableAttributedString(string: text)
        
        let toIcon = NSTextAttachment(image: exchange.icon)
        toIcon.bounds = .init(x: 0, y: -3, width: 14, height: 14)
        let toIconRange = (text as NSString).range(of: "{icon2}")
        attrString.replaceCharacters(in: toIconRange, with: .init(attachment: toIcon))
        
        let fromIcon = NSTextAttachment(image: from.icon)
        fromIcon.bounds = .init(x: 0, y: -3, width: 14, height: 14)
        let fromIconRange = (text as NSString).range(of: "{icon1}")
        attrString.replaceCharacters(in: fromIconRange, with: .init(attachment: fromIcon))
        
        return attrString
    }
}

#if DEBUG

import SwiftUI

struct LNMoneyNotEnoughAlertViewPreview: UIViewRepresentable {
    func makeUIView(context: Context) -> some UIView {
        let container = UIView()
        container.backgroundColor = .lightGray
        
        let button = UIButton()
        button.backgroundColor = .red
        button.addAction(UIAction(handler: { [weak container] _ in
            guard let container else { return }
            
            let view = LNMoneyNotEnoughAlertView()
            view.update(.diamond, exchange: .coin)
            view.popup(container)
            
        }), for: .touchUpInside)
        container.addSubview(button)
        button.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(50)
        }
        
        return container
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) { }
}

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

