//
//  AvailablePaymentMethodView.swift
//  B24PaymentSdk
//
//  Created by visal ny on 19/12/24.
//

import UIKit
import Alamofire

class AvailablePaymentMethodView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
    
    var availablePMType:[AvailablePaymentMethodType] = []
    
    @IBOutlet weak var apmCollectionView: UICollectionView!
    
    @IBOutlet var loadingIndicator: UIActivityIndicatorView!
    
    @IBOutlet weak var navBottomLine: UIView!
    private let refreshControl = UIRefreshControl()
    
    @IBOutlet weak var noAvailabelPMBackground: UIView!
    
    @IBOutlet weak var noAvailableLabel: UILabel!
    @IBOutlet weak var noAvailableIcon: UIImageView!
    var language:String = "km"
    var customerSyncCode:String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        view.backgroundColor = DefaultAppearance.shared.screenBgColor
        self.noAvailabelPMBackground.isHidden=true;
        self.noAvailableIcon.isHidden=true;
        self.noAvailableLabel.isHidden=true;
        
        navBottomLine.isHidden = true
       
        
        getSharePref()
        B24PaymentSdkHelper.getCurrentLanguage(language: language)
        
        applyToolBar()
        
        setUpCollectionViewCell()
        setUpUIRefreshControl()
        fetchAvailablePMType()
        

    }
    
    func getSharePref(){
        if let languageCode = SharedPreferenceManager.getString(forKey: SharePrefKey.lanuageCode.rawValue){
            language = languageCode
        }else{
            language = "km"
        }
        
        if let code = SharedPreferenceManager.getString(forKey: SharePrefKey.customerSyncode.rawValue){
            customerSyncCode = code
        }else{
            customerSyncCode = ""
        }
    }
    
    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)
        // Image
        let imageView = UIImageView(image: UIImage(systemName: "chevron.backward"))
        imageView.tintColor = DefaultAppearance.shared.primaryLabelColor
        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        customButton.addSubview(imageView)
        
        let titleLabel = UILabel()
        
        titleLabel.text = B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.add_payment_method.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,constant: -10),
            imageView.centerYAnchor.constraint(equalTo: customButton.centerYAnchor),
            imageView.widthAnchor.constraint(equalToConstant: 24), // Set desired width
            imageView.heightAnchor.constraint(equalToConstant: 24),
            
            titleLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 8),
            titleLabel.centerYAnchor.constraint(equalTo: customButton.centerYAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: customButton.trailingAnchor)
        ])

        // 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
    }
    
    // Back button action
    @objc func backButtonTapped() {
        navigationController?.popViewController(animated: true)
    }
    
    
    
    func setUpCollectionViewCell(){
        let nibName = UINib(nibName: "AvailablePMCollectionViewCell", bundle: B24PaymentSdkHelper.frameworkBundle())
        
        self.apmCollectionView.register(nibName, forCellWithReuseIdentifier: "AvailablePMCollectionViewCell")
        
        self.apmCollectionView.backgroundColor = DefaultAppearance.shared.screenBgColor
        
        self.apmCollectionView.delegate = self
        self.apmCollectionView.dataSource = self
        
        self.apmCollectionView.reloadData()
        
        
    }
    
    func setUpUIRefreshControl(){
        refreshControl.tintColor = DefaultAppearance.shared.primaryColor
        refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged)
        apmCollectionView.refreshControl = refreshControl
    }
    
    @objc func refreshData() {
        fetchAvailablePMType(isRefreshing: true)
    }
    
    func setUpLoadinIndicator(isShow:Bool){
        loadingIndicator.style = .large
        loadingIndicator.color = DefaultAppearance.shared.primaryColor
        if isShow{
            loadingIndicator.startAnimating()
        }else{
            loadingIndicator.isHidden = true
            loadingIndicator.stopAnimating()
        }
    }
        
    
    
    func fetchAvailablePMType(isRefreshing: Bool = false){
       
        // Show loading indicator
        if !isRefreshing {
            setUpLoadinIndicator(isShow: true) // Show loading indicator only if not refreshing
        }
        
        AF.request(WalletRouter.getAvailablePMType(customerSyncCode: customerSyncCode)).validate().responseData{
            response in
            
            // Hide loading indicator
            if !isRefreshing {
                self.setUpLoadinIndicator(isShow: false) // Hide loading indicator
            }
                        
            if isRefreshing {
                self.refreshControl.endRefreshing() // Stop refresh control
            }
            
            switch response.result {
            case .success(let data):
                do {
                    // Decode the response data
                    let decodedData = try JSONDecoder().decode(AvailablePMTypeResponseModel.self, from: data)
                    
                    if(decodedData.data.availablePaymentMethodTypes.isEmpty || !decodedData.data.availablePaymentMethodTypes.contains(where: { $0.type == "wallet" })){
                        //show empty ui
                        self.noAvailabelPMBackground.isHidden=false;
                        self.noAvailableIcon.isHidden=false;
                        self.noAvailableLabel.isHidden=false;
                        
                        self.noAvailabelPMBackground.backgroundColor = DefaultAppearance.shared.screenBgColor;
                        self.noAvailableIcon.tintColor = DefaultAppearance.shared.warningColor
                        self.noAvailableLabel.text = B24PaymentSdkHelper.localized(PaymentMethodWalletLocalizedKeys.msg_no_apm.rawValue)
                        self.noAvailableLabel.font = FontManager.shared.mediumFont(forLanguage: self.language,fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
                        self.noAvailableLabel.textColor = DefaultAppearance.shared.secondaryLabelColor
                        
                        
                    }else{
                        
                        self.noAvailabelPMBackground.isHidden=true;
                        self.noAvailableIcon.isHidden=true;
                        self.noAvailableLabel.isHidden=true;
                        
                        
                        // Reload data on the main thread after fetching
                        DispatchQueue.main.async {
                            self.availablePMType = decodedData.data.availablePaymentMethodTypes
                            self.apmCollectionView.reloadData()
                        }
                    }
                    
                   
                    
                    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 numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return availablePMType.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = apmCollectionView.dequeueReusableCell(withReuseIdentifier: "AvailablePMCollectionViewCell", for:indexPath) as! AvailabelPMCollectionViewCell
        
        
        let availabePMType = availablePMType[indexPath.row]
        
        configureCell(cell, with: availabePMType)

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let availbePMType = availablePMType[indexPath.row]
        
        performAction(for: availbePMType)
        
        //print("Selected Payment Method: \(availbePMType.name)")
        
    }
    
    // action when click on the item
    func performAction(for paymentMethodType:AvailablePaymentMethodType){
        
        // when item is wallet
        if paymentMethodType.type == AvailablePMType.wallet.rawValue {
            let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
                if let addWalletVC = storyboard.instantiateViewController(withIdentifier: "AddWalletView") as? AddWalletView {
                    
//                    let backButton = UIBarButtonItem()
//                    backButton.title = B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.title.rawValue)
//                        
//                    // 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(addWalletVC, animated: true)
                } else {
                    print("AddWalletView not found in storyboard")
            }
         }
     }

    
    
    //Config each Cell
    private func configureCell(_ cell: AvailabelPMCollectionViewCell, with paymentMethodType: AvailablePaymentMethodType) {
        
        
        //apply icon for payment method type
       if paymentMethodType.type != AvailablePMType.wallet.rawValue{
            cell.paymentMethodTypeIcon.image = UIImage(systemName: "creditcard.fill")
           
            //remove other payment method type beside wallet
            cell.paymentMethodTypeCardView.isHidden = true
        }
        
        if language == "km" && !paymentMethodType.nameKh.isEmpty {
            cell.paymentMethodTypeTitle.text = paymentMethodType.nameKh
        }else{
            cell.paymentMethodTypeTitle.text = paymentMethodType.name
        }
        
        cell.paymentMethodTypeTitle.font = FontManager.shared.mediumFont(forLanguage: language ,fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.cardTitle)
            
        cell.paymentMethodTypeTitle.textColor = DefaultAppearance.shared.primaryLabelColor
        
        cell.backgroundLogo.backgroundColor = DefaultAppearance.shared.primaryColor
        cell.paymentMethodTypeIcon.tintColor = DefaultAppearance.shared.onPrimaryColor
        cell.paymentMethodTypeCardView.backgroundColor = DefaultAppearance.shared.cardColor
            
        //set shadow and radadius on container
        cell.addCardShadow(cornerRadius: 8)
        //set corner on child
        cell.paymentMethodTypeCardView.roundCorners(cornerRadius: 8)
           
        cell.backgroundLogo.layer.cornerRadius = 6
        
            
        }

}

// extension UIView {
//     func addCardShadow(cornerRadius: CGFloat, shadowColor: UIColor = .black, shadowOpacity: Float = 0.1, shadowOffsetY: CGFloat = 3, shadowBlur: CGFloat = 13) {
//             // Add shadow to the container
//             self.layer.shadowColor = shadowColor.cgColor
//             self.layer.shadowOpacity = shadowOpacity
//             self.layer.shadowOffset = CGSize(width: 0, height: shadowOffsetY)
//             self.layer.shadowRadius = shadowBlur
//             self.layer.masksToBounds = false
//         }

//         func roundCorners(cornerRadius: CGFloat) {
//             // Add rounded corners to the card
//             self.layer.cornerRadius = cornerRadius
//             self.layer.masksToBounds = true
//         }
// }

