//
//  CartDataCache.swift
//  WOKA
//
//  Created by MacBook Pro on 29/07/24.
//

import Foundation
import Alamofire

class CartDataCache{
    
    static var cartListData = [CartListingDM.ResultData](){
        didSet{
                cartBadgeLabel.text = cartListData.count.toString()
                cartBadgeLabel.isHidden = false
        }
    }
    
    static var isFetched = false
//    static var cartCount = 0 {
//        didSet{
//            if cartCount == 0{
//                cartBadgeLabel.text = "0"
//                cartBadgeLabel.isHidden = true
//            }else{
//                cartBadgeLabel.text = cartCount.toString()
//                cartBadgeLabel.isHidden = false
//            }
//        }
//    }
    
    static var addressData = [AddressListDM]()
    static let cartBadgeLabel = UILabel()
    static let shareInstance = CartDataCache()

    func removeAll(){
        CartDataCache.addressData.removeAll()
        CartDataCache.cartListData.removeAll()
        CartDataCache.isFetched = false
        CartDataCache.cartBadgeLabel.text = "0"
    }
    
    func getCartList(vc : UIViewController, onCompletion : @escaping (Bool) -> Void){
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Cart.cart_listing, method: .get,headers: headers, queue : QueueHelper.background) { (result : Result<BaseResponseModel<CartListingDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    onCompletion(false)
                case 1:
                    Utilities.dismissProgressHUD()
                    
                    guard let data = data.data?.result else{return}
                    CartDataCache.cartListData = data
                    CartDataCache.isFetched = true
                    CartDataCache.cartBadgeLabel.text = data.count.toString()
                    onCompletion(true)
                default:
                    Utilities.dismissProgressHUD()
                    onCompletion(false)
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
//                Utilities.alert(title: "Error", message: error.localizedDescription, viewController: vc)
                onCompletion(false)
            }
        }
    }
}

class BadgeBarBtn {
    static let shared = BadgeBarBtn()

    func setupBadge(for button: UIButton, with text: String) {
        var badgeLabel = CartDataCache.cartBadgeLabel

        if let existingLabel = button.viewWithTag(999) as? UILabel {
            badgeLabel = existingLabel
        } else {
            badgeLabel = UILabel()
            badgeLabel.tag = 999
            button.addSubview(badgeLabel)
        }
        
        badgeLabel.frame = CGRect(x: 30, y: 0, width: 18, height: 18)
        badgeLabel.backgroundColor = UIColor.red
//        badgeLabel.isHidden = false // Ensure it is not hidden
        badgeLabel.clipsToBounds = true
        badgeLabel.layer.cornerRadius = 9
        badgeLabel.textColor = UIColor.white
        badgeLabel.font = FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 10)
        badgeLabel.textAlignment = .center
        badgeLabel.text = text
        
        button.addShadowAndCorner(radius: button.frame.width / 2, shadowColor: .darkGray, shadowOpacity: 0.5, shadowOffset: CGSize(width: 0, height: 0.8), shadowRadius: 6)

        // Add the badge label to the button if not already added
        if badgeLabel.superview != button {
            button.addSubview(badgeLabel)
        }

        // Ensure the badge label is brought to the front
        button.bringSubviewToFront(badgeLabel)
    }

    func setupCartButton(target: Any?, action: Selector) -> UIBarButtonItem {
        let filterBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 45, height: 45))
        filterBtn.setImage(UIImage(named: "CartIcon"), for: .normal)
        filterBtn.addTarget(target, action: action, for: .touchUpInside)

        // Configure the badge label
        setupBadge(for: filterBtn, with: CartDataCache.cartListData.count.toString())

        return UIBarButtonItem(customView: filterBtn)
    }
    
    func updateBadge(for button: UIButton, with text: String) {
        if let badgeLabel = button.viewWithTag(999) as? UILabel {
            if text == "0"{
                badgeLabel.backgroundColor = .clear
                badgeLabel.textColor = .clear
            }else{
                badgeLabel.backgroundColor = .red
                badgeLabel.textColor = .white
            }
            badgeLabel.text = text
            badgeLabel.isHidden = text.isEmpty
        }
    }
}
