//
//  InstantPMView.swift
//  B24PaymentSdk
//
//  Created by visal ny on 28/12/24.
//

import UIKit
import Alamofire

class InstantPMView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
   
    @IBOutlet weak var toolbarLine: UIView!
    
    @IBOutlet weak var pmCollectionView: UICollectionView!
    @IBOutlet weak var addButton: UIButton!
    
    @IBOutlet weak var textEmpty: UILabel!
    var paymentMethodList:[PaymentMethodModel] = [
        
    ]
    var language:String = "km"
    var customerSynCode:String = ""
    var disableFloatButton:Bool=false
    let activityIndicator = UIActivityIndicatorView(style: .large)
    
    private let refreshControl = UIRefreshControl() // Step 1

    // MARK: - Network Monitoring
    private var isWaitingForConnection: Bool = false

    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = DefaultAppearance.shared.screenBgColor
        // Hide custom line to use system separator for consistency
        toolbarLine.isHidden = true
        textEmpty.isHidden = true
        
        view.accessibilityIdentifier = "instantPMView"
        pmCollectionView.accessibilityIdentifier = "pmCollectionView"
        addButton.accessibilityIdentifier = "addPaymentMethodButton"

        getSharePref()

        B24PaymentSdkHelper.getCurrentLanguage(language: language)
        
        applyToolBar()
            
        
        //get current language
        B24PaymentSdkHelper.getCurrentLanguage(language: language)
        //fetchAvailablePMType(customerSyncCode: customerSynCode)
        
        setupButton()
        
        setUpCollectionView()
        setupRefreshControl() // Step 2
        fetchPaymentMethods()
        fetchAvailablePMType(customerSyncCode: customerSynCode)

        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupNetworkMonitoring()
        NetworkMonitor.shared.startMonitoring()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NetworkMonitor.shared.stopMonitoring()
        NetworkMonitor.shared.onConnectionStatusChanged = nil
        isWaitingForConnection = false
    }

    // 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)
                // Auto-refresh payment methods when connection is restored
                self.fetchPaymentMethods()
                self.fetchAvailablePMType(customerSyncCode: self.customerSynCode)
            }
        }
    }
    
    func dismissAll(){
        var presentingVC = presentingViewController
        while let parent = presentingVC?.presentingViewController {
            presentingVC = parent
        }
        presentingVC?.dismiss(animated: true) {
            print("Dismissal completed")
        }
    }
    
    
    // Back button action
    @objc func backButtonTapped() {
      // self.dismiss(animated: true)
        self.dismissAll()
    
    }
    
    func startLoading() {
        activityIndicator.center = view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.color = UIColor.systemBlue
        view.addSubview(activityIndicator)
        activityIndicator.startAnimating()
    }
    
    func stopLoading() {
        activityIndicator.stopAnimating()
        activityIndicator.isHidden = true
    }
    
    private func getSharePref(){
        if let languageCode = SharedPreferenceManager.getString(forKey: SharePrefKey.lanuageCode.rawValue){
            language = languageCode
        }else{
            language = "km"
        }
        
        if let userSyncode = SharedPreferenceManager.getString(forKey: SharePrefKey.customerSyncode.rawValue){
            customerSynCode = userSyncode
        }else{
             customerSynCode = ""
        }
        
        disableFloatButton = SharedPreferenceManager.getBool(forKey: SharePrefKey.disableFloatButton.rawValue)
           
        
    }
    
    
    private func setupButton(){
           
            addButton.setTitle("", for:.normal)
            addButton.tintColor = DefaultAppearance.shared.primaryColor
            addButton.frame.size = CGSize(width: 56, height: 56) // Example size
            addButton.layer.cornerRadius = addButton.frame.size.width / 2
            addButton.clipsToBounds = true
            addButton.layer.shadowColor = UIColor.black.cgColor
            addButton.layer.shadowOffset = CGSize(width: 0, height: 2)
            addButton.layer.shadowRadius = 4
            addButton.layer.shadowOpacity = 0.2

//        let plusConfig = UIImage.SymbolConfiguration(pointSize: 20, weight: .medium)
//        addButton.setImage(UIImage(systemName: "plus", withConfiguration: plusConfig)?.withTintColor(DefaultAppearance.shared.onPrimaryColor), for: .normal)
        let plusConfig = UIImage.SymbolConfiguration(pointSize: 20, weight: .medium)
        let plusImage = UIImage(systemName: "plus", withConfiguration: plusConfig)?
            .withTintColor(DefaultAppearance.shared.onPrimaryColor, renderingMode: .alwaysOriginal) // Force original rendering
        addButton.setImage(plusImage, for: .normal)
        
        if(disableFloatButton){
            addButton.isHidden=true
        }
    }
    
    private func setupRefreshControl() {
        refreshControl.tintColor = DefaultAppearance.shared.primaryColor
        refreshControl.addTarget(self, action: #selector(refreshPaymentMethods), for: .valueChanged)
        pmCollectionView.refreshControl = refreshControl // Step 3
    }
    
    private func fetchPaymentMethods() {
        
        if !refreshControl.isRefreshing{
            startLoading()
        }
        
       
        AF.request(WalletRouter.instantPaymentMethod(customerSynCode: customerSynCode, filterBy: " "))
            .validate().responseData{
                [self](response) in
                
                self.refreshControl.endRefreshing()
                
                switch response.result{
                case .success(let data):
                    
                    stopLoading()
                    
                    do{
                        let decodeData = try JSONDecoder().decode(ApiResponse<InstantPaymentMethodsResponse>.self,from: data)
                        
                        
                        if decodeData.code == StatusCode.succcess.rawValue{
                            
                            if decodeData.data.paymentMethods?.count == 0{
                                
                                textEmpty.isHidden = false
                                textEmpty.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.empty.rawValue)
                                textEmpty.font = FontManager.shared.regularFont(forLanguage: language,fontFromconfig:DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
                                textEmpty.textColor = DefaultAppearance.shared.primaryLabelColor
                            }else{
                                textEmpty.isHidden = true
                                self.paymentMethodList = decodeData.data.paymentMethods!
                                self.pmCollectionView.reloadData()
                            }
                            
                           
                        }else{
                            
                            textEmpty.isHidden = false
                            textEmpty.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.empty.rawValue)
                            textEmpty.font = FontManager.shared.regularFont(forLanguage: language,fontFromconfig:DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
                            textEmpty.textColor = DefaultAppearance.shared.primaryLabelColor
                
                            let message = language == "en" ? decodeData.message : decodeData.messageKh
                            
                            B24PaymentSdkHelper.errorSnackbar(view: view,
                                                              message: message )
                           
                        }
                        
                        
                    }catch{
                        print("Decode Error: \(error)")
                    }
                    
                case .failure(let error):
                    
                    print("error \(error)")
                    
                    textEmpty.isHidden = false
                    textEmpty.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.empty.rawValue)
                    textEmpty.font = FontManager.shared.regularFont(forLanguage: language,fontFromconfig:DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
                    textEmpty.textColor = DefaultAppearance.shared.primaryLabelColor
        
                    B24PaymentSdkHelper.errorSnackbar(
                                    view: view,
                                    message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                                                        forBottomSheet: false
                                                    )
                    stopLoading()
        
                    }
                }
            }
    @objc private func refreshPaymentMethods() { // Step 5
            fetchPaymentMethods()
    }
        
        
//        let url = APIManager.merchantApiUrl().appendingPathComponent("instantpaymentsdk/instant_payment_methods")
//        let parameters: [String: Any] = [
//            "customer_sync_code": "C001",
//            "filter_by_status": "active"
//        ]
//
//        AF.request(
//            url,
//            method: .post,
//            parameters: parameters,
//            encoding: JSONEncoding.default,
//            headers: APIManager.initHeader()
//        ).responseData { [weak self] response in
//            guard let self = self else { return }
//
//            self.refreshControl.endRefreshing() // Step 4
//            switch response.result {
//            case .success(let data):
//                do {
//                    let decoder = JSONDecoder()
//                    let apiResponse = try decoder.decode(ApiResponse<InstantPaymentMethodsResponse>.self, from: data)
//
//                    if apiResponse.code == "SUCCESS" {
//                        self.paymentMethodList = apiResponse.data.paymentMethods
//                            .sorted { $0.isActive && !$1.isActive }
//                        self.pmCollectionView.reloadData()
//                    } else {
//                        
//                    }
//                } catch {
//                   
//                }
//            case .failure(let error):
//                print("ERROR \(error)")
//            }
//        }
  //  }
    
    func fetchAvailablePMType(customerSyncCode:String){
           
            
            AF.request(WalletRouter.getAvailablePMType(customerSyncCode: customerSyncCode)).validate().responseData{
                response in
                
                switch response.result {
                case .success(let data):
                    do {
                        // Decode the response data
                        let decodedData = try JSONDecoder().decode(AvailablePMTypeResponseModel.self, from: data)
                        
                        SharedPreferenceManager.set(value: false, forKey: SharePrefKey.isWalletTopup.rawValue)
                        
                        if(decodedData.data.availablePaymentMethodTypes.isEmpty || decodedData.data.availablePaymentMethodTypes.count==0){
                            
                            self.disableFloatButton=true
                            
                            //SharedPreferenceManager.set(value: true, forKey: SharePrefKey.disableFloatButton.rawValue)
                        }else{
                            //SharedPreferenceManager.set(value: false, forKey: SharePrefKey.disableFloatButton.rawValue)
                            self.disableFloatButton=false
                        }
                        
                        
                        ///
                        self.setupButton()
                    
                       
                        
                        print("Success: \(decodedData)")
                                    // Handle the decoded data as needed
                        } catch let decodeError {
                                    // Handle decoding error
                        print("Decoding Error: \(decodeError.localizedDescription)")
                    }
                    
                case .failure(let failure):
                    print("ERROR \(failure)")
                }
            }
        }
        
    
   

    func setUpCollectionView(){
        let nibName = UINib(nibName: "PaymentMethodViewCell", bundle: B24PaymentSdkHelper.frameworkBundle())
        
        self.pmCollectionView.register(nibName, forCellWithReuseIdentifier: "PaymentMethodViewCell")
        
        self.pmCollectionView.backgroundColor = DefaultAppearance.shared.screenBgColor
        
        self.pmCollectionView.delegate = self
        self.pmCollectionView.dataSource = self
        
        self.pmCollectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        paymentMethodList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       
        let cell = pmCollectionView.dequeueReusableCell(withReuseIdentifier: "PaymentMethodViewCell", for: indexPath)as! PaymentMethodViewCell
        
        let paymentMethod = paymentMethodList[indexPath.row]
        
        configureCell(cell, with: paymentMethod)

        return cell
    }
    
    //Config each Cell
    private func configureCell(_ cell: PaymentMethodViewCell,with paymentMethod:PaymentMethodModel) {
        
        //remove overlay
        cell.overlayContainer.backgroundColor = UIColor.clear
        cell.overlayIcon.isHidden = true
        cell.overlayLabel.isHidden = true
        
        
        cell.bgCardView.addCardShadow(cornerRadius: 8)
        cell.bgCardView.roundCorners(cornerRadius: 8)
        cell.bgCardView.backgroundColor = DefaultAppearance.shared.cardColor
        cell.bgLogo.backgroundColor = DefaultAppearance.shared.primaryColor
        cell.bgLogo.layer.cornerRadius = 4
        cell.logo.tintColor = DefaultAppearance.shared.onPrimaryColor
        cell.titleLabel.text = paymentMethod.title
//        cell.titleLabel.font = B24PaymentSdkHelper.setFont(named: FixFontFamily.fontEnglishMedium, ofSize: FixFontSize.cardTitle)
        cell.titleLabel.font = FontManager.shared.mediumFont(forLanguage: language, fontFromconfig: DefaultAppearance.shared.fontEnglish, size:FixFontSize.cardTitle)
        cell.titleLabel.textColor = DefaultAppearance.shared.primaryLabelColor
        
        cell.logo.frame.size = CGSize(width: 30, height: 30)
        if(!paymentMethod.logo.isEmpty){
            cell.logo.frame.size = CGSize(width: 30, height: 30)
            cell.logo.loadImage(from: paymentMethod.logo)
            NSLayoutConstraint.activate([
                cell.logo.widthAnchor.constraint(equalToConstant: 30),
                cell.logo.heightAnchor.constraint(equalToConstant: 30)
            ])
           
            
        }
      
        
        cell.subTitleLabel.textColor = DefaultAppearance.shared.primaryLabelColor
        
        if language == "km" && !paymentMethod.subTitleKh.isEmpty{
            cell.subTitleLabel.text = paymentMethod.subTitleKh
            cell.subTitleLabel.font = FontManager.shared.regularFont(forLanguage: FixFontFamily.fontKhmerRegular,fontFromconfig:DefaultAppearance.shared.fontEnglish, size: FixFontSize.cardSubTitle)
        }else{
            cell.subTitleLabel.text = paymentMethod.subTitle
            cell.subTitleLabel.font = FontManager.shared.regularFont(forLanguage: language,fontFromconfig:DefaultAppearance.shared.fontEnglish, size: FixFontSize.cardSubTitle)
            
        }
        
        if paymentMethod.isActive{
            cell.bgInactive.isHidden = true
            cell.inactiveLabel.isHidden = true
           
        }else{
            
            cell.bgInactive.isHidden = false
            cell.inactiveLabel.isHidden = false
           
            cell.bgInactive.backgroundColor = DefaultAppearance.shared.dangerColor
            cell.bgInactive.layer.cornerRadius = 6
            cell.inactiveLabel.textColor = DefaultAppearance.shared.onPrimaryColor
            cell.inactiveLabel.font = FontManager.shared.regularFont(forLanguage: language ,fontFromconfig:DefaultAppearance.shared.fontEnglish, size: 12)
            cell.inactiveLabel.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.inActive.rawValue)
            
        }
        
        if paymentMethod.isDefault{
            cell.defaultIcon.isHidden = false
            cell.defaultIcon.image = UIImage(systemName:"star.fill")
            cell.defaultIcon.tintColor = DefaultAppearance.shared.primaryColor
        }else{
            cell.defaultIcon.isHidden = true
        }
            
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        guard NetworkMonitor.shared.isConnected else {
            if !isWaitingForConnection {
                isWaitingForConnection = true
                setupNetworkMonitoring()
                NetworkMonitor.shared.startMonitoring()
                
                B24PaymentSdkHelper.showNoInternetPopup(on: self) { [weak self] in
                    guard let self = self else { return }
                    self.isWaitingForConnection = false
                    B24PaymentSdkHelper.hideNoInternetPopup(from: self, showSuccess: false)
                }
            }
            return
        }

        let selectedItem = paymentMethodList[indexPath.row]
        
        SharedPreferenceManager.set(value: selectedItem.id, forKey: SharePrefKey.paymentMethodId.rawValue)
        
        let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
        if let accountDetailVC = storyboard.instantiateViewController(withIdentifier: "AccountDetailView") as? AccountDetailView {
            
//            let backButton = UIBarButtonItem()
//            
//           var toolbarTitle:String = B24PaymentSdkHelper.localized(AccountDetailLocalizedKeys.title.rawValue)
//            
//            backButton.title = toolbarTitle + selectedItem.
//            
//            // Customize the font and other attributes for the back button
//                        let customFont = FontManager.shared.mediumFont(forLanguage: language, size: FixFontSize.toolbarTitle)
//                        backButton.setTitleTextAttributes([
//                            .font: customFont,
//                            .foregroundColor: DefaultAppearance.shared.primaryLabelColor
//                        ], for: .normal)
//
//                        // Assign the custom back button to the current view controller's navigation item
//                        navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
//
//                        // Customize navigation bar colors and title text attributes
//                        navigationController?.navigationBar.tintColor = DefaultAppearance.shared.primaryLabelColor
//                        navigationController?.navigationBar.barTintColor = DefaultAppearance.shared.primaryLabelColor
            
            
           
            
            navigationController?.pushViewController(accountDetailVC, animated: true)
        }
       
    }

    @IBAction func addButtonAction(_ sender: Any) {
        if let availablePMVC = storyboard?.instantiateViewController(withIdentifier: "AvailablePaymentMethodView") as? AvailablePaymentMethodView {
//            if let availablePMVC = storyboard?.instantiateViewController(withIdentifier: "AddWalletView") as? AddWalletView {
            // Directly customize the navigation bar
                
//            availablePMVC.title = B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.title.rawValue)

            //self.present(availablePMVC, animated: true, completion: nil)
            navigationController?.pushViewController(availablePMVC, animated: true)
        } else {
            print("AddWalletView not found in storyboard")
        }
    }

    private func applyToolBar() {
        // Configure navigation bar appearance for consistency
        if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = DefaultAppearance.shared.screenBgColor
            appearance.shadowColor = DefaultAppearance.shared.primaryLabelColor.withAlphaComponent(0.3)
            
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = appearance
            navigationController?.navigationBar.compactAppearance = appearance
        } else {
            navigationController?.navigationBar.barTintColor = DefaultAppearance.shared.screenBgColor
            navigationController?.navigationBar.isTranslucent = false
        }
        
        let customButton = UIButton(type: .system)
        customButton.translatesAutoresizingMaskIntoConstraints = false
        // Image
        let imageView = UIImageView(image: UIImage(systemName: "chevron.backward"))
        imageView.tintColor = DefaultAppearance.shared.primaryLabelColor
        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        customButton.addSubview(imageView)

        // Title
        let titleLabel = UILabel()
        titleLabel.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.payment_method_title.rawValue)
        titleLabel.textColor = DefaultAppearance.shared.primaryLabelColor
        titleLabel.font = FontManager.shared.mediumFont(forLanguage: language, fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.toolbarTitle)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        customButton.addSubview(titleLabel)
     
        // Add constraints to position the image and title properly
        NSLayoutConstraint.activate([
            imageView.leadingAnchor.constraint(equalTo: customButton.leadingAnchor),
            imageView.centerYAnchor.constraint(equalTo: customButton.centerYAnchor),
            imageView.widthAnchor.constraint(equalToConstant: 20),
            imageView.heightAnchor.constraint(equalToConstant: 24),
            
            titleLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 4),
            titleLabel.centerYAnchor.constraint(equalTo: customButton.centerYAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: customButton.trailingAnchor, constant: -5),
        ])

        // Add action to the button
        customButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)

        // Create a UIBarButtonItem with the custom button
        let backButton = UIBarButtonItem(customView: customButton)
        navigationItem.leftBarButtonItem = backButton
    }
}
