import UIKit
import Alamofire

// Protocol for Android-like scroll-to-collapse behavior
protocol TransactionsViewDelegate: AnyObject {
    func shouldCollapseBottomSheet()
    func shouldExpandBottomSheet()
}

struct TransactionSection {
    let date: String
    var transactions: [DWalletTransaction]
}

private func debugLogTransactions(_ transactions: [DWalletTransaction], context: String) {
    print("========== \(context) ==========")
    let encoder = JSONEncoder()
    encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
    for (index, transaction) in transactions.enumerated() {
        if let data = try? encoder.encode(transaction),
           let json = String(data: data, encoding: .utf8) {
            print("[\(index)] \(json)")
        } else {
            print("[\(index)] unable to encode transaction: \(transaction.tranID)")
        }
    }
    print("================================")
}

class TransactionsView: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var transactionCollectionView: UICollectionView!
    @IBOutlet weak var indicator: UIView!
    @IBOutlet weak var progressIndicator: UIActivityIndicatorView!
    
    // Android-like scroll-to-collapse delegate
    weak var delegate: TransactionsViewDelegate?
    
    // Programmatic indicator to avoid storyboard constraint issues
    private lazy var programmaticIndicator: UIView = {
        let indicatorView = UIView()
        indicatorView.backgroundColor = SDKVariableSetting.isDarkMode == true ? UIColor(hex:SDKVariableSetting.indicatorDark) :UIColor(hex:SDKVariableSetting.indicatorLight)
        indicatorView.layer.cornerRadius = 4
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        return indicatorView
    }()
    
    private var transactionSections: [TransactionSection] = []
    var accountId: String = ""
    
    // Android-like scroll behavior control
    private var isBottomSheetCollapsed: Bool = true
    private var isAtTopOfContent: Bool = false
    private var hasScrolledPastTop: Bool = false
    
    // Enhanced scroll-to-collapse control
    private var collapseScrollLockActive: Bool = false
    private var hasUserScrolledAwayFromTop: Bool = false

    private var isWaitingForConnection: Bool = false

    private var currentPage = 1
    private let pageSize = 10
    private var isLastPage = false
    var language:String = ""
    private var lastFetchTime: Date?
    
    private let centerLoadingIndicator: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(style: .large)
        indicator.hidesWhenStopped = true
        indicator.color = DefaultAppearance.shared.primaryColor
        indicator.translatesAutoresizingMaskIntoConstraints = false
        return indicator
    }()

    // MARK: - State Management
    private var hasCheckedInitialNetworkState: Bool = false
    private weak var transactionDetailView: TransactionDetailView?

    private var isLoading: Bool = false {
        didSet {
            updateLoadingState()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = DefaultAppearance.shared.cardColor

        getSharePref()

        setUpCollectionViewCell()
        setupProgrammaticIndicator()

        // Hide IBOutlet indicator to prevent conflicts
        progressIndicator.isHidden = true

        // Add footer loading view
        view.addSubview(footerLoadingView)
        NSLayoutConstraint.activate([
            footerLoadingView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            footerLoadingView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20)
        ])

        // Add empty data label with center alignment
        view.addSubview(emptyDataLabel)
        emptyDataLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            emptyDataLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            emptyDataLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            emptyDataLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            emptyDataLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)
        ])

        // Add center loading indicator
        view.addSubview(centerLoadingIndicator)
        NSLayoutConstraint.activate([
            centerLoadingIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            centerLoadingIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // Only fetch transactions on first appearance
        guard !hasCheckedInitialNetworkState else { return }
        hasCheckedInitialNetworkState = true
        
        fetchTransactions()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NetworkMonitor.shared.onConnectionStatusChanged = nil
        isWaitingForConnection = false
        B24PaymentSdkHelper.removePersistentSnackbar(from: view)
    }

    // Recalculate insets whenever layout changes (e.g., bottom sheet height adjustment)
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        updateCollectionInsets()
    }
    
    // MARK: - Empty State UI Update
    private func updateEmptyState(isOffline: Bool, customMessage: String? = nil) {
        let iconName = isOffline ? "wifi.exclamationmark" : "clock.arrow.circlepath"
        
        if let iconView = emptyDataLabel.subviews.first(where: { $0 is UIImageView }) as? UIImageView {
            iconView.image = UIImage(systemName: iconName)
            iconView.tintColor = DefaultAppearance.shared.warningColor
        }
        
        if let label = emptyDataLabel.subviews.first(where: { $0 is UILabel }) as? UILabel {
            if let customMessage = customMessage {
                label.text = customMessage
            } else {
                let messageKey = isOffline ? SnackBarLocalizedKeys.error_connect_server.rawValue : AccountDetailLocalizedKeys.no_tran_history.rawValue
                label.text = B24PaymentSdkHelper.localized(messageKey)
            }
        }
    }
    
    
    private func startLoading(){
        // Only use footer loading view for consistency
        // Hide the IBOutlet indicator to avoid conflicts
        progressIndicator.stopAnimating()
        progressIndicator.isHidden = true
    }
    
    private func stopLoading(){
        // Only manage footer loading view
        progressIndicator.stopAnimating()
        progressIndicator.isHidden = true
    }
    
    
    private func getSharePref(){
        if let languageCode = SharedPreferenceManager.getString(forKey: SharePrefKey.lanuageCode.rawValue){
            language = languageCode
        }else{
            language = "km"
        }
    }

    private func setUpCollectionViewCell() {
        let nibName = UINib(nibName: "TransactionViewCell", bundle: B24PaymentSdkHelper.frameworkBundle())
        self.transactionCollectionView.backgroundColor = DefaultAppearance.shared.cardColor
        self.transactionCollectionView.register(nibName, forCellWithReuseIdentifier: "TransactionViewCell")
        
        let headerNib = UINib(nibName: "SectionHeader", bundle: B24PaymentSdkHelper.frameworkBundle())
        self.transactionCollectionView.register(headerNib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "Header")
        
        if let layout = transactionCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.sectionHeadersPinToVisibleBounds = true
            layout.estimatedItemSize = .zero
        }

        self.transactionCollectionView.delegate = self
        self.transactionCollectionView.dataSource = self
        self.transactionCollectionView.alwaysBounceVertical = true
        self.transactionCollectionView.clipsToBounds = true
    }

    private func setupProgrammaticIndicator() {
        // Hide the IBOutlet indicator to avoid conflicts
        indicator.isHidden = true

        // Add our programmatic indicator
        view.addSubview(programmaticIndicator)

        // Set up constraints for fixed size and positioning
        NSLayoutConstraint.activate([
            // Fixed size constraints - never changes
            programmaticIndicator.widthAnchor.constraint(equalToConstant: 40),
            programmaticIndicator.heightAnchor.constraint(equalToConstant: 5),

            // Positioning constraints
            programmaticIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            programmaticIndicator.topAnchor.constraint(equalTo: view.topAnchor, constant: 8)
        ])
    }

    // MARK: - Adaptive Insets
    private func updateCollectionInsets() {
        view.layoutIfNeeded()
        
        // Calculate proper bottom inset to ensure last item is properly visible
        let footerHeight: CGFloat = footerLoadingView.isHidden ? 0 : 44  // Height for loading indicator
        let safeAreaBottom: CGFloat = view.safeAreaInsets.bottom
        let basicPadding: CGFloat = 20  // Additional padding to ensure last item is fully visible
        
        // Ensure the last item has enough space to be fully visible above any bottom content
        let bottomInset = footerHeight + basicPadding + safeAreaBottom
        
        // Use 0 top inset to ensure sticky headers stick to the absolute top of the view
        let insets = UIEdgeInsets(top: 0, left: 0, bottom: bottomInset, right: 0)
        transactionCollectionView.contentInset = insets
        transactionCollectionView.scrollIndicatorInsets = insets
        
        // Force layout update to apply changes immediately
        transactionCollectionView.setNeedsLayout()
        transactionCollectionView.layoutIfNeeded()
    }

    // Parent calls after resizing sheet height
    func refreshInsets() { updateCollectionInsets() }
    
    // 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.parent ?? self)
                // Auto-refresh when connection is restored
                self.refreshTransactions()
            }
        }
    }
    
    // MARK: - Android-like Scroll Control
    func setBottomSheetState(collapsed: Bool) {
        isBottomSheetCollapsed = collapsed
        
        // Reset all scroll state when state changes
        resetScrollState()
        
        // Android behavior: Disable scrolling when collapsed (medium state)
        // Enable scrolling when expanded (large state)
        transactionCollectionView.isScrollEnabled = !collapsed
        
        if collapsed {
            // When collapsing: Always reset to top position immediately
            transactionCollectionView.setContentOffset(.zero, animated: false)
            isAtTopOfContent = true
        } else {
            // When expanding: Enable scrolling
            // Only reset to top if we were previously collapsed to avoid jumps during simple snaps
            if isBottomSheetCollapsed {
                DispatchQueue.main.async {
                    self.transactionCollectionView.setContentOffset(.zero, animated: false)
                    self.isAtTopOfContent = true
                }
            }
            
            DispatchQueue.main.async {
                self.transactionCollectionView.isScrollEnabled = true
            }
        }
    }

    // MARK: - Grip / Indicator adaptive appearance
    // progress: 0 (collapsed) -> 1 (expanded)
    func updateGripAppearance(progress: CGFloat) {
        // Update only the opacity of our programmatic indicator
        // Size remains fixed at 40x5 points always
        let baseAlpha: CGFloat = 1
        let expandedAlpha: CGFloat = 1
        programmaticIndicator.alpha = baseAlpha + (expandedAlpha - baseAlpha) * progress
    }


    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y
        
        // Only handle collapse behavior when bottom sheet is expanded
        if !isBottomSheetCollapsed {
            let isCurrentlyAtTop = offsetY <= 5 // Small threshold for "at top"
            
            // Track if user is at top for parent gesture coordination
            if isCurrentlyAtTop {
                isAtTopOfContent = true
            } else if offsetY > 20 {
                isAtTopOfContent = false
                hasUserScrolledAwayFromTop = true
            }
        }
        
        // Pagination: Load more content when near bottom
        guard !isLoading, !isLastPage else { return }
        
        let contentHeight = scrollView.contentSize.height
        let frameHeight = scrollView.frame.size.height
        let threshold: CGFloat = 120
        
        if offsetY > contentHeight - frameHeight - threshold {
            fetchTransactions()
        }
    }
    
    private func resetScrollState() {
        isAtTopOfContent = true // Start assuming we're at top
        hasScrolledPastTop = false
        collapseScrollLockActive = false
        hasUserScrolledAwayFromTop = false
        
        // Ensure collection view is enabled and properly positioned
        if !isBottomSheetCollapsed {
            transactionCollectionView.isScrollEnabled = true
        }
    }

    private let footerLoadingView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(style: .medium)
        indicator.hidesWhenStopped = true
        indicator.color = DefaultAppearance.shared.primaryColor
        indicator.translatesAutoresizingMaskIntoConstraints = false
        return indicator
    }()

    private lazy var emptyDataLabel: UIView = {
            let containerView = UIView()
            containerView.isHidden = true
            containerView.translatesAutoresizingMaskIntoConstraints = false

            // Create exclamation icon image view
            let iconImageView = UIImageView()
            iconImageView.translatesAutoresizingMaskIntoConstraints = false
            iconImageView.image = UIImage(systemName: "clock.arrow.circlepath")
            iconImageView.tintColor = DefaultAppearance.shared.secondaryLabelColor
            iconImageView.contentMode = .scaleAspectFit

            // Create label
            let label = UILabel()
            label.translatesAutoresizingMaskIntoConstraints = false
            label.text = B24PaymentSdkHelper.localized(AccountDetailLocalizedKeys.no_tran_history.rawValue)
            label.textColor = DefaultAppearance.shared.secondaryLabelColor
        label.font = FontManager.shared.mediumFont(forLanguage: "en" ,fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
            label.textAlignment = .center
            label.numberOfLines = 0
       

            // Add subviews
            containerView.addSubview(iconImageView)
            containerView.addSubview(label)

            // Setup constraints
            NSLayoutConstraint.activate([
                iconImageView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
                iconImageView.topAnchor.constraint(equalTo: containerView.topAnchor),
                iconImageView.widthAnchor.constraint(equalToConstant: 40),
                iconImageView.heightAnchor.constraint(equalToConstant: 40),

                label.topAnchor.constraint(equalTo: iconImageView.bottomAnchor, constant: 16),
                label.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20),
                label.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20),
                label.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
            ])

            return containerView
        }()

    // MARK: - Fetch Transactions
    private func fetchTransactions() {
        guard !isLoading, !isLastPage else { return }
        
        // Debounce: prevent rapid successive calls
        let now = Date()
        if let lastFetch = lastFetchTime, now.timeIntervalSince(lastFetch) < 0.5 {
            return
        }
        
        lastFetchTime = now
        
        // If this is the first page, reset the state
        if currentPage == 1 {
            transactionSections.removeAll()
            isLastPage = false
            // Hide empty data label during initial loading
            emptyDataLabel.isHidden = true
        }
        
        isLoading = true
        if currentPage == 1 {
            centerLoadingIndicator.startAnimating()
        } else {
            footerLoadingView.startAnimating()
            updateCollectionInsets()
        }
        
        // Don't call startLoading() - causes conflict with footerLoadingView

        let url = APIManager.merchantApiUrl().appendingPathComponent("instantpaymentsdk/payment_method/transactions")
        let parameters: [String: Any] = [
            "id": accountId,
            "pagination": [
                "current_page": currentPage,
                "page_size": pageSize
            ]
        ]
        print("TransactionsView request -> url: \(url.absoluteString), payload: \(parameters)")

        AF.request(
            url,
            method: .post,
            parameters: parameters,
            encoding: JSONEncoding.default,
            headers: APIManager.initHeader()
        )
        .validate()
        .responseDecodable(of: DWalletTransactionResponseModel.self) { [weak self] response in
            guard let self = self else { return }
            self.isLoading = false
            self.centerLoadingIndicator.stopAnimating()
            self.footerLoadingView.stopAnimating()
            self.updateCollectionInsets()

            switch response.result {
            case .success(let responseModel):
                if responseModel.code == StatusCode.succcess.rawValue {
                    debugLogTransactions(
                        responseModel.data.transactions,
                        context: "TransactionsView response page \(self.currentPage)"
                    )
                    // Don't call stopLoading() - already handled by footerLoadingView.stopAnimating()
                    
                    // Filter out any transactions that already exist (prevent duplicates)
                    let existingTransactionIDs = Set(self.transactionSections.flatMap { $0.transactions }.map { $0.tranID })
                    let newTransactions = responseModel.data.transactions.filter { !existingTransactionIDs.contains($0.tranID) }
                    
                    print("DEBUG: Page \(self.currentPage), Got \(responseModel.data.transactions.count) transactions, \(newTransactions.count) are new")
                    
                    self.groupTransactionsByDate(newTransactions)
                    self.isLastPage = responseModel.data.pagination.hasNextPage == false
                    self.transactionCollectionView.reloadData()
                    self.updateCollectionInsets()
                    self.emptyDataLabel.isHidden = !self.transactionSections.isEmpty
                    self.currentPage += 1
                } else {
//                    self.showError(message: responseModel.message)
                    let message = (self.language.lowercased() == "en") ? responseModel.message : responseModel.messageKh
                    
                    if self.currentPage == 1 {
                        self.updateEmptyState(isOffline: false, customMessage: message)
                        self.emptyDataLabel.isHidden = false
                    } else {
                        B24PaymentSdkHelper.errorSnackbar(view: self.view, message: message)
                    }
                }
            case .failure(let error):
                print("=====>\(error)")

                if self.currentPage == 1 {
                    self.updateEmptyState(isOffline: false, customMessage: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue))
                    self.emptyDataLabel.isHidden = false
                } else {
                    B24PaymentSdkHelper.errorSnackbar(
                        view: self.view,
                        message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                        forBottomSheet: false
                    )
                }
            }
        }
    }

    private func groupTransactionsByDate(_ newTransactions: [DWalletTransaction]) {
        for transaction in newTransactions {
            let dateKey = B24PaymentSdkHelper.formatDateOnly(transaction.tranDate)
            
            if let index = transactionSections.firstIndex(where: { $0.date == dateKey }) {
                transactionSections[index].transactions.append(transaction)
            } else {
                transactionSections.append(TransactionSection(date: dateKey, transactions: [transaction]))
            }
        }
    }

    // MARK: - Public Methods
    func refreshTransactions() {
        // Reset pagination state and reload from beginning
        currentPage = 1
        isLastPage = false
        isLoading = false
        lastFetchTime = nil
        transactionSections.removeAll()
        transactionCollectionView.reloadData()
        
        // Reset scroll state and position
        resetScrollState()
        transactionCollectionView.setContentOffset(.zero, animated: false)
        
        fetchTransactions()
    }

    // MARK: - Loading State
    private func updateLoadingState() {
        DispatchQueue.main.async {
            // Only manage indicators if not pagination
            if self.currentPage == 1 && self.isLoading {
                self.centerLoadingIndicator.startAnimating()
                self.footerLoadingView.stopAnimating()
            } else if self.isLoading {
                self.centerLoadingIndicator.stopAnimating()
                self.footerLoadingView.startAnimating()
            } else {
                self.centerLoadingIndicator.stopAnimating()
                self.footerLoadingView.stopAnimating()
            }
            
            self.footerLoadingView.isHidden = !self.isLoading || self.currentPage == 1
            
            // Show empty container if we have no data
            if !self.isLoading {
                // Only show empty label (with either "No History" or "Offline" message) 
                // if we have no transaction data to display.
                self.emptyDataLabel.isHidden = !self.transactionSections.isEmpty
                
                // Update specific icon/text based on connection state
                self.updateEmptyState(isOffline: self.isWaitingForConnection)
            } else {
                // Always hide empty data label when loading
                self.emptyDataLabel.isHidden = true
            }
        }
    }

    // MARK: - Error Handling
    private func showError(message: String) {
        let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }

    // MARK: - Collection View Data Source
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return transactionSections.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return transactionSections[section].transactions.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = transactionCollectionView.dequeueReusableCell(withReuseIdentifier: "TransactionViewCell", for: indexPath) as! TransactionViewCell
        let transaction = transactionSections[indexPath.section].transactions[indexPath.item]
        configureTransactionCell(cell, with: transaction, at: indexPath)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! SectionHeader
            header.titleLabel.text = transactionSections[indexPath.section].date
            header.titleLabel.font = FontManager.shared.mediumFont(forLanguage: "en", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
            header.titleLabel.textColor = DefaultAppearance.shared.primaryLabelColor
            
            // Ensure background matches the screen background
            header.backgroundColor = DefaultAppearance.shared.screenBgColor
            
            // Set high zPosition to stay on top of transaction cells
            header.layer.zPosition = 10
            
            return header
        }
        return UICollectionReusableView()
    }

    private func configureTransactionCell(_ cell: TransactionViewCell, with transaction: DWalletTransaction, at indexPath: IndexPath) {
        cell.container.backgroundColor = DefaultAppearance.shared.cardColor

        cell.line.backgroundColor = DefaultAppearance.shared.primaryLabelColor.withAlphaComponent(0.1)
        cell.line.isHidden = false

        if transaction.tranType == TransactionType.walletTopup.rawValue {
            let placeholder = UIImage(systemName: "arrow.down.backward")
            cell.setLogoFill(false)
            cell.logo.loadImage(from: transaction.logo, placeholder: placeholder) { success in
                if success {
                    cell.setLogoFill(true)
                }
            }
            cell.logo.tintColor = nil
            cell.bgLogo.backgroundColor = DefaultAppearance.shared.successColor.withAlphaComponent(0.1)
            cell.amountLabel.textColor = DefaultAppearance.shared.successColor
            cell.amountLabel.text = transaction.totalAmountDisplay
        } else {
            cell.setLogoFill(false)
            cell.logo.image = UIImage(systemName: "arrow.up.left")
            cell.logo.tintColor = DefaultAppearance.shared.dangerColor
            cell.bgLogo.backgroundColor = DefaultAppearance.shared.dangerColor.withAlphaComponent(0.1)
            cell.amountLabel.textColor = DefaultAppearance.shared.dangerColor
            cell.amountLabel.text = transaction.totalAmountDisplay
        }

        if transaction.tranType == TransactionType.walletTopup.rawValue {
            let value = (transaction.paidFrom?.isEmpty == false) ? transaction.paidFrom! : "N/A"
            cell.tranDateLabel.text = "\(value)"
            
            let descEn = transaction.descriptionEn.trimmingCharacters(in: .whitespacesAndNewlines)
            let descKm = transaction.descriptionKm.trimmingCharacters(in: .whitespacesAndNewlines)
            if language.lowercased() == "en" {
                cell.detailLabel.text = descEn.isEmpty ? B24PaymentSdkHelper.localized(TopupLocalizedKeys.topup.rawValue) : descEn
            } else {
                cell.detailLabel.text = descKm.isEmpty ? B24PaymentSdkHelper.localized(TopupLocalizedKeys.topup.rawValue) : descKm
            }
        } else {
            let value = (transaction.paidTo?.isEmpty == false) ? transaction.paidTo! : "N/A"
            cell.tranDateLabel.text = "\(value)"
            cell.detailLabel.text = (language.lowercased() == "en") ? (transaction.descriptionEn) : (transaction.descriptionKm)
        }
        
        cell.tranDateLabel.font = B24PaymentSdkHelper.setFont(named: FixFontFamily.fontEnglishMedium, ofSize: FixFontSize.tranText)
        cell.tranDateLabel.textColor = DefaultAppearance.shared.secondaryLabelColor

        cell.detailLabel.font = B24PaymentSdkHelper.setFont(named: FixFontFamily.fontEnglishMedium, ofSize: FixFontSize.tranTypeText)
        cell.detailLabel.textColor = DefaultAppearance.shared.primaryLabelColor.withAlphaComponent(0.4)

        
//        cell.amountLabel.font = B24PaymentSdkHelper.setFont(named: FixFontFamily.fontEnglishMedium, ofSize: FixFontSize.buttonText)
        cell.amountLabel.font = FontManager.shared.mediumFont(forLanguage: "en",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.buttonText)
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // Check Network Connection
        guard NetworkMonitor.shared.isConnected else {
            if !isWaitingForConnection {
                isWaitingForConnection = true
                
                // Start monitoring on-demand
                setupNetworkMonitoring()
                NetworkMonitor.shared.startMonitoring()
                
                B24PaymentSdkHelper.showNoInternetPopup(on: self.parent ?? self) { [weak self] in
                    guard let self = self else { return }
                    self.isWaitingForConnection = false
                    B24PaymentSdkHelper.hideNoInternetPopup(from: self.parent ?? self, showSuccess: false)
                }
            }
            return
        }

        let selectedTransaction = transactionSections[indexPath.section].transactions[indexPath.item]
        let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
        guard let transactionDetailVC = storyboard.instantiateViewController(withIdentifier: "TransactionDetailView") as? TransactionDetailView else { return }

        // Pass the transaction ID to the detail view
        transactionDetailVC.tranID = selectedTransaction.tranID
        
        // Store reference to forward connection changes
        self.transactionDetailView = transactionDetailVC

        transactionDetailVC.modalPresentationStyle = .overFullScreen
        self.present(transactionDetailVC, animated: false) {
            // Send initial connection state after view is presented
            self.transactionDetailView?.handleConnectionChange(isConnected: NetworkMonitor.shared.isConnected)
        }
    }

    // MARK: - Collection View Flow Layout Delegate
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.width
        let height: CGFloat = 80 // Fixed height for consistent alignment
        return CGSize(width: width, height: height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 35)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0 // No spacing between rows for clean appearance
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0 // No spacing between items in the same row
    }

}
