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

import UIKit

class ShopProductsVC: UIViewController {

    @IBOutlet weak var subCategoryCV: UICollectionView!
    @IBOutlet weak var productCV: UICollectionView!
    @IBOutlet weak var spinnerView: UIActivityIndicatorView!
    @IBOutlet weak var noDataStack: UIStackView!
    
    var vm = ShopProductsVM()
    
    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)
        
        /*
         check for single product
         */
        if self.vm.shopProductsData.count == 1{
            self.navigationController?.popViewController(animated: true)
        }
        
        // 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)
    }

    @IBAction func retryBtnTapped(_ sender: UIButton) {
        vm.getCategory()
    }
}

// MARK: - CollectionView Delegate

extension ShopProductsVC : CollectionViewSRC{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == subCategoryCV{
            return vm.subCategoryData.count
        }else{
            return vm.shopProductsData.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == subCategoryCV{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.CellIdentifier.WebSeries.seasonCategoryCell, for: indexPath) as! SeasonCategoryCell
            let data = vm.subCategoryData[indexPath.row]
            cell.setSubCategory(data: data, isSelected: data.id == vm.selectedSubCategory)
            return cell
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.CellIdentifier.Shop.shopProductsCell, for: indexPath) as! ShopProductsCell
            let data = vm.shopProductsData[indexPath.row]
            cell.setData(data: data)
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if collectionView == productCV{
            if vm.stopFetch{return}
            if indexPath.row == productCV.numberOfItems(inSection: 0) - 1{
                spinnerView.startAnimating()
                vm.pageNo += 1
                vm.getShopProducts(subCategoryID: vm.selectedSubCategory)
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch collectionView{
        case productCV:
            let data = vm.shopProductsData[indexPath.row]
            if let postID = data.id{
                PersistentStorage.shared.addShopCount(postID: postID)
            }
            let sb = UIStoryboard(name: K.StoryBoard.shop, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Shop.productDetailsVC) as! ProductDetailsVC
            vcPush.vm.productID = data.id
            self.navigationController?.pushViewController(vcPush, animated: true)
        case subCategoryCV:
            if let selectedSubCategory = vm.subCategoryData[indexPath.row].id{
                if selectedSubCategory == -1{
                    PersistentStorage.shared.addShopCount(postID: 0)
                }else{
                    PersistentStorage.shared.addShopCount(postID: selectedSubCategory)
                }
                
                vm.selectedSubCategory = selectedSubCategory
                self.subCategoryCV.reloadData()
                Utilities.startProgressHUD()
                vm.pageNo = 0
                vm.getShopProducts(subCategoryID: selectedSubCategory)
                productCV.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
            }
        default:
            break
        }
        
    }
}

// MARK: - Collection Flow Layout

extension ShopProductsVC : UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == subCategoryCV{
            // Generate a random string for testing purposes
            let randomText = vm.subCategoryData[indexPath.row].subCategoryName!
            
            // Define the font for the text
            let font = FontCustom.shareInstance.customFont(fontName: .Exo2_Bold, size: 18) // Adjust the font size as needed
            
            // Calculate the width of the text
            let attributes = [NSAttributedString.Key.font: font]
            let textWidth = (randomText as NSString).size(withAttributes: attributes).width
            
            // Set the cell width based on the text width and any additional padding
            // 14 for container view + 10 for inside spacing.
            let padding: CGFloat = 24 + 20 // Adjust padding as needed
            let cellWidth = textWidth + padding
            return CGSize(width: cellWidth , height: 60)
        }else{
            let numberOfItemsPerRow: CGFloat = 2
            let itemSpacing: CGFloat = 10
            let totalSpacing = (numberOfItemsPerRow - 1) * itemSpacing
            let totalWidth = collectionView.frame.width - totalSpacing
            let itemWidth = totalWidth / numberOfItemsPerRow
            let itemHeight = itemWidth - 20 // Adjust based on your needs
            
            return CGSize(width: itemWidth, height: itemHeight)
        }
    }
}
