//
//  ShopListingVC.swift
//  WOKA
//
//  Created by MacBook Pro on 22/07/24.
//

import UIKit

class ShopListingVC: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var noDataStack: UIStackView!
    
    var vm = ShopListingVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vm.vc = self
        vm.initView()
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
        self.navigationController?.setColor(color: .white)
        
        // Update the badge label with the current cart data
        if let button = vm.cartButton.customView as? UIButton {
            BadgeBarBtn.shared.updateBadge(for: button, with: CartDataCache.cartListData.count.toString())
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
        if self.isMovingFromParent {
            // Back button was pressed
            PersistentStorage.shared.addOthersCount()
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        // Customize the navigation bar's appearance
        self.navigationController?.setColor(color: .black)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        /*
         Check if ads is there to map impressions
         */
        if let adsData = AuthFunc.shareInstance.adsData{
            // check if ads data contains ad for webseries
            if let shopSuperCatAd = adsData.result?.filter({$0.forPage == AdsEnum.shop_super_category.rawValue}).first, let adID = shopSuperCatAd.id{
                PersistentStorage.shared.addAdsCount(adID: adID ,impressions: 1)
            }
        }
    }
    
    @IBAction func retryBtnTapped(_ sender: LocalisedElementsButton) {
        noDataStack.isHidden = true
        tableView.isHidden = false
        vm.getSuperCategory()
    }
}

// MARK: - TableView DataSource , Delegates

extension ShopListingVC : TableViewSRC{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return vm.superCatData.count == 0 ? 3 : vm.superCatData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: K.CellIdentifier.Shop.shopListingCell) as! ShopListingCell

        if vm.superCatData.count == 0{
            cell.showShimmer()
        }else{
            let data = vm.superCatData[indexPath.row]
            cell.setData(data: data)
            cell.stopShimmer()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        /*
         MAke logic for ads
         */
        if vm.superCatData[indexPath.row].isAD == true{
            if let adsData = AuthFunc.shareInstance.adsData{
                // check if ads data contains ad for webseries
                if let shopSuperCatAd = adsData.result?.filter({$0.forPage == AdsEnum.shop_super_category.rawValue}).first,let adLink = shopSuperCatAd.adLink, let adID = shopSuperCatAd.id{
                    PersistentStorage.shared.addAdsCount(adID: adID,clicks: 1)
                    if let url = URL(string: adLink), UIApplication.shared.canOpenURL(url) {
                        UIApplication.shared.open(url)
                    }
                    return
                }
            }
        }
        
        if vm.superCatData.count == 0 {return}
        
        let superCatID = vm.superCatData[indexPath.row].id
        if let superCatID{
            PersistentStorage.shared.addShopCount(postID: superCatID)
        }
        let sb = UIStoryboard(name: K.StoryBoard.shop, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Shop.shopCategoryVC) as! ShopCategoryVC
        vcPush.vm.superCatID = superCatID
        self.navigationController?.pushViewController(vcPush, animated: true)
        
//        if let adsData = AuthFunc.shareInstance.adsData, (adsData.result?.filter({$0.forPage == AdsEnum.shop_super_category.rawValue}).first) != nil{
//            // check if ads data contains ad for webseries
//                let superCatID = vm.superCatData[indexPath.row - 1].id
//                if let superCatID{
//                    PersistentStorage.shared.addShopCount(postID: superCatID)
//                }
//                let sb = UIStoryboard(name: K.StoryBoard.shop, bundle: nil)
//                let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Shop.shopCategoryVC) as! ShopCategoryVC
//                vcPush.vm.superCatID = superCatID
//                self.navigationController?.pushViewController(vcPush, animated: true)
//                return
//        }else{
//            let superCatID = vm.superCatData[indexPath.row].id
//            if let superCatID{
//                PersistentStorage.shared.addShopCount(postID: superCatID)
//            }
//            let sb = UIStoryboard(name: K.StoryBoard.shop, bundle: nil)
//            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Shop.shopCategoryVC) as! ShopCategoryVC
//            vcPush.vm.superCatID = superCatID
//            self.navigationController?.pushViewController(vcPush, animated: true)
//        }
    }
}

//extension UIViewController {
//    
//    func createCartButton(imageName: String,
//                          badgeNumber: Int,
//                          buttonSize: CGSize = CGSize(width: 50, height: 50),
//                          badgeColor: UIColor = .red,
//                          badgeTextColor: UIColor = .white,
//                          buttonColor: UIColor = .blue,
//                          target: Any,
//                          action: Selector) -> UIBarButtonItem {
//        
//        // Create the button
//        let button = UIButton(type: .custom)
//        button.setImage(UIImage(named: imageName), for: .normal)
//        button.setTitleColor(.black, for: .normal)
//        button.addTarget(target, action: action, for: .touchUpInside)
//        button.isEnabled = true
//        button.isUserInteractionEnabled = true
//        // Set button height and width
//        button.translatesAutoresizingMaskIntoConstraints = false
//        button.widthAnchor.constraint(equalToConstant: buttonSize.width).isActive = true
//        button.heightAnchor.constraint(equalToConstant: buttonSize.height).isActive = true
//        
//        // Create the badge label
////        let badgeLabel = UILabel()
//        CartDataCache.cartBadgeLabel.text = "\(badgeNumber)"
//        CartDataCache.cartBadgeLabel.textColor = badgeTextColor
//        CartDataCache.cartBadgeLabel.backgroundColor = badgeColor
//        CartDataCache.cartBadgeLabel.font = UIFont.systemFont(ofSize: 12)
//        CartDataCache.cartBadgeLabel.textAlignment = .center
//        CartDataCache.cartBadgeLabel.layer.cornerRadius = 10
//        CartDataCache.cartBadgeLabel.clipsToBounds = true
//        
//        badgeNumber == 0 ? (CartDataCache.cartBadgeLabel.isHidden = true) : (CartDataCache.cartBadgeLabel.isHidden = false)
//        // Set badge label constraints
//        CartDataCache.cartBadgeLabel.translatesAutoresizingMaskIntoConstraints = false
//        CartDataCache.cartBadgeLabel.widthAnchor.constraint(equalToConstant: 20).isActive = true
//        CartDataCache.cartBadgeLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
//        
//        // Create a container view for the button
//        let containerView = UIView(frame: CGRect(x: 0, y: 0, width: buttonSize.width, height: buttonSize.height))
//        
//        containerView.backgroundColor = buttonColor
//        containerView.addSubview(button)
//        containerView.addSubview(CartDataCache.cartBadgeLabel)
//        containerView.isUserInteractionEnabled = true
//        // Set constraints for the button inside the container view
//        NSLayoutConstraint.activate([
//            button.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
//            button.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
//            
//            // Position the badge at the top-right corner of the button
//            CartDataCache.cartBadgeLabel.topAnchor.constraint(equalTo: button.topAnchor, constant: -3),
//            CartDataCache.cartBadgeLabel.rightAnchor.constraint(equalTo: button.rightAnchor, constant: -2)
//        ])
//        
//        // Create a UIBarButtonItem with the custom view
//        let customBarButton = UIBarButtonItem(customView: containerView)
//        // Return the custom bar button
//        return customBarButton
//    }
//}
