//
//  ProductDetailsVC.swift
//  WOKA
//
//  Created by Bilal on 26/07/2024.
//

import UIKit

class ProductDetailsVC: UIViewController {

    @IBOutlet weak var productTitle: UILabel!
    @IBOutlet weak var categoryName: UILabel!
    @IBOutlet weak var skuID: UILabel!
    @IBOutlet weak var productPrice: UILabel!
    @IBOutlet weak var productDescription: UILabel!
    @IBOutlet weak var addToCartBtn: LocalisedElementsButton!
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var productImageCV: UICollectionView!
    @IBOutlet weak var shadowView: UIView!
    @IBOutlet weak var noDataStack: UIStackView!
    @IBOutlet weak var retryBtn: UIButton!
    @IBOutlet weak var scrollView: UIScrollView!
    
    var vm = ProductDetailsVM()
    
    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)
    }
    
    @IBAction func pageControl(_ sender: UIPageControl) {
        self.productImageCV.scrollToItem(at: IndexPath(row: sender.currentPage, section: 0), at: .centeredHorizontally, animated: true)
    }
    
    @IBAction func addToCartBtnTapped(_ sender: LocalisedElementsButton) {
        if let postID =  vm.productDetails?.id{
            PersistentStorage.shared.addShopCount(postID: postID)
        }
        if AuthFunc.shareInstance.guestUserLoginPopUp() { return}

        if sender.titleLabel?.text == "Add to Cart"{
            if let shopMasterID = vm.productDetails?.id{
                vm.addToCart(shopMasterID: shopMasterID)
            }
        }else{
            if let shopMasterID = vm.productDetails?.id{
                vm.removeItemFromCart(shopMasterID: shopMasterID)
            }
        }
    }
    
    @IBAction func retryBtnTapped(_ sender: UIButton) {
        if let productID = vm.productID{
            vm.getProductDetails(productID: productID)
        }
    }
}

// MARK: - Collection delegate and datasource

extension ProductDetailsVC : UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return vm.productDetails?.shopImage?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.CellIdentifier.Shop.shopProductImageCell, for: indexPath) as! ShopProductImageCell
        if let data = vm.productDetails?.shopImage?[indexPath.row]{
            cell.setData(image: data)
        }
        return cell
    }
    
    // MARK: - Collection Scroll Handling

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let visibleRect = CGRect(origin: self.productImageCV.contentOffset, size: self.productImageCV.bounds.size)
        let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
        if let visibleIndexPath = self.productImageCV.indexPathForItem(at: visiblePoint) {
            self.pageControl.currentPage = visibleIndexPath.row
        }
    }
}

// MARK: - Collection Flow Layout

extension ProductDetailsVC : UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let frameSize = collectionView.frame.size
        return CGSize(width: frameSize.width - 10, height: frameSize.height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    }
}
