import Foundation
import UIKit
import Alamofire

public class PaymentMethodView : UIView{
    @IBOutlet weak var bankCollectionView: UICollectionView!
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var dottedLineView: UIView!
    @IBOutlet weak var paymentMethodTitle: UILabel!
    @IBOutlet weak var versionLabel: UILabel!
    @IBOutlet weak var transactionLabel: UILabel!
    @IBOutlet weak var transactionAmount: UILabel!
    @IBOutlet weak var verticalView: UIView!
    @IBOutlet weak var bill24Label: UILabel!
    @IBOutlet weak var powerByLabel: UILabel!
    @IBOutlet weak var currencyLabel: UILabel!
    @IBOutlet weak var centerLoading: UIActivityIndicatorView!
    
    private var transaction: Transaction?
    private var transactionInfo: TransInfo?
    private var checkoutPageConfig: CheckoutPageConfig?
    private var setting: Setting?
    private var generateLinkResponse: GenerateLinkResponse?
    private var bottomSheetController: BottomSheetViewController?
    private var paymentMethodView: UIView!
    
    // MARK: - Network Monitoring
    private var isWaitingForConnection: Bool = false
    
    var transactionId: String = ""
    var controller: UIViewController!
    
    private lazy var closeButton: UIButton = {
        let button = UIButton(type: .system)
        let config = UIImage.SymbolConfiguration(pointSize: 14, weight: .bold)
        button.setImage(UIImage(systemName: "xmark", withConfiguration: config), for: .normal)
        button.layer.cornerRadius = 14
        button.layer.borderWidth = 1
        button.clipsToBounds = true
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
        return button
    }()
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        if let flowLayout = bankCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            // CollectionView
            let collectionViewWidth = bankCollectionView.bounds.width
            let leadingSpace: CGFloat = 15
            let trailingSpace: CGFloat = 15
            let itemWidth =  collectionViewWidth - leadingSpace - trailingSpace
            let itemHeight: CGFloat = 76
            flowLayout.itemSize = CGSize(width: itemWidth, height: itemHeight)

            // Header View
            let topSpace: CGFloat = 15
            let bottomSpace: CGFloat = 15
            flowLayout.headerReferenceSize = CGSize(width: collectionViewWidth , height: 35)
            flowLayout.sectionInset = UIEdgeInsets(top: topSpace, left: 0, bottom: bottomSpace, right: 0)

            // Make section headers sticky
            flowLayout.sectionHeadersPinToVisibleBounds = true
        }
    }
    
    
    init(frame: CGRect, controller: UIViewController, transactionId: String, bottomSheetController: BottomSheetViewController, transaction: Transaction?) {
        self.controller = controller
        self.transactionId = transactionId
        self.bottomSheetController = bottomSheetController
        self.transaction = transaction
        super.init(frame: frame)
        initSubviews()
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initSubviews()
    }
    
    private func initSubviews() {
        registerPaymentView()
        fetchCheckoutDetailApi()
        print("*** Payment Method ***")
    }
    
    private func registerPaymentView(){
        let nib = UINib(nibName: "PaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
        guard let view = nib.instantiate(withOwner: self, options: nil).first as?
                UIView else {fatalError("Unable to convert nib")}
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(view)
        paymentMethodView = view
        
        // Move centerLoading to the bottomSheetController's view to center it on the screen
        if let superview = centerLoading.superview {
            centerLoading.removeFromSuperview()
            bottomSheetController?.view.addSubview(centerLoading)
        }
        
        // Center the activity indicator on the screen
        centerLoading.translatesAutoresizingMaskIntoConstraints = false
        if let sheetView = bottomSheetController?.view {
            NSLayoutConstraint.activate([
                centerLoading.centerXAnchor.constraint(equalTo: sheetView.centerXAnchor),
                centerLoading.centerYAnchor.constraint(equalTo: sheetView.centerYAnchor)
            ])
            sheetView.bringSubviewToFront(centerLoading)
        }
        
        // Add bottomView as a subview to PaymentMethodView
        addSubview(bottomView)
        bottomView.backgroundColor =  UIColor(
            named: "primary_background_color",
            in: B24PaymentSdkHelper.frameworkBundle(),
            compatibleWith: nil
        )
        // Set bottomView constraints
        let footerHeight: CGFloat = 150
        bottomView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            bottomView.leadingAnchor.constraint(equalTo: leadingAnchor),
            bottomView.trailingAnchor.constraint(equalTo: trailingAnchor),
            bottomView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -20),
            bottomView.heightAnchor.constraint(equalToConstant: footerHeight)
        ])

        // Add bottom inset so last items aren't hidden behind the footer overlay
        bankCollectionView.contentInset.bottom = footerHeight
        bankCollectionView.scrollIndicatorInsets.bottom = footerHeight
        
        // Add close button
        addSubview(closeButton)
        NSLayoutConstraint.activate([
            closeButton.centerYAnchor.constraint(equalTo: paymentMethodTitle.centerYAnchor),
            closeButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -14),
            closeButton.widthAnchor.constraint(equalToConstant: 28),
            closeButton.heightAnchor.constraint(equalToConstant: 28)
        ])
        bringSubviewToFront(closeButton)

        // Accessibility identifiers for XCUITest
        bankCollectionView.accessibilityIdentifier = "bankCollectionView"
        closeButton.accessibilityIdentifier = "closeButton"
        transactionAmount.accessibilityIdentifier = "transactionAmount"
        
        self.hideCenterLoading()
    }
    
    @objc private func closeButtonTapped() {
        bottomSheetController?.dismiss(animated: true)
    }

    private func applyCloseButtonTheme() {
        let backgroundColor = SDKVariableSetting.isDarkMode ? UIColor(hex: "#2C2C2E") : UIColor(hex: "#F3F4F6")
        let borderColor = SDKVariableSetting.isDarkMode ? UIColor(hex: "#3A3A3C") : UIColor(hex: "#E5E7EB")

        closeButton.backgroundColor = backgroundColor
        closeButton.layer.borderColor = borderColor.cgColor
        closeButton.tintColor = UIColor(hex: Themes.Property.labelTextColor)
    }
    
    private func setUpFontAndTranslatePaymentMethod(language: String){
        paymentMethodTitle.font = FontManager.shared.boldFont(forLanguage: language, size: 16.0)
        transactionLabel.font = FontManager.shared.boldFont(forLanguage: language, size: 12.0)
        transactionAmount.font = B24PaymentSdkHelper.setFont(named: "Roboto-Bold", ofSize: 22.0)
        powerByLabel.font = B24PaymentSdkHelper.setFont(named: "Roboto-Italic", ofSize: 11.0)
        bill24Label.font = B24PaymentSdkHelper.setFont(named: "Roboto-Medium", ofSize: 12.0)
        versionLabel.font = B24PaymentSdkHelper.setFont(named: "Roboto-Regular", ofSize: 12.0)
        currencyLabel.font = B24PaymentSdkHelper.setFont(named: "Roboto-Bold", ofSize: 14.0)
        
        versionLabel.text = SDKVariableSetting.version
        
        paymentMethodTitle.text = B24PaymentSdkHelper.localized(PaymentMethodLocalizedKeys.title.rawValue)
        transactionLabel.text = B24PaymentSdkHelper.localized(PaymentMethodLocalizedKeys.amount.rawValue)
        
    }
    
//    private func fetchCheckoutDetailApi(){
//        AF.request(CheckoutRouter.checkoutDetail(transactionId: transactionId)).validate().responseData{
//            [self](response) in
//            switch response.result{
//            case .success(let data):
//                transaction = try? JSONDecoder().decode(Transaction.self, from: data)
//                if(transaction?.code == "SUCCESS"){
//                    bankPaymentMethods.removeAll()
//                    transactionInfo = (transaction?.data?.transInfo)
//                    checkoutPageConfig = (transaction?.data?.checkoutPageConfig)
//                    // Setting
//                    B24PaymentSdkHelper.getCurrentLanguage(language: transactionInfo?.language)
//                    setUpFontAndTranslatePaymentMethod(language: SDKVariableSetting.currentLanguage)
//                    Themes.setTheme(isDarkMode: SDKVariableSetting.isDarkMode, themeData: (checkoutPageConfig?.appearance)!)
//                    setUpTheme()
//                    setting = (checkoutPageConfig?.setting)
//                    bankPaymentMethods.append(contentsOf: (transaction?.data?.transInfo.bankPaymentMethod)!)
//                    loadBankCollectionView()
//                    registerFooterViewData(transactionInfo: transactionInfo!, checkoutPageConfig: checkoutPageConfig!)
//                    bankCollectionView.layoutIfNeeded()
//                    self.hideCenterLoading()
//                }else{
//                    B24PaymentSdkHelper.errorSnackbar(
//                        view: self,
//                        activitiyIndicator: centerLoading,
//                        message: (transaction?.messageKh ?? transaction?.message) ??  B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
//                        forBottomSheet: true
//                    )
//                    bankCollectionView.isHidden = true
//                    bottomView.isHidden = true
//                    print("Error\(String(describing: transaction?.messageKh))")
//                }
//                
//            case .failure(let error):
//                print(error)
//                B24PaymentSdkHelper.errorSnackbar(
//                    view: self,
//                    activitiyIndicator: centerLoading,
//                    message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
//                    forBottomSheet: true
//                )
//                bankCollectionView.isHidden = true
//                bottomView.isHidden = true
//            }
//        }
//    }
    
    private func fetchCheckoutDetailApi(){
        bankPaymentMethods.removeAll()
        transactionInfo = (transaction?.data?.transInfo)
        checkoutPageConfig = (transaction?.data?.checkoutPageConfig)
        // Setting
        B24PaymentSdkHelper.getCurrentLanguage(language: transactionInfo?.language)
        setUpFontAndTranslatePaymentMethod(language: SDKVariableSetting.currentLanguage)
        // Themes.useDefaults(isDarkMode: SDKVariableSetting.isDarkMode)
       Themes.setTheme(isDarkMode: SDKVariableSetting.isDarkMode, themeData: (checkoutPageConfig?.appearance)!)
        setUpTheme()
        setting = (checkoutPageConfig?.setting)
        // Take only payment method which having item
        for bankPaymentMethod in transaction?.data?.transInfo.bankPaymentMethod ?? [] {
            if(!bankPaymentMethod.items.isEmpty){
                bankPaymentMethods.append(bankPaymentMethod)
            }
        }
//        bankPaymentMethods.append(contentsOf: (transaction?.data?.transInfo.bankPaymentMethod)!)
        loadBankCollectionView()
        registerFooterViewData(transactionInfo: transactionInfo!, checkoutPageConfig: checkoutPageConfig!)
        bankCollectionView.layoutIfNeeded()
        self.hideCenterLoading()
    }
    
    private func setUpTheme(){
        paymentMethodTitle.textColor = UIColor(hex: Themes.Property.labelTextColor)
        transactionLabel.textColor  = UIColor(hex: Themes.Property.primaryTextColor)
        transactionAmount.textColor = UIColor(hex: Themes.Property.labelTextColor)
        powerByLabel.textColor = UIColor(hex: Themes.Property.secondaryTextColor)
        bill24Label.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        versionLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        bottomView.backgroundColor = UIColor(hex: Themes.Property.secondaryBackgroundColor)
        currencyLabel.textColor = UIColor(hex: Themes.Property.labelTextColor)
        dottedLineView.tintColor = UIColor(hex: Themes.Property.indicatorColor)
        bankCollectionView.backgroundColor = UIColor(hex: Themes.Property.secondaryBackgroundColor)
        paymentMethodView.backgroundColor = UIColor(hex: Themes.Property.secondaryBackgroundColor)
        verticalView.backgroundColor = UIColor(hex: Themes.Property.indicatorColor)

        applyCloseButtonTheme()

        bottomSheetController?.view.layoutIfNeeded()
        bottomSheetController?.appearanceSetup()
    }
    
    private func registerFooterViewData(transactionInfo: TransInfo, checkoutPageConfig: CheckoutPageConfig){
        transactionAmount.text = transactionInfo.tranAmountDisplay
        currencyLabel.text = transactionInfo.currency
        
        // Disable bill24 label
        if(checkoutPageConfig.displayBill24Info == false ){
            bill24Label.isHidden = true
            verticalView.isHidden = true
            powerByLabel.isHidden = true
        }else{
            bill24Label.isHidden = false
            verticalView.isHidden = false
            powerByLabel.isHidden = false
        }
        // Navigation to Bill24 Website
        bill24Label.isUserInteractionEnabled = true
        bill24Label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(navigateToBill24Url)))
    }
    
    @objc func navigateToBill24Url(){
        B24PaymentSdkHelper.openDeeplink(deepLinkUrl: APIManager.openBill24Website(), view: self)
    }
    
    private func loadBankCollectionView() {
        let nib = UINib(
            nibName: "BankCollectionViewCell",
            bundle: B24PaymentSdkHelper.frameworkBundle()
        )
        bankCollectionView.register(nib, forCellWithReuseIdentifier: "BankCollectionViewCell")
        
        bankCollectionView.delegate = self
        bankCollectionView.dataSource = self
        self.bankCollectionView.reloadData()
        
        let headerNib = UINib(nibName: "SectionHeader", bundle: B24PaymentSdkHelper.frameworkBundle())
        bankCollectionView.register(headerNib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "Header")
    }
    
    private func showCenterLoading() {
        centerLoading.startAnimating()
        centerLoading.isHidden = false
        self.isUserInteractionEnabled = false
        // Disable drag-to-close functionality while loading
        bottomSheetController?.disableDragToClose()
    }
    
    private func hideCenterLoading() {
        centerLoading.stopAnimating()
        centerLoading.isHidden = true
        self.isUserInteractionEnabled = true
        // Disable drag-to-close functionality
        bottomSheetController?.disableDragToClose()
    }
    
    // MARK: - Network Monitoring Setup
    private func setupNetworkMonitoring() {
        NetworkMonitor.shared.onConnectionStatusChanged = { [weak self] isConnected in
            guard let self = self else { return }
            
            if isConnected {
                guard self.isWaitingForConnection else { return }
                self.isWaitingForConnection = false
                B24PaymentSdkHelper.hideNoInternetPopup(from: self.controller)
            }
        }
    }
}

extension PaymentMethodView : UICollectionViewDelegate, UICollectionViewDataSource {
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        // Return the total number of sections in your collection view
        return bankPaymentMethods.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return bankPaymentMethods[section].items.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BankCollectionViewCell", for: indexPath) as! BankCollectionViewCell
        cell.setUp(with: (bankPaymentMethods[indexPath.section].items[indexPath.row]), tranInfo: transactionInfo!, setting: setting!)
        cell.setUpFontAndTranslateBankCollectionView()
        cell.setUpStyleAndConstraintCell()
        setUpCellStyle(cell: cell)
        setUpAddToFavorite(cell: cell, bankItem: bankPaymentMethods[indexPath.section].items[indexPath.row])
        cell.backgroundColor = UIColor(hex: Themes.Property.bankButtonBackgroundColor)
        return cell
    }
    
     func setUpAddToFavorite(cell: BankCollectionViewCell, bankItem: BankPaymentItem) {
        // Create a new instance of CustomTapGestureRecognizer
        let tapGesture = CustomTapGestureRecognizer(target: self, action: #selector(clickAddToFavoriteView(sender:)))
        tapGesture.cell = cell
        tapGesture.bankId = bankItem.id
        tapGesture.isFavourite = cell.isFavourite

        // Attach the tap gesture to the favoriteView subview
        cell.favoriteView.addGestureRecognizer(tapGesture)
        cell.favoriteView.isUserInteractionEnabled = true
    }
    
    @objc func clickAddToFavoriteView(sender: CustomTapGestureRecognizer){
        // Check Network Connection
        guard NetworkMonitor.shared.isConnected else {
            if !isWaitingForConnection {
                isWaitingForConnection = true
                setupNetworkMonitoring()
                NetworkMonitor.shared.startMonitoring()
                
                B24PaymentSdkHelper.showNoInternetPopup(on: self.controller) { [weak self] in
                    guard let self = self else { return }
                    self.isWaitingForConnection = false
                    B24PaymentSdkHelper.hideNoInternetPopup(from: self.controller, showSuccess: false)
                }
            }
            return
        }
        
        // toggle favorite state
        sender.cell.isFavourite = !sender.cell.isFavourite
        AF.request(CheckoutRouter.addToFavorite(transactionId: transactionId, bankId: sender.bankId, isFavorite: sender.cell.isFavourite)).validate().responseData{
            [self] response in
            switch response.result{
            case .success(let data):
                let favoriteBankResult  = try? JSONDecoder().decode(FavoriteBankResponse.self, from: data)
                if(favoriteBankResult?.code == "SUCCESS"){
                    // Perform other actions based on the tap event
                    if (sender.cell.isFavourite == true) {
                        sender.cell.favoriteIcon.image =  UIImage(systemName: "star.fill")
                    } else {
                        sender.cell.favoriteIcon.image = UIImage(systemName: "star")
                    }
                }else{
                    B24PaymentSdkHelper.errorSnackbar(
                        view: self,
                        message: (favoriteBankResult?.messageKh ?? favoriteBankResult?.message) ??  B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                        forBottomSheet: true
                    )
                }
                self.hideCenterLoading()
            case .failure(let error):
                print(error)
                self.hideCenterLoading()
                let message = error.isSessionTaskError ? B24PaymentSdkHelper.localized("msg_error_connect") : B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue)
                B24PaymentSdkHelper.errorSnackbar(
                    view: self,
                    message: message,
                    forBottomSheet: true
                )
            }
        }
    }
    
    private func setUpCellStyle(cell: UICollectionViewCell){
        cell.layer.cornerRadius = 12
        cell.layer.borderWidth = 1
        let borderColor = SDKVariableSetting.isDarkMode
            ? UIColor(hex: Themes.Property.indicatorColor)       // #4B5563 for dark
            : UIColor(hex: "#E5E7EB")                            // light gray for light
        cell.layer.borderColor = borderColor.cgColor
        cell.layer.masksToBounds = true
    }
    
    public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        guard kind == UICollectionView.elementKindSectionHeader else {
            fatalError("Invalid supplementary view kind")
        }
        
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! SectionHeader
        
        if(SDKVariableSetting.currentLanguage.lowercased() == "en"){
            headerView.titleLabel.text = bankPaymentMethods[indexPath.section].section
        }else{
            headerView.titleLabel.text = bankPaymentMethods[indexPath.section].sectionKh
        }
        headerView.titleLabel.font = FontManager.shared.boldFont(forLanguage: SDKVariableSetting.currentLanguage, size: 13.0)
        headerView.titleLabel.textColor = UIColor(hex: Themes.Property.labelTextColor)
        headerView.backgroundColor = UIColor(hex: Themes.Property.secondaryBackgroundColor)
        
        return headerView
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // Check Network Connection
        guard NetworkMonitor.shared.isConnected else {
            if !isWaitingForConnection {
                isWaitingForConnection = true
                setupNetworkMonitoring()
                NetworkMonitor.shared.startMonitoring()
                
                B24PaymentSdkHelper.showNoInternetPopup(on: self.controller) { [weak self] in
                    guard let self = self else { return }
                    self.isWaitingForConnection = false
                    B24PaymentSdkHelper.hideNoInternetPopup(from: self.controller, showSuccess: false)
                }
            }
            return
        }
        
        // Handle cell selection here
        let bankItem  = bankPaymentMethods[indexPath.section].items[indexPath.row]
        if bankItem.id.lowercased() == "khqr" {
            // Directly swap to KHQR view without dismissing the bottom sheet
            guard let bottomSheet = bottomSheetController else { return }
            
            // Remove current view from container
            self.removeFromSuperview()
            
            // Create KHQR view
            let khqrView = KHQRView(
                frame: controller.view.frame,
                transactionId: transactionId,
                controller: controller,
                transactionData: transaction!,
                bottomSheetController: bottomSheet
            )
            
            // Add KHQR view to the same bottom sheet container
            bottomSheet.bottomSheetContainerView.addSubview(khqrView)
            
            // Notify bottom sheet about the stationary view
            bottomSheet.notifyStationaryViewAdded()
            
            // Update view type and animate the height change
            bottomSheet.viewType = .sixtyPercent
            UIView.animate(withDuration: 0.3) {
                bottomSheet.updateViewConstraints()
                bottomSheet.view.layoutIfNeeded()
            }
        } else {
            generateLinkApi(bankId: bankItem.id, transactionId: transactionId)
        }
    }
    
    private func generateLinkApi(bankId: String, transactionId: String){
        // Check Network Connection
        guard NetworkMonitor.shared.isConnected else {
            if !isWaitingForConnection {
                isWaitingForConnection = true
                setupNetworkMonitoring()
                NetworkMonitor.shared.startMonitoring()
                
                B24PaymentSdkHelper.showNoInternetPopup(on: self.controller) { [weak self] in
                    guard let self = self else { return }
                    self.isWaitingForConnection = false
                    B24PaymentSdkHelper.hideNoInternetPopup(from: self.controller, showSuccess: false)
                }
            }
            return
        }
        
        self.showCenterLoading()
        AF.request(CheckoutRouter.generateLink(bankId: bankId, transactionId: transactionId)).validate().responseData{
            [self] response in
            switch response.result{
            case .success(let data):
                generateLinkResponse = try? JSONDecoder().decode(GenerateLinkResponse.self, from: data)
                if(generateLinkResponse?.code == "SUCCESS"){
                    if let mobileDeepLink = generateLinkResponse?.data?.mobileDeepLink, !mobileDeepLink.isEmpty {
                        B24PaymentSdkHelper.openDeeplink(deepLinkUrl: mobileDeepLink, view: self) { success in
                            if !success {
                                // Fallback to external browser if deep link fails
                                if let webPaymentUrl = self.generateLinkResponse?.data?.webPaymentURL, !webPaymentUrl.isEmpty {
                                    B24PaymentSdkHelper.openDeeplink(deepLinkUrl: webPaymentUrl, view: self)
                                } else {
                                    // No web fallback available, show error
                                    B24PaymentSdkHelper.errorSnackbar(
                                        view: self,
                                        message: B24PaymentSdkHelper.localized("msg_unable_to_open_payment"),
                                        forBottomSheet: true
                                    )
                                }
                            }
                        }
                    } else if let webPaymentUrl = generateLinkResponse?.data?.webPaymentURL, !webPaymentUrl.isEmpty {
                        B24PaymentSdkHelper.openDeeplink(deepLinkUrl: webPaymentUrl, view: self)
                    }else{
                        B24PaymentSdkHelper.errorSnackbar(
                            view: self,
                            message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                            forBottomSheet: true
                        )
                    }
                }else{
                    print("Error\(String(describing: generateLinkResponse?.messageKh))")
                    B24PaymentSdkHelper.errorSnackbar(
                        view: self,
                        message:  (generateLinkResponse?.messageKh ?? generateLinkResponse?.message) ??  B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                        forBottomSheet: true
                    )
                }
                self.hideCenterLoading()
            case .failure(let error):
                print(error)
                self.hideCenterLoading()
                let message = error.isSessionTaskError ? B24PaymentSdkHelper.localized("msg_error_connect") : B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue)
                B24PaymentSdkHelper.errorSnackbar(
                    view: self,
                    message: message,
                    forBottomSheet: true
                )
            }
        }
    }
}

class CustomTapGestureRecognizer: UITapGestureRecognizer {
    var cell: BankCollectionViewCell!
    var bankId: String!
    var isFavourite: Bool!
}






