//
//  ExpireView.swift
//  Bill24OnlinePaymentSdk
//
//  Created by MacbookPro on 23/10/23.
//

import Foundation
import UIKit
import Alamofire

public class ExpireView: UIView {
    
    @IBOutlet weak var expireTitlteLabel: UILabel!
    @IBOutlet weak var retryButton: UIButton!
    
    var controller: UIViewController!
    var transactionId: String = ""
    var transactionData: Transaction?
    private var bottomSheetController: BottomSheetViewController?

    private var isWaitingForConnection: Bool = false
    private var dismissButton: UIButton!
    private var backButton: UIButton!
    private var expireMainView: UIView!
    
    @IBOutlet weak var dotLineView: DottedLineView!
    @IBOutlet weak var expireContent: UILabel!
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initSubviews()
    }
    
    init(frame: CGRect, transactionId: String, controller: UIViewController, transactionData: Transaction, bottomSheetController: BottomSheetViewController) {
        self.transactionData = transactionData
        self.transactionId = transactionId
        self.controller = controller
        self.bottomSheetController = bottomSheetController
        super.init(frame: frame)
        initSubviews()
    }
    
    private func initSubviews() {
        registerView()
        setUpStyle()
        setUpFont()
        setUpThemes()
        setUpTranslate()
        setupDismissButton()
        setupBackButton()
    }
    
    private func setUpThemes() {
        expireTitlteLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        expireContent.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        dotLineView.tintColor = UIColor(hex: Themes.Property.indicatorColor)
        retryButton.backgroundColor = UIColor(hex: Themes.Property.buttonBackgroundColor)
        retryButton.tintColor = UIColor(hex: Themes.Property.buttonTextColor)
        retryButton.titleLabel?.textColor = UIColor(hex: Themes.Property.buttonTextColor)
        if dismissButton != nil {
            applyDismissButtonTheme()
        }
        if backButton != nil {
            applyNavigationButtonTheme(backButton)
        }
    }
    
    private func setUpFont() {
        expireTitlteLabel.numberOfLines = 0
        expireContent.numberOfLines = 0
        expireContent.font = FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 16.0)
        expireTitlteLabel.font = FontManager.shared.boldFont(forLanguage: SDKVariableSetting.currentLanguage, size: 18.0)
        retryButton.titleLabel?.font = FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 14.0)
    }
    
    private func setUpTranslate() {
        retryButton.setTitle(B24PaymentSdkHelper.localized(ExpireLocalizedKeys.button.rawValue), for: .normal)
        expireTitlteLabel.text = B24PaymentSdkHelper.localized(ExpireLocalizedKeys.title.rawValue)
        expireContent.text = B24PaymentSdkHelper.localized(ExpireLocalizedKeys.description.rawValue)
    }
    
    @IBAction func onClickRetryButton(_ sender: Any) {
        requestVeriftyTransaction()
    }
    
    private func registerView() {
        let nib = UINib(
            nibName: "ExpireView",
            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]
        expireMainView = view
        addSubview(view)
        print("*** Load Expire View ***")
        view.backgroundColor = UIColor(hex: Themes.Property.secondaryBackgroundColor)
    }

    // 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)
            }
        }
    }

    @objc private func retryAction() {
        B24PaymentSdkHelper.hideNoInternetPopup(from: self.controller)
        requestVeriftyTransaction()
    }

    private func setupDismissButton() {
        // Create dismiss button
        dismissButton = UIButton(type: .system)
        let config = UIImage.SymbolConfiguration(pointSize: 14, weight: .bold)
        dismissButton.setImage(UIImage(systemName: "xmark", withConfiguration: config), for: .normal)
        dismissButton.layer.cornerRadius = 14
        dismissButton.layer.borderWidth = 1
        dismissButton.clipsToBounds = true
        dismissButton.translatesAutoresizingMaskIntoConstraints = false
        dismissButton.addTarget(self, action: #selector(dismissBottomSheet), for: .touchUpInside)
        
        // Add button to the main view
        expireMainView.addSubview(dismissButton)
        
        // Set up constraints
        NSLayoutConstraint.activate([
            dismissButton.topAnchor.constraint(equalTo: expireMainView.topAnchor, constant: 5),
            dismissButton.trailingAnchor.constraint(equalTo: expireMainView.trailingAnchor, constant: -14),
            dismissButton.widthAnchor.constraint(equalToConstant: 28),
            dismissButton.heightAnchor.constraint(equalToConstant: 28)
        ])

        applyDismissButtonTheme()
    }

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

        dismissButton.backgroundColor = backgroundColor
        dismissButton.layer.borderColor = borderColor.cgColor
        dismissButton.tintColor = UIColor(hex: Themes.Property.labelTextColor)
    }

    private func setupBackButton() {
        backButton = UIButton(type: .system)
        let config = UIImage.SymbolConfiguration(pointSize: 12, weight: .bold)
        backButton.setImage(UIImage(systemName: "chevron.backward", withConfiguration: config), for: .normal)
        backButton.layer.cornerRadius = 14
        backButton.layer.borderWidth = 1
        backButton.clipsToBounds = true
        backButton.translatesAutoresizingMaskIntoConstraints = false
        backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside)

        expireMainView.addSubview(backButton)

        NSLayoutConstraint.activate([
            backButton.topAnchor.constraint(equalTo: expireMainView.topAnchor, constant: 5),
            backButton.leadingAnchor.constraint(equalTo: expireMainView.leadingAnchor, constant: 14),
            backButton.widthAnchor.constraint(equalToConstant: 28),
            backButton.heightAnchor.constraint(equalToConstant: 28)
        ])

        applyNavigationButtonTheme(backButton)
    }

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

        button.backgroundColor = backgroundColor
        button.layer.borderColor = borderColor.cgColor
        button.tintColor = UIColor(hex: Themes.Property.labelTextColor)
    }
    
    @objc private func dismissBottomSheet() {
        bottomSheetController?.dismissBottomSheet()
    }

    @objc private func backAction() {
        guard let bottomSheet = bottomSheetController else { return }

        removeFromSuperview()

        let paymentView = PaymentMethodView(
            frame: controller.view.frame,
            controller: controller,
            transactionId: transactionId,
            bottomSheetController: bottomSheet,
            transaction: transactionData
        )

        bottomSheet.bottomSheetContainerView.addSubview(paymentView)
        bottomSheet.notifyStationaryViewAdded()
        bottomSheet.viewType = .ninetyPercent

        UIView.animate(withDuration: 0.3) {
            bottomSheet.updateViewConstraints()
            bottomSheet.view.layoutIfNeeded()
        }
    }
    
    private func retryVerify() {
        requestVeriftyTransaction()
    }
    
    private func setUpStyle() {
        retryButton.layer.cornerRadius = 10
    }
    
    // Removed SharedPreference approach - now using TopUpView.isTopUpTransaction static variable
    private func requestVeriftyTransaction() {
        // Show progress indicator on button
        showLoadingOnButton(true)

        // Check Network Connection
        guard NetworkMonitor.shared.isConnected else {
            // Reset loading state
            showLoadingOnButton(false)
            
            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
                    NetworkMonitor.shared.stopMonitoring()
                }
            }
            return
        }
        
        AF.request(CheckoutRouter.checkoutDetail(transactionId: transactionId)).validate().responseData { [weak self] response in
            guard let self = self else { return }
            
            // Hide progress indicator
            self.showLoadingOnButton(false)
            
            switch response.result {
            case .success(let data):
                let transaction = try? JSONDecoder().decode(Transaction.self, from: data)
                
                if transaction?.code == "SUCCESS" {
                    let newTransactionId = transaction?.data?.transInfo.tranNo ?? self.transactionId
                    
                    if transaction?.data?.transInfo.status == "success" {
                        let displayDefaultSuccessPage = transaction?.data?.checkoutPageConfig.displaySuccessPage
                        let merchantDeeplink = transaction?.data?.transInfo.redirectURL
                        
                        // Use TopUpView's static flag instead of SharedPreference
                        // open success of wallet
                        
                        if TopUpView.isTopUpTransaction {
                            // Reset the flag
                            TopUpView.isTopUpTransaction = false
                            
                            let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
                            
                            if let walletVC = storyboard.instantiateViewController(withIdentifier: "WalletSuccessViewController") as? WalletSuccessViewController {
                                // Dismiss the bottom sheet first
                                self.controller.dismiss(animated: true) {
                                    // Present the wallet success view controller modally (no back button)
                                    walletVC.modalPresentationStyle = .fullScreen
                                    self.controller.present(walletVC, animated: true)
                                }
                            }
                        }
                        // open success deeplink
                        else if displayDefaultSuccessPage == true {
                            // check to open success in wallet
                            let storyboard = UIStoryboard(name: "SuccessScreenViewController", bundle: B24PaymentSdkHelper.frameworkBundle())
                            let vc = storyboard.instantiateViewController(withIdentifier: "SuccessScreenViewController") as! SuccessScreenViewController
                            vc.transactionSuccess = transaction
                            vc.presentingVC = self.controller
                            vc.modalPresentationStyle = .fullScreen
                            self.controller.present(vc, animated: true)
                        } else {
                            if(merchantDeeplink != ""){
                                self.controller.dismiss(animated: true) {
                                    B24PaymentSdkHelper.openDeeplink(deepLinkUrl: merchantDeeplink ?? "", view: self.controller.view)
                                }
                            }
                            
                        }
                    } else {
                        // Status is not "success", open KHQRView
                        self.openKHQRView(transactionId: newTransactionId, transactionData: transaction)
                    }
                } else {
                    // let lan = SDKVariableSetting.currentLanguage?.lowercased() ?? "km"
                    let message = SDKVariableSetting.currentLanguage.lowercased() == "en" ? transaction?.message : transaction?.messageKh
                    
                    // Show snackbar on the superview (bottomSheetContainerView) to ensure visibility
                    if let parentView = self.superview {
                        B24PaymentSdkHelper.errorSnackbar(
                            view: parentView,
                            message: message ?? B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                            forBottomSheet: false
                        )
                    }
                }
                
            case .failure(let error):
                print("*** ERROR========> \(error) ***")
                self.showLoadingOnButton(false) // Ensure loading is hidden on failure
                
                if error.isSessionTaskError {
                    if !self.isWaitingForConnection {
                        self.isWaitingForConnection = true
                        self.setupNetworkMonitoring()
                        NetworkMonitor.shared.startMonitoring()
                        
                        B24PaymentSdkHelper.showNoInternetPopup(on: self.controller) { [weak self] in
                            guard let self = self else { return }
                            self.isWaitingForConnection = false
                            NetworkMonitor.shared.stopMonitoring()
                        }
                    }
                } else {
                    // Show snackbar on the superview (bottomSheetContainerView) to ensure visibility
                    if let parentView = self.superview {
                        B24PaymentSdkHelper.errorSnackbar(
                            view: parentView,
                            message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                            forBottomSheet: false
                        )
                    }
                }
            }
        }
    }
    
    private func openKHQRView(transactionId: String, transactionData: Transaction?) {
        B24PaymentSdkHelper.navigationToNextBottomSheet(from: controller) { [self] in
            let b24PaymentSdkHelper = B24PaymentSdkHelper()
            let khqrView = KHQRView(
                frame: controller.view.frame,
                transactionId: transactionId,
                controller: controller,
                transactionData: transactionData!,
                bottomSheetController: b24PaymentSdkHelper.vc
            )
            b24PaymentSdkHelper.presentBottomSheet(
                from: controller,
                view: khqrView,
                viewType: .sixtyPercent,
                transactionId: transactionId,
                completed: {
                    khqrView.completed()
                }
            )
        }
    }
    
    // Store the original button image
    private var originalButtonImage: UIImage?
    
    private func showLoadingOnButton(_ show: Bool) {
        retryButton.isEnabled = !show
        
        if show {
            // Save and remove the current image
            if let currentImage = retryButton.image(for: .normal) {
                originalButtonImage = currentImage
                retryButton.setImage(nil, for: .normal)
            }
            
            // Create and add activity indicator
            let activityIndicator = UIActivityIndicatorView(style: .medium)
            activityIndicator.tag = 999 // Tag to identify and remove later
            activityIndicator.color = UIColor(hex: Themes.Property.buttonTextColor)
            activityIndicator.translatesAutoresizingMaskIntoConstraints = false
            retryButton.addSubview(activityIndicator)
            
            NSLayoutConstraint.activate([
                activityIndicator.centerXAnchor.constraint(equalTo: retryButton.centerXAnchor),
                activityIndicator.centerYAnchor.constraint(equalTo: retryButton.centerYAnchor)
            ])
            
            activityIndicator.startAnimating()
            retryButton.titleLabel?.alpha = 0
        } else {
            // Remove activity indicator
            if let activityIndicator = retryButton.viewWithTag(999) as? UIActivityIndicatorView {
                activityIndicator.stopAnimating()
                activityIndicator.removeFromSuperview()
            }
            
            // Restore the original image
            if let savedImage = originalButtonImage {
                retryButton.setImage(savedImage, for: .normal)
                originalButtonImage = nil
            }
            
            retryButton.titleLabel?.alpha = 1
        }
    }

    public override func removeFromSuperview() {
        super.removeFromSuperview()
        B24PaymentSdkHelper.hideNoInternetPopup(from: self.controller, showSuccess: false)
        NetworkMonitor.shared.stopMonitoring()
        NetworkMonitor.shared.onConnectionStatusChanged = nil
        isWaitingForConnection = false
    }
}
