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

import UIKit

class ShopCategoryVC: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var vm = ShopCategoryVM()
    
    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) {
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
        
        // 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 viewDidAppear(_ animated: Bool) {
        self.navigationController?.setColor(color: .white)
    }
    
    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)
    }
}

// MARK: - TableView DataSource , Delegates

extension ShopCategoryVC : TableViewSRC{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return vm.categoryData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: K.CellIdentifier.Shop.shopListingCell) as! ShopListingCell
        let data = vm.categoryData[indexPath.row]
        cell.setCategoryData(data: data)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = vm.categoryData[indexPath.row]
        
        if let catID = data.id{
            PersistentStorage.shared.addShopCount(postID: catID)
        }
        let sb = UIStoryboard(name: K.StoryBoard.shop, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Shop.shopProductsVC) as! ShopProductsVC
        vcPush.vm.categoryID = data.id
        vcPush.vm.pageTitle = data.categoryName
        self.navigationController?.pushViewController(vcPush, animated: true)
    }
}
