//
//  TransactionDetailView.swift
//  B24PaymentSdk
//
//  Created by visal ny on 24/12/24.
//

import UIKit
import Alamofire

class TransactionDetailView: UIViewController {

    @IBOutlet weak var bgContainer: UIView!
    
    @IBOutlet weak var imageDownload: UIView!
    @IBOutlet weak var indicator: UIView!
    
    @IBOutlet weak var bgLogo: UIView!
    @IBOutlet weak var line: UIView!
    @IBOutlet weak var dashLine: UIView!
    
    @IBOutlet weak var shareContainer: UIView!
    @IBOutlet weak var downloadContainer: UIView!
    @IBOutlet weak var logo: UIImageView!
    @IBOutlet weak var amountLable: UILabel!
    @IBOutlet weak var detailLabel: UILabel!
    @IBOutlet weak var tranIdLabel: UILabel!
    @IBOutlet weak var invoiceIdText: UILabel!
    @IBOutlet weak var paidPayText: UILabel!
    @IBOutlet weak var originalAmountText: UILabel!
    @IBOutlet weak var feeText: UILabel!
    @IBOutlet weak var referenceText: UILabel!
    @IBOutlet weak var tranDateText: UILabel!
    @IBOutlet weak var tranIdValue: UILabel!
    @IBOutlet weak var invoiceIdValue: UILabel!
    @IBOutlet weak var paidPayValue: UILabel!
    @IBOutlet weak var feeValue: UILabel!
    @IBOutlet weak var originalAmountValue: UILabel!
    @IBOutlet weak var referenceValue: UILabel!
    @IBOutlet weak var tranDateValue: UILabel!
    
    @IBOutlet weak var downshareContainer: UIView!
    
    @IBOutlet weak var bgDownloadLogo: UIView!
    
    @IBOutlet weak var downloadLogo: UIImageView!
    
    @IBOutlet weak var downloadText: UILabel!
    @IBOutlet weak var shareLogo: UIImageView!
    
    @IBOutlet weak var shareText: UILabel!
    @IBOutlet weak var bgShareLogo: UIView!
    @IBOutlet weak var emptyLabel: UILabel!
    @IBOutlet weak var emptyImage: UIImageView!
    
    @IBOutlet weak var progressContainerMain: UIView!
    
    @IBOutlet weak var progressMain: UIActivityIndicatorView!
    private let activityIndicator = UIActivityIndicatorView(style: .medium)
    
    
    @IBOutlet weak var invoiceIdHeightConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var invoiceIdBottomSpace: NSLayoutConstraint!
    
    @IBOutlet weak var invoiceIdValueHeightConstraint: NSLayoutConstraint!

    @IBOutlet weak var invoiceValueBottomSpace: NSLayoutConstraint!
    
    private var panGesture: UIPanGestureRecognizer!
    private var initialContainerY: CGFloat = 0
    var tranID: String = ""
    var tranDetail = DataWalletTransactionDetail()
    var language: String?
    let emptyIconName = "exclamationmark.circle.fill"
    private var logoConstraints: [NSLayoutConstraint] = []
    private let titleLabel = UILabel()
    private let statusBadgeLabel = PaddedLabel()
    private var isWaitingForConnection: Bool = false
    private var hasCheckedInitialNetworkState: Bool = false


    private var isLoading: Bool = false {
            didSet {
                if isLoading {
                    LoadingIndicatorManager.shared.showLoading(in: view)
                } else {
                    LoadingIndicatorManager.shared.hideLoading()
                }
            }
        }

    override func viewDidLoad() {
          super.viewDidLoad()
          setupUI()
          // Initial fetch will be done in viewDidAppear after view is in hierarchy
      }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // Start off-screen at the bottom
        bgContainer.transform = CGAffineTransform(translationX: 0, y: view.frame.height)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // Only check network state on first appearance
        guard !hasCheckedInitialNetworkState else {
            // Slide up with animation and fade in background dimming
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
                self.bgContainer.transform = .identity
                self.view.backgroundColor = UIColor.black.withAlphaComponent(0.35)
            }
            return
        }
        hasCheckedInitialNetworkState = true
        
        // Check network status before fetching
        if !NetworkMonitor.shared.isConnected {
            // Show offline state immediately
            isWaitingForConnection = true
            
            progressMain.stopAnimating()
            progressMain.isHidden = true
            emptyImage.isHidden = false
            emptyLabel.isHidden = false
            
            emptyImage.image = UIImage(systemName: "wifi.exclamationmark")
            emptyImage.tintColor = DefaultAppearance.shared.warningColor
            emptyLabel.text = B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error_connect_server.rawValue)
            emptyLabel.textColor = DefaultAppearance.shared.primaryLabelColor
            emptyLabel.font = FontManager.shared.regularFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
            
            B24PaymentSdkHelper.persistentErrorSnackbar(
                view: self.view,
                message: B24PaymentSdkHelper.localized(
                    SnackBarLocalizedKeys.error_connect_server.rawValue
                ),
                forBottomSheet: false
            )
        } else {
            fetchTransactionDetails() // Fetch only if connected
        }

        // Resize container to fit content before slide-up so it's compact from the start
        adjustContainerToFitContent()

        // Slide up with animation and fade in background dimming
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
            self.bgContainer.transform = .identity
            self.view.backgroundColor = UIColor.black.withAlphaComponent(0.35)
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        // Force the indicator size using frame (backup approach)
        let currentFrame = indicator.frame
        indicator.frame = CGRect(x: currentFrame.origin.x, 
                               y: currentFrame.origin.y, 
                               width: 30, 
                               height: 5)
    }

    private func dismissWithAnimation() {
        UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn) {
            self.bgContainer.transform = CGAffineTransform(translationX: 0, y: self.view.frame.height)
            self.view.backgroundColor = .clear
        } completion: { _ in
            self.dismiss(animated: false)
        }
    }
    
    private func startLoading(){
        emptyImage.isHidden = true
        emptyLabel.isHidden = true
        progressMain.isHidden = false
        imageDownload.isHidden = true
        downshareContainer.isHidden = true
        progressContainerMain.backgroundColor = .clear
        progressMain.color = DefaultAppearance.shared.primaryColor
        progressMain.startAnimating()
    }
    
    private func stopLoading(){
        progressContainerMain.isHidden = true
    }
    

    private func setupUI() {
        view.backgroundColor = .clear
        
        let bgColor = DefaultAppearance.shared.cardColor
        
        downloadContainer.backgroundColor = bgColor
        shareContainer.backgroundColor = bgColor
        imageDownload.backgroundColor = bgColor

        // Initially hide content until data is loaded
        imageDownload.isHidden = true
        downshareContainer.isHidden = true

        getSharePref()
        
        B24PaymentSdkHelper.getCurrentLanguage(language: language)

        indicatorAppearance()
        setUpAppearance()
        setupTitleLabel()
        setupDownloadShare()
        setupGestureRecognizers()
    }
    
    // MARK: - Network Notification (Called by Parent)
    func handleConnectionChange(isConnected: Bool) {
        if isConnected && isWaitingForConnection {
            isWaitingForConnection = false
            
            // Reset UI state before refetching
            emptyImage.isHidden = true
            emptyLabel.isHidden = true
            progressMain.isHidden = false
            progressMain.startAnimating()
            
            B24PaymentSdkHelper.removePersistentSnackbar(from: self.view) {
                B24PaymentSdkHelper.successSnackbar(
                    view: self.view,
                    message: B24PaymentSdkHelper.localized(
                        SnackBarLocalizedKeys.connection_restored.rawValue
                    ),
                    forBottomSheet: false
                )
                // Retry fetching transaction details
                self.fetchTransactionDetails()
            }
        } else if !isConnected {
            // Connection lost - show persistent error
            if !isWaitingForConnection {
                isWaitingForConnection = true
                
                // Show offline UI
                progressMain.stopAnimating()
                progressMain.isHidden = true
                emptyImage.isHidden = false
                emptyLabel.isHidden = false
                
                emptyImage.image = UIImage(systemName: "wifi.exclamationmark")
                emptyImage.tintColor = DefaultAppearance.shared.warningColor
                emptyLabel.text = B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error_connect_server.rawValue)
                emptyLabel.textColor = DefaultAppearance.shared.primaryLabelColor
                emptyLabel.font = FontManager.shared.regularFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
                
                B24PaymentSdkHelper.persistentErrorSnackbar(
                    view: self.view,
                    message: B24PaymentSdkHelper.localized(
                        SnackBarLocalizedKeys.error_connect_server.rawValue
                    ),
                    forBottomSheet: false
                )
            }
        }
    }

    private func setupGestureRecognizers() {
        bgShareLogo.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(shareImage)))
        bgDownloadLogo.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(downloadImage)))
        bgShareLogo.isUserInteractionEnabled = true
        bgDownloadLogo.isUserInteractionEnabled = true
        
        
        tranIdValue.isUserInteractionEnabled = true
        tranIdValue.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(copyTransactionId)))
        
        referenceValue.isUserInteractionEnabled = true
        referenceValue.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(copyReference)))
        
        tranDateValue.isUserInteractionEnabled = true
        tranDateValue.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(copyTranDate)))
        
        // Add tap gesture to dismiss when tapping outside the main content
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleBackgroundTap(_:)))
        view.addGestureRecognizer(tapGesture)
        tapGesture.cancelsTouchesInView = false

        let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        pan.delegate = self
        bgContainer.addGestureRecognizer(pan)
        panGesture = pan
    }
    
    
    @objc func copyTransactionId(){
        UIPasteboard.general.string = tranIdValue.text
        let message = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.copy.rawValue) + " " +  (tranIdValue.text ?? "")
        B24PaymentSdkHelper.successSnackbar(view: self.view, message: message, forBottomSheet: false)
    }
    
    @objc func copyReference(){
        UIPasteboard.general.string = referenceValue.text
        let message = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.copy.rawValue) + " " +  (referenceValue.text ?? "")
        B24PaymentSdkHelper.successSnackbar(view: self.view, message: message, forBottomSheet: false)
    }
    
    @objc func copyTranDate(){
        UIPasteboard.general.string = tranDateValue.text
        let message = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.copy.rawValue) + " " +  (tranDateValue.text ?? "")
        B24PaymentSdkHelper.successSnackbar(view: self.view, message: message, forBottomSheet: false)
    }
    
    @objc private func handleBackgroundTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: view)
        
        // Check if the tap is outside the main content container
        if !bgContainer.frame.contains(location) {
            dismissWithAnimation()
        }
    }

    private func fetchTransactionDetails() {
        
    
        
      //  print("===============>\(tranID)")
        
//        AF.request(WalletRouter.transactionDetail(id: tranID))
//            .validate().responseDecodable(){
//                [self](response) in
//                switch response.result{
//                case .success(let data):
//                    do{
//                        let decodedData = try JSONDecoder().decode(ApiResponse<DataWalletTransactionDetail>.self, from: data)
//                        
//                       
//                        if(decodedData.code == "SUCCESS"){
//                            stopLoading()
//                            self.handleSuccessResponse(decodedData.data)
//                        }else{
//                            progressMain.stopAnimating()
//                            progressMain.isHidden = true
//                            
//                            emptyImage.image = UIImage(systemName: emptyIconName)
//                            emptyImage.tintColor = DefaultAppearance.shared.warningColor
//                            emptyLabel.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.emptyText.rawValue)
//                            emptyLabel.textColor = DefaultAppearance.shared.primaryLabelColor
//                            emptyLabel.font = FontManager.shared.regularFont(forLanguage: language ?? "km", size: FixFontSize.contentText)
//                            
//                            
//                            let message = language == "en" ? decodedData.message : decodedData.messageKh
//                            
//                            B24PaymentSdkHelper.errorSnackbar(view: view,
//                                                              message: message )
//                        }
//                    }catch{
//                        print("Decode Error: \(error)")
//                    }
//                    
//                case .failure(let error):
//                    progressMain.stopAnimating()
//                    progressMain.isHidden = true
//                    
//                    emptyImage.image = UIImage(systemName: emptyIconName)
//                    emptyImage.tintColor = DefaultAppearance.shared.warningColor
//                    emptyLabel.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.emptyText.rawValue)
//                    emptyLabel.textColor = DefaultAppearance.shared.primaryLabelColor
//                    emptyLabel.font = FontManager.shared.regularFont(forLanguage: language ?? "km", size: FixFontSize.contentText)
//                    
//                    B24PaymentSdkHelper.errorSnackbar(
//                                    view: view,
//                                    message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
//                                                        forBottomSheet: false
//                                                )
//                }
//            }
        
        
       // isLoading = true
        
        startLoading()

        let url = APIManager.merchantApiUrl().appendingPathComponent("instantpaymentsdk/payment_method/transaction_detail")
        let parameters: [String: Any] = ["tran_id": tranID]

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

            switch response.result {
            case .success(let responseModel):
                if responseModel.code == StatusCode.succcess.rawValue {
                    stopLoading()
                    self.handleSuccessResponse(responseModel.data)
                } else {
//                    self.showAlert(title: "Error", message: responseModel.message)
                    progressMain.stopAnimating()
                    progressMain.isHidden = true
                    emptyImage.isHidden = false
                    emptyLabel.isHidden = false
                    
                    emptyImage.image = UIImage(systemName: emptyIconName)
                    emptyImage.tintColor = DefaultAppearance.shared.warningColor
                    emptyLabel.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.emptyText.rawValue)
                    emptyLabel.textColor = DefaultAppearance.shared.primaryLabelColor
                    emptyLabel.font = FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
                    let message = (language?.lowercased() == "en") ? responseModel.message : responseModel.messageKh
                    
                    B24PaymentSdkHelper.errorSnackbar(view: view,
                                                                                  message: message )
                }
            case .failure(let error):
                
                print("error \(error)")
              //  self.showAlert(title: "Error", message: error.localizedDescription)
                progressMain.stopAnimating()
                progressMain.isHidden = true
                
                if !error.isSessionTaskError {
                    emptyImage.isHidden = false
                    emptyLabel.isHidden = false
                    emptyImage.image = UIImage(systemName: emptyIconName)
                    emptyImage.tintColor = DefaultAppearance.shared.warningColor
                    emptyLabel.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.emptyText.rawValue)
                    emptyLabel.textColor = DefaultAppearance.shared.primaryLabelColor
                    emptyLabel.font = FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
                    
                    B24PaymentSdkHelper.errorSnackbar(
                                                        view: view,
                                                        message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                                                                            forBottomSheet: false
                                                                    )
                }
            }
        }
    }

    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: view)
        let velocity = gesture.velocity(in: view)

        switch gesture.state {
        case .began:
            initialContainerY = bgContainer.frame.origin.y

        case .changed:
            // Only allow dragging DOWN
            if translation.y > 0 {
                bgContainer.frame.origin.y = initialContainerY + translation.y
            }

        case .ended, .cancelled:
            let dismissThreshold = bgContainer.frame.height * 0.25

            if translation.y > dismissThreshold || velocity.y > 1200 {
                dismissWithAnimation()
            } else {
                // Snap back
                UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseOut) {
                    self.bgContainer.frame.origin.y = self.initialContainerY
                }
            }

        default:
            break
        }
    }

    private func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }

    private func handleSuccessResponse(_ data: DataWalletTransactionDetail) {

        emptyImage.isHidden = true
        emptyLabel.isHidden = true
        imageDownload.isHidden = false
        downshareContainer.isHidden = false
        tranDetail = data
        setUpHeaderAppearance(detail: data)
        setUpContentAppearance(detail: data)

    }

    /// Converts proportional layout to content-driven sizing to eliminate excess white space at the bottom.
    /// All internal elements are proportionally sized to bgContainer, which guarantees ~31% empty space.
    /// This method captures the current computed sizes, deactivates proportional constraints,
    /// and replaces them with fixed values so the container wraps its content tightly.
    private func adjustContainerToFitContent() {
        // Force layout to get current computed sizes from the proportional layout
        view.layoutIfNeeded()

        // Capture current sizes before deactivating proportional constraints
        let contentHeight = imageDownload.frame.height
        let buttonsHeight = downshareContainer.frame.height
        let shareContHeight = shareContainer.frame.height
        let downloadBgH = bgDownloadLogo.frame.height
        let shareBgH = bgShareLogo.frame.height
        let dashH = max(dashLine.frame.height, 1)

        // 1. Deactivate container proportional height constraint (on view)
        for constraint in view.constraints {
            if let first = constraint.firstItem as? UIView, first === bgContainer,
               constraint.firstAttribute == .height,
               constraint.secondAttribute == .height {
                constraint.isActive = false
                break
            }
        }

        // 2. Deactivate all child height constraints proportional to bgContainer
        for constraint in bgContainer.constraints {
            if constraint.secondAttribute == .height,
               let second = constraint.secondItem as? UIView, second === bgContainer,
               constraint.firstAttribute == .height {
                constraint.isActive = false
            }
        }

        // 3. Calculate ideal container height based on actual content
        let topPadding: CGFloat = 10    // indicator top
        let indicatorH: CGFloat = 5     // indicator height (set by indicatorAppearance)
        let titleGap: CGFloat = 12      // gap below indicator to title
        let titleH: CGFloat = ceil(titleLabel.intrinsicContentSize.height) // title label height
        let titleBottom: CGFloat = 12   // gap below title to content
        let buttonsGap: CGFloat = 30    // gap between content and buttons
        let bottomPadding: CGFloat = 30 // padding below buttons

        let idealHeight = topPadding + indicatorH + titleGap + titleH + titleBottom
            + contentHeight + buttonsGap + buttonsHeight + bottomPadding

        // 4. Set fixed heights for all affected elements
        NSLayoutConstraint.activate([
            bgContainer.heightAnchor.constraint(equalToConstant: idealHeight),
            imageDownload.heightAnchor.constraint(equalToConstant: contentHeight),
            downshareContainer.heightAnchor.constraint(equalToConstant: buttonsHeight),
            shareContainer.heightAnchor.constraint(equalToConstant: shareContHeight),
            bgDownloadLogo.heightAnchor.constraint(equalToConstant: downloadBgH),
            bgShareLogo.heightAnchor.constraint(equalToConstant: shareBgH),
            dashLine.heightAnchor.constraint(equalToConstant: dashH),
        ])

        // 5. Animate the layout change
        UIView.animate(withDuration: 0.25) {
            self.view.layoutIfNeeded()
        }
    }

//    private func handleSuccessResponse(_ data: DataWalletTransactionDetail) {
//        self.tranDetail = data
//        setUpHeaderAppearance(detail: data)
//        setUpContentAppearance(detail: data)
//    }

    private func handleError(_ error: AFError) {
        let errorMessage = error.localizedDescription
        showError(message: errorMessage)
    }

    private func showError(message: String) {
        // Implement your error handling UI here
        let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }

    private func setupActivityIndicator() {
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(activityIndicator)
        NSLayoutConstraint.activate([
            activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }


    
    func getSharePref(){
        if let languageCode = SharedPreferenceManager.getString(forKey: SharePrefKey.lanuageCode.rawValue){
            language = languageCode
        }else{
            language = "km"
        }
    }
    
    
    func setUpHeaderAppearance(detail: DataWalletTransactionDetail) {
        bgLogo.layer.cornerRadius = bgLogo.frame.size.width / 2
        bgLogo.clipsToBounds = true
        if detail.tranType == TransactionType.walletTopup.rawValue {
            bgLogo.backgroundColor = DefaultAppearance.shared.successColor.withAlphaComponent(0.1)
            setLogoFill(false)
            logo.tintColor = nil

            let placeholder = UIImage(systemName: "arrow.down.backward")
            logo.loadImage(from: detail.logo, placeholder: placeholder) { [weak self] success in
                if success {
                    self?.setLogoFill(true)
                }
            }
        } else {
            bgLogo.backgroundColor = DefaultAppearance.shared.dangerColor.withAlphaComponent(0.1)
            setLogoFill(false)

            logo.image = UIImage(systemName: "arrow.up.left")
            logo.tintColor = DefaultAppearance.shared.dangerColor
        }

        amountLable.text = detail.totalAmountDisplay
        amountLable.font = FontManager.shared.boldFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        amountLable.numberOfLines = 0
        amountLable.lineBreakMode = .byWordWrapping
        amountLable.adjustsFontSizeToFitWidth = false
        amountLable.setContentCompressionResistancePriority(.required, for: .vertical)
        amountLable.setContentHuggingPriority(.required, for: .vertical)
        if detail.tranType == TransactionType.walletTopup.rawValue {
            amountLable.textColor = DefaultAppearance.shared.successColor
        } else {
            amountLable.textColor = DefaultAppearance.shared.dangerColor
        }

        if detail.tranType == TransactionType.walletTopup.rawValue {
            let descEn = (detail.descriptionEn ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
            let descKm = (detail.descriptionKm ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
            if language?.lowercased() == "en" {
                detailLabel.text = descEn.isEmpty ? B24PaymentSdkHelper.localized(TopupLocalizedKeys.topup.rawValue) : descEn
            } else {
                detailLabel.text = descKm.isEmpty ? B24PaymentSdkHelper.localized(TopupLocalizedKeys.topup.rawValue) : descKm
            }
        } else {
            detailLabel.text = (language?.lowercased() == "en") ? (detail.descriptionEn) : (detail.descriptionKm)
        }

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

        configureStatusBadge(status: detail.status)
    }

    private func setLogoFill(_ fill: Bool) {
        // Remove all existing constraints related to logo in bgLogo
        bgLogo.constraints.forEach { constraint in
            if constraint.firstItem === logo || constraint.secondItem === logo {
                bgLogo.removeConstraint(constraint)
            }
        }
        
        // Remove constraints on the logo itself
        logo.removeConstraints(logo.constraints)
        
        NSLayoutConstraint.deactivate(logoConstraints)
        logoConstraints.removeAll()
        
        logo.translatesAutoresizingMaskIntoConstraints = false
        
        if fill {
            logoConstraints = [
                logo.topAnchor.constraint(equalTo: bgLogo.topAnchor),
                logo.bottomAnchor.constraint(equalTo: bgLogo.bottomAnchor),
                logo.leadingAnchor.constraint(equalTo: bgLogo.leadingAnchor),
                logo.trailingAnchor.constraint(equalTo: bgLogo.trailingAnchor)
            ]
            logo.contentMode = .scaleAspectFill
        } else {
            logoConstraints = [
                logo.centerXAnchor.constraint(equalTo: bgLogo.centerXAnchor),
                logo.centerYAnchor.constraint(equalTo: bgLogo.centerYAnchor),
                logo.widthAnchor.constraint(equalTo: bgLogo.widthAnchor, multiplier: 0.4),
                logo.heightAnchor.constraint(equalTo: bgLogo.heightAnchor, multiplier: 0.4)
            ]
            logo.contentMode = .scaleAspectFit
        }
        
        NSLayoutConstraint.activate(logoConstraints)
        bgLogo.layoutIfNeeded()
    }

    func shareAction(){
        bgShareLogo.isUserInteractionEnabled = true
        let shareAction = UITapGestureRecognizer(target: self, action: #selector(shareImage))
        
        bgShareLogo.addGestureRecognizer(shareAction)
    }
    
    
    @objc func shareImage(){
        
        let image = imageDownload.saveAsImage() // Assuming saveAsImage() returns a UIImage
        
        let imageName = "image.png"
        // Get the URL for the documents directory
        if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            // Append the custom image name to the documents directory URL
            let fileURL = documentsDirectory.appendingPathComponent(imageName)
            
            // Save the image to the specified URL
            if let data = image.pngData() {
                do {
                    try data.write(to: fileURL)
                   // let items: [Any] = [image, imageName]
                    let items: [Any] = [fileURL]
                    // Now you can share the image using UIActivityViewController
                    let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
                    
                    // For iPads, you need to specify a source view and arrow direction for the popover
                    activityViewController.popoverPresentationController?.sourceView = self.view
                    activityViewController.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
                    // Present the activity view controller
                    self.present(activityViewController, animated: true, completion: nil)
                } catch {
                    print("Error saving image: \(error)")
                }
            }
        }
      
       
    }
    
    
    func downLoadAction(){
        bgDownloadLogo.isUserInteractionEnabled = true
        let downloadAction = UITapGestureRecognizer(target: self, action: #selector(downloadImage))
        
        bgDownloadLogo.addGestureRecognizer(downloadAction)
    }
    
    @objc func downloadImage(){
     let image =   imageDownload.saveAsImage()
      saveImageToPhotoLibrary(image: image)
        print("downLoad")
    }
    
    private func saveImageToPhotoLibrary(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            print(error)
            B24PaymentSdkHelper.errorSnackbar(
                view: view,
                message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                forBottomSheet: false
            )
        } else {
            B24PaymentSdkHelper.successSnackbar(
                view: view,
                message: B24PaymentSdkHelper.localized(AccountDetailLocalizedKeys.image_save.rawValue),
                forBottomSheet: false
            )
        }
    }
    
    
    
    func showHideInvoice(height:CGFloat,bottom:CGFloat,detail:DataWalletTransactionDetail){
        
        invoiceIdText.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.invoice_id.rawValue)
        invoiceIdText.font = FontManager.shared.regularFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish,size: FixFontSize.contentText)
        invoiceIdText.textColor = DefaultAppearance.shared.secondaryLabelColor
        
        invoiceIdValue.text = detail.invoiceId
        invoiceIdValue.font = FontManager.shared.boldFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        invoiceIdValue.textColor = DefaultAppearance.shared.primaryLabelColor
        
        
        invoiceIdHeightConstraint.isActive = false
        invoiceIdValueHeightConstraint.isActive = false
        if let existingConstraint = invoiceIdBottomSpace {
            existingConstraint.isActive = false
        }
        if let existingValueconstraint = invoiceValueBottomSpace{
            existingValueconstraint.isActive = false
        }
       
        
        
        // Set new values to the height constraints
        if let invoiceIdHeightConstraint = invoiceIdHeightConstraint {
            invoiceIdHeightConstraint.constant = height
        } else {
            let heightConstraint = NSLayoutConstraint(item: invoiceIdText!,
                                                      attribute: .height,
                                                      relatedBy: .equal,
                                                      toItem: nil,
                                                      attribute: .notAnAttribute,
                                                      multiplier: 1.0,
                                                      constant: height)
            invoiceIdText.addConstraint(heightConstraint)
            invoiceIdHeightConstraint = heightConstraint
            
            
        }
        
        if let invoiceIdValueHeightConstraint = invoiceIdValueHeightConstraint{
            invoiceIdValueHeightConstraint.constant = height
        }else{
            let heightConstraint = NSLayoutConstraint(item: invoiceIdValue!,
                                                      attribute: .height,
                                                      relatedBy: .equal,
                                                      toItem: nil,
                                                      attribute: .notAnAttribute,
                                                      multiplier: 1.0,
                                                      constant: height)
            invoiceIdValue.addConstraint(heightConstraint)
            invoiceIdValueHeightConstraint = heightConstraint
        }
        
        
        if let invoiceIdBottomSpace = invoiceIdBottomSpace {
            invoiceIdBottomSpace.constant = bottom
        } else {
            let bottomToTopConstraint = NSLayoutConstraint(
                item: invoiceIdText!, // Invoice Id
                attribute: .bottom,
                relatedBy: .equal,
                toItem: paidPayText, // Paid Pay Id
                attribute: .top,
                multiplier: 1.0,
                constant: bottom // Set spacing to 10
            )
            // Add the constraint to a common superview
            view.addConstraint(bottomToTopConstraint)
            invoiceIdBottomSpace = bottomToTopConstraint
        }

        // Handle Invoice Value Bottom Space Constraint
        if let invoiceValueBottomSpace = invoiceValueBottomSpace {
            invoiceValueBottomSpace.constant = bottom
        } else {
            let bottomToTopConstraint = NSLayoutConstraint(
                item: invoiceIdValue!, // Invoice Value
                attribute: .bottom,
                relatedBy: .equal,
                toItem: paidPayValue, // Paid Pay Value
                attribute: .top,
                multiplier: 1.0,
                constant: bottom // Set spacing to 10
            )
            // Add the constraint to a common superview
            view.addConstraint(bottomToTopConstraint)
            invoiceValueBottomSpace = bottomToTopConstraint
        }

        
        invoiceIdHeightConstraint.isActive = true
        invoiceIdValueHeightConstraint.isActive = true
        invoiceIdBottomSpace?.isActive = true
        invoiceValueBottomSpace?.isActive = true
    
        
    }
    
    
    
    func setUpContentAppearance(detail: DataWalletTransactionDetail) {
        tranIdLabel.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.tran_id.rawValue)
        tranIdLabel.font = FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        tranIdLabel.textColor = DefaultAppearance.shared.secondaryLabelColor

        tranIdValue.text = detail.tranNo
        tranIdValue.font = FontManager.shared.boldFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        tranIdValue.textColor = DefaultAppearance.shared.primaryLabelColor

//        invoiceIdText.isHidden = true
//        invoiceIdText.constraints.forEach { constraint in
//                if constraint.firstAttribute == .height {
//                    constraint.constant = 0
//                }
//            }
//        invoiceIdValue.isHidden = true
//        invoiceIdValue.constraints.forEach { constraint in
//                if constraint.firstAttribute == .height {
//                    constraint.constant = 0
//                }
//            }
//        
//        invoiceIdText.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.invoice_id.rawValue)
//        invoiceIdText.font = FontManager.shared.regularFont(forLanguage: language ?? "km", size: FixFontSize.contentText)
//        invoiceIdText.textColor = DefaultAppearance.shared.secondaryLabelColor
//
//        invoiceIdValue.text = detail.refNo
//        invoiceIdValue.font = FontManager.shared.regularFont(forLanguage: language ?? "km", size: FixFontSize.contentText)
//        invoiceIdValue.textColor = DefaultAppearance.shared.secondaryLabelColor

        if detail.tranType == TransactionType.walletTopup.rawValue {
            paidPayText.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.payment_from.rawValue)
            paidPayValue.text = detail.paymentFrom
            
           
            //hide invoice id
            showHideInvoice(height: 0,bottom:0,detail: detail)
            
        } else {
            
            showHideInvoice(height: 21,bottom:-10,detail: detail)
            
            paidPayText.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.paid_to.rawValue)
            paidPayValue.text = detail.paidTo
        }

        paidPayText.font = FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        paidPayText.textColor = DefaultAppearance.shared.secondaryLabelColor

        paidPayValue.font = FontManager.shared.boldFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        paidPayValue.textColor = DefaultAppearance.shared.primaryLabelColor

        originalAmountText.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.origial_amount.rawValue)
        originalAmountText.font = FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        originalAmountText.textColor = DefaultAppearance.shared.secondaryLabelColor

        originalAmountValue.text = detail.originalAmountDisplay
        originalAmountValue.font = FontManager.shared.boldFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        originalAmountValue.textColor = DefaultAppearance.shared.primaryLabelColor

        feeText.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.fee_amount.rawValue)
        feeText.font = FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        feeText.textColor = DefaultAppearance.shared.secondaryLabelColor

        feeValue.text = detail.feeDisplay
        feeValue.font = FontManager.shared.boldFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        feeValue.textColor = DefaultAppearance.shared.primaryLabelColor

        referenceText.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.reference.rawValue)
        referenceText.font = FontManager.shared.regularFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish,size: FixFontSize.contentText)
        referenceText.textColor = DefaultAppearance.shared.secondaryLabelColor

        referenceValue.text = detail.refNo
        referenceValue.font = FontManager.shared.boldFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        referenceValue.textColor = DefaultAppearance.shared.primaryLabelColor

        tranDateText.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.tran_date.rawValue)
        tranDateText.font = FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        tranDateText.textColor = DefaultAppearance.shared.secondaryLabelColor

        tranDateValue.text = B24PaymentSdkHelper.formatTransactionDate(detail.tranDate)
        tranDateValue.font = FontManager.shared.boldFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        tranDateValue.textColor = DefaultAppearance.shared.primaryLabelColor
    }

    private func setupTitleLabel() {
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.text = B24PaymentSdkHelper.localized(TransactionDetailLocalizedKeys.tran_detail_title.rawValue)
        titleLabel.font = FontManager.shared.boldFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.toolbarTitle)
        titleLabel.textColor = DefaultAppearance.shared.primaryLabelColor
        titleLabel.textAlignment = .left
        bgContainer.addSubview(titleLabel)
        NSLayoutConstraint.activate([
            titleLabel.topAnchor.constraint(equalTo: indicator.bottomAnchor, constant: 12),
            titleLabel.leadingAnchor.constraint(equalTo: bgContainer.leadingAnchor, constant: 20),
            titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: bgContainer.trailingAnchor, constant: -20),
        ])
    }

    private func configureStatusBadge(status: String?) {
        guard let status = status, !status.isEmpty else {
            statusBadgeLabel.isHidden = true
            return
        }

        let normalizedStatus = status.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let statusColor: UIColor
        switch normalizedStatus {
        case "processing":
            statusColor = UIColor(hex: "#F5A623")
        default:
            statusColor = UIColor(hex: "#17A865")
        }

        let localizedStatus = localizedStatusText(for: status)

        statusBadgeLabel.translatesAutoresizingMaskIntoConstraints = false
        statusBadgeLabel.text = "\u{25CF} \(localizedStatus)"
        statusBadgeLabel.font = FontManager.shared.regularFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.tranTypeText)
        statusBadgeLabel.textColor = statusColor
        statusBadgeLabel.backgroundColor = statusColor.withAlphaComponent(0.2)
        statusBadgeLabel.textAlignment = .center
        statusBadgeLabel.clipsToBounds = true
        statusBadgeLabel.isHidden = false
        statusBadgeLabel.padding = UIEdgeInsets(top: 4, left: 10, bottom: 4, right: 10)
        statusBadgeLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        statusBadgeLabel.setContentHuggingPriority(.required, for: .horizontal)

        if statusBadgeLabel.superview == nil {
            imageDownload.addSubview(statusBadgeLabel)
            NSLayoutConstraint.activate([
                statusBadgeLabel.centerYAnchor.constraint(equalTo: detailLabel.centerYAnchor),
                statusBadgeLabel.leadingAnchor.constraint(equalTo: detailLabel.trailingAnchor, constant: 8),
            ])
        }

        DispatchQueue.main.async {
            self.statusBadgeLabel.layoutIfNeeded()
            self.statusBadgeLabel.layer.cornerRadius = self.statusBadgeLabel.frame.height / 2
        }
    }

    private func localizedStatusText(for status: String) -> String {
        let normalizedStatus = status.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()

        let localizationKey: String?
        switch normalizedStatus {
        case "success":
            localizationKey = TransactionDetailLocalizedKeys.status_success.rawValue
        case "processing":
            localizationKey = TransactionDetailLocalizedKeys.status_processing.rawValue
        default:
            localizationKey = nil
        }

        guard let localizationKey else {
            return status.prefix(1).uppercased() + status.dropFirst().lowercased()
        }

        let localizedValue = B24PaymentSdkHelper.localized(localizationKey)
        if localizedValue == localizationKey {
            return status.prefix(1).uppercased() + status.dropFirst().lowercased()
        }
        return localizedValue
    }

    func indicatorAppearance(){
        indicator.backgroundColor = SDKVariableSetting.isDarkMode == true ? UIColor(hex:SDKVariableSetting.indicatorDark) :UIColor(hex:SDKVariableSetting.indicatorLight)
        indicator.layer.cornerRadius = 4
        
        // Remove existing constraints first
        indicator.translatesAutoresizingMaskIntoConstraints = false
        
        // Remove any existing width/height constraints from both the view and its superview
        indicator.constraints.forEach { constraint in
            if constraint.firstAttribute == .width || constraint.firstAttribute == .height {
                constraint.isActive = false
            }
        }
        
        indicator.superview?.constraints.forEach { constraint in
            if (constraint.firstItem as? UIView) == indicator && 
               (constraint.firstAttribute == .width || constraint.firstAttribute == .height) {
                constraint.isActive = false
            }
        }
        
        // Set both width and height constraints for the indicator with high priority
        let widthConstraint = indicator.widthAnchor.constraint(equalToConstant: 40)
        widthConstraint.priority = UILayoutPriority(999)
        widthConstraint.isActive = true
        
        let heightConstraint = indicator.heightAnchor.constraint(equalToConstant: 5)
        heightConstraint.priority = UILayoutPriority(999)
        heightConstraint.isActive = true
        
        // Backup: Also set frame directly
        DispatchQueue.main.async {
            let currentFrame = self.indicator.frame
            self.indicator.frame = CGRect(x: currentFrame.origin.x, 
                                        y: currentFrame.origin.y, 
                                        width: 40, 
                                        height: 5)
            
        }
        
        line.backgroundColor = DefaultAppearance.shared.primaryLabelColor.withAlphaComponent(0.3)

        dashLine.isHidden = true

        
    }
    
    func setUpAppearance(){
        bgContainer.backgroundColor = DefaultAppearance.shared.cardColor
        
        // Match KHQRView corners and shadow
        bgContainer.layer.cornerRadius = 30
        bgContainer.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        bgContainer.layer.shadowColor = UIColor.black.cgColor
        bgContainer.layer.shadowOffset = CGSize(width: 0, height: 0)
        bgContainer.layer.shadowOpacity = 0.10
        bgContainer.layer.shadowRadius = 8
        bgContainer.layer.masksToBounds = false
    }
    
    
    func setupDownloadShare(){
        downshareContainer.backgroundColor = DefaultAppearance.shared.cardColor
        downloadText.text = B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.save_button.rawValue)
        downloadText.font = FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.tranTypeText)
        downloadText.textColor = DefaultAppearance.shared.secondaryLabelColor
        
        shareText.text = B24PaymentSdkHelper.localized(LocalizedKeys.share.rawValue)
        shareText.font = FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.tranTypeText)
        shareText.textColor = DefaultAppearance.shared.secondaryLabelColor
        
        //logo
        
        bgDownloadLogo.backgroundColor = DefaultAppearance.shared.primaryColor.withAlphaComponent(0.4)
        bgDownloadLogo.layer.cornerRadius = 6
        downloadLogo.tintColor = DefaultAppearance.shared.primaryColor
        
        bgShareLogo.backgroundColor = DefaultAppearance.shared.primaryColor.withAlphaComponent(0.4)
        bgShareLogo.layer.cornerRadius = 6
        shareLogo.tintColor = DefaultAppearance.shared.primaryColor

        // Update button icon containers to 48pt
        for container in [bgDownloadLogo, bgShareLogo] {
            guard let container = container else { continue }
            for constraint in container.superview?.constraints ?? [] {
                if let first = constraint.firstItem as? UIView, first === container,
                   constraint.firstAttribute == .height || constraint.firstAttribute == .width {
                    constraint.constant = 48
                }
            }
            for constraint in container.constraints {
                if constraint.firstAttribute == .height || constraint.firstAttribute == .width {
                    constraint.constant = 48
                }
            }
        }
    }
        
    
}


class LoadingIndicatorManager {
    static let shared = LoadingIndicatorManager()
    private var containerView: UIView?
    private let activityIndicator = UIActivityIndicatorView(style: .large)

    private init() {}

    func showLoading(in view: UIView) {
        // Remove any existing loading indicator
        hideLoading()

        // Create semi-transparent container
        let container = UIView()
        container.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        container.translatesAutoresizingMaskIntoConstraints = false

        // Configure activity indicator
        activityIndicator.color = .white
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false

        // Add views to hierarchy
        view.addSubview(container)
        container.addSubview(activityIndicator)

        // Setup constraints
        NSLayoutConstraint.activate([
            container.topAnchor.constraint(equalTo: view.topAnchor),
            container.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            container.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            container.bottomAnchor.constraint(equalTo: view.bottomAnchor),

            activityIndicator.centerXAnchor.constraint(equalTo: container.centerXAnchor),
            activityIndicator.centerYAnchor.constraint(equalTo: container.centerYAnchor)
        ])

        containerView = container
        activityIndicator.startAnimating()
    }

    func hideLoading() {
        activityIndicator.stopAnimating()
        containerView?.removeFromSuperview()
        containerView = nil
    }
}

extension TransactionDetailView: UIGestureRecognizerDelegate {
    func gestureRecognizer(
        _ gestureRecognizer: UIGestureRecognizer,
        shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
    ) -> Bool {
        return true
    }
}

class PaddedLabel: UILabel {
    var padding = UIEdgeInsets(top: 4, left: 10, bottom: 4, right: 10)

    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: padding))
    }

    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(width: size.width + padding.left + padding.right,
                      height: size.height + padding.top + padding.bottom)
    }
}
