//
//  LNOrderQRCodeShowView.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/27.
//

import Foundation
import UIKit
import SnapKit


class LNOrderQRCodeShowView: UIView {
    private let qrCodeSize: CGFloat = 145
    
    private let qrCodeIc = UIImageView()
    private let priceLabel = UILabel()
    private let unitLabel = UILabel()
    
    private let saveButton = UIButton()
    private let copyButton = UIButton()
    
    private var qrCodeUrl: String?
    
    private var curSkill: LNGameMateSkillVO?
    private var count: Int = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func update(_ skill: LNGameMateSkillVO, customCount: Int? = nil) {
        let count = customCount ?? 1
        if skill.id == curSkill?.id, count == self.count { return }
        
        priceLabel.text = (skill.price * Double(count)).toDisplay
        unitLabel.text = if count <= 1 {
            "/\(skill.unit)"
        } else {
            "/\(skill.unit) x \(count)"
        }
        
        qrCodeIc.image = nil
        
        curSkill = skill
        self.count = count
        
        saveButton.isEnabled = false
        copyButton.isEnabled = false
        
        let type: LNOrderSource = customCount != nil ? .custom : .normal
        LNOrderManager.shared.createOrderQR(
            skillId: skill.id,
            count: count,
            type: type) { [weak self] qrCode in
                guard let self else { return }
                guard let qrCode else { return }
                guard skill.id == self.curSkill?.id,
                      self.count == count else { return }
                let url: String = .orderQRShareUrl + "?id=\(skill.id)&code=\(qrCode)"
                self.qrCodeIc.image = url.toQRCode(size: qrCodeSize)
                self.qrCodeUrl = url
                self.saveButton.isEnabled = true
                self.copyButton.isEnabled = true
            }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

extension LNOrderQRCodeShowView {
    private func setupViews() {
        let container = UIView()
        container.backgroundColor = .fill
        container.layer.cornerRadius = 6
        addSubview(container)
        container.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(20)
        }
        
        container.addSubview(qrCodeIc)
        qrCodeIc.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(12)
            make.width.height.equalTo(qrCodeSize)
        }
        
        let priceView = UIView()
        addSubview(priceView)
        priceView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(container.snp.bottom).offset(12)
        }
        
        let coin = UIImageView.coinImageView()
        priceView.addSubview(coin)
        coin.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.height.equalTo(22)
        }
        
        priceLabel.font = .heading_h1
        priceLabel.textColor = .text_5
        priceView.addSubview(priceLabel)
        priceLabel.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview()
            make.leading.equalTo(coin.snp.trailing)
        }
        
        unitLabel.font = .body_m
        unitLabel.textColor = .text_5
        priceView.addSubview(unitLabel)
        unitLabel.snp.makeConstraints { make in
            make.leading.equalTo(priceLabel.snp.trailing)
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview()
        }
        
        saveButton.layer.cornerRadius = 23.5
        saveButton.setTitleColor(.text_6, for: .normal)
        saveButton.setTitle(.init(key: "A00156"), for: .normal)
        saveButton.titleLabel?.font = .heading_h3
        saveButton.setBackgroundImage(.primary_7, for: .normal)
        saveButton.clipsToBounds = true
        saveButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            guard let skill = self.curSkill else { return }
            guard let image = qrCodeIc.image else { return }
            let generator = LNOrderShareImageGenerator()
            generator.update(skill: skill, count: self.count, image: image)
            let share = generator.generate()
            share.saveToLibrary { success, err in
                if success {
                    showToast(.init(key: "A00157"))
                } else if let err {
                    showToast(err.localizedDescription)
                }
            }
        }), for: .touchUpInside)
        addSubview(saveButton)
        saveButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.top.equalTo(priceView.snp.bottom).offset(22)
            make.height.equalTo(47)
            make.bottom.equalToSuperview().offset(-10)
        }
        
        let cover = UIView()
        cover.backgroundColor = .fill
        cover.layer.cornerRadius = 22
        cover.isUserInteractionEnabled = false
        saveButton.insertSubview(cover, at: 0)
        cover.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(1.5)
        }
        
        copyButton.layer.cornerRadius = 23.5
        copyButton.clipsToBounds = true
        copyButton.setBackgroundImage(.primary_8, for: .normal)
        copyButton.setTitle(.init(key: "A00158"), for: .normal)
        copyButton.setTitleColor(.text_1, for: .normal)
        copyButton.titleLabel?.font = .heading_h3
        copyButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            UIPasteboard.general.string = self.qrCodeUrl
            showToast(.init(key: "A00159"))
        }), for: .touchUpInside)
        addSubview(copyButton)
        copyButton.snp.makeConstraints { make in
            make.leading.equalTo(saveButton.snp.trailing).offset(10)
            make.trailing.equalToSuperview().offset(-16)
            make.centerY.equalTo(saveButton)
            make.width.height.equalTo(saveButton)
        }
    }
}
