//
//  KaraokeListingVC.swift
//  WOKA
//
//  Created by Bilal on 05/07/2024.
//

import UIKit
import GoogleMobileAds

class KaraokeListingVC: UIViewController {

    @IBOutlet weak var headerView: ShimmerEffectView!
    @IBOutlet weak var headerBtn: LocalisedElementsButton!
    @IBOutlet weak var selectedShowView: ShimmerEffectView!
    @IBOutlet weak var headerHeight: NSLayoutConstraint!
    @IBOutlet weak var headerViewLabelHeight: NSLayoutConstraint!
    @IBOutlet weak var headerImage: UIImageView!
    @IBOutlet weak var headerTitleLabel: UILabel!
    @IBOutlet weak var noDataStack: UIView!
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var continueWatchingCV: UICollectionView!
    @IBOutlet weak var continueWatchingStack: UIStackView!

    @IBOutlet weak var karaokeListingTableView: UITableView!
    @IBOutlet weak var tableHeight: NSLayoutConstraint!
    @IBOutlet weak var loadMoreBtn: LocalisedElementsButton!
    @IBOutlet weak var loadMoreActivityIndicator: UIActivityIndicatorView!
    
    var vm = KaraokeListingVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        scrollView.delegate = self
        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)
    }
    
    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 viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        vm.updateTableHeight()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        if K.GVar.reloadContinueKaraoke{
            K.GVar.reloadContinueKaraoke = false
            self.vm.getContinueWatching()
        }
        
        /*
         Check if ads is there to map impressions
         */
        if let adsData = AuthFunc.shareInstance.adsData{
            // check if ads data contains ad for webseries
            if let karaokeAd = adsData.result?.filter({$0.forPage == AdsEnum.karaoke.rawValue}).first, let adID = karaokeAd.id{
                PersistentStorage.shared.addAdsCount(adID: adID ,impressions: 1)
            }
        }
    }
    
    @IBAction func loadMoreBtnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addOthersCount()
        loadMoreBtn.isHidden = true
        vm.pageNo += 1
        loadMoreActivityIndicator.startAnimating()
        vm.getKaraokeListing(isBtnClick: true)
    }
    
    @IBAction func singBtnTapped(_ sender: LocalisedElementsButton) {
        
        /*
         MAke logic for ads
         */
        if let adsData = AuthFunc.shareInstance.adsData{
            // check if ads data contains ad for webseries
            if let karaokeAd = adsData.result?.filter({$0.forPage == AdsEnum.karaoke.rawValue}).first, let adLink = karaokeAd.adLink, let adID = karaokeAd.id{
                PersistentStorage.shared.addAdsCount(adID: adID ,clicks: 1)

                if let url = URL(string: adLink), UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url)
                }
                return
            }
        }
        
        if let id = vm.headerData?.id{
            PersistentStorage.shared.addKaraokeCount(postID: id)
        }
        
        let sb = UIStoryboard(name: K.StoryBoard.Karaoke, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Karaoke.karaokeDetailsVC) as! KaraokeDetailsVC
        vcPush.modalPresentationStyle = .overCurrentContext
        vcPush.modalTransitionStyle = .crossDissolve
        vcPush.karaokeData = vm.headerData
        vcPush.delegate = self
        self.present(vcPush, animated: true)
    }
    
    @IBAction func retryBtnTapped(_ sender: LocalisedElementsButton) {
        /*
         make page 0 as its lazy loading, hide the no data stack as retry is tapped,
         start the shimmer and reload tableview so that both header and table shimmer matches, get the karaoke listing
         */
        vm.pageNo = 0
        noDataStack.isHidden = true
        headerTitleLabel.isHidden = false
        headerBtn.isHidden = false
        vm.startShimmer()
        vm.getKaraokeListing()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { [weak self] in
            guard let self else{return}
            vm.checkAds()
        })
    }
}

// MARK: - CollectionView Delegate and Data Source

extension KaraokeListingVC : CollectionViewSRC{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return vm.continueWatchingData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.CellIdentifier.AudioBooks.continueAudioCell, for: indexPath) as! ContinueAudioCell
        let data = vm.continueWatchingData[indexPath.row]
        cell.setKaraokeData(data: data)
        
        cell.btnTapped = { [self] (type) -> Void in
            guard let postID = data.id ,let postType = data.contentMoreDetails?.first?.postType else{return}
            let isFav = data.markAsFavourite
            let isLiked = data.isLiked
            PersistentStorage.shared.addKaraokeCount(postID: postID)

            vm.updateFavLikes(type: type, isFav: isFav, isLiked: isLiked, postID: postID, postType: postType)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let data = vm.continueWatchingData[indexPath.row]
        if let id = data.id{
            PersistentStorage.shared.addKaraokeCount(postID: id)
        }

        /*
         MAke logic for ads
         */
        if let adsData = AuthFunc.shareInstance.adsData, adsData.result?.filter({$0.forPage == AdsEnum.karaoke.rawValue}).first != nil{
            // check if ads data contains ad for webseries
        }else{
            /*
             Updated the top header data
             */
            vm.headerData = data
            vm.setHeaderData()
        }
        
        let sb = UIStoryboard(name: K.StoryBoard.Karaoke, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Karaoke.karaokeDetailsVC) as! KaraokeDetailsVC
        vcPush.modalPresentationStyle = .overCurrentContext
        vcPush.modalTransitionStyle = .crossDissolve
        vcPush.karaokeData = data
        vcPush.delegate = self
        self.present(vcPush, animated: true)

    }
    
}

// MARK: - Collection Flow Layout

extension KaraokeListingVC : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let inset: CGFloat = 10
        return UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0 // Space between cells
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let widthPerItem = collectionView.frame.width - 30 // Adjust to your desired width
        return CGSize(width: widthPerItem, height: 230)
    }
}

// MARK: - TableView DataSource , Delegates

extension KaraokeListingVC : TableViewSRC{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return vm.karaokeListData.count == 0 ? 2 : vm.karaokeListData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: K.CellIdentifier.WebSeries.webSeriesShowListingCell) as! WebSeriesShowListingCell

        if vm.karaokeListData.count == 0{
            cell.showShimmer()
        }else{
            cell.stopShimmer()
            let data = vm.karaokeListData[indexPath.row]
            cell.setKaraokeData(data: data)
        }
        
        cell.btnTapped = { [weak self] (type) -> Void in
            guard let self else{return}
            let data = vm.karaokeListData[indexPath.row]
            guard let postID = data.id ,let postType = data.contentMoreDetails?.first?.postType else{return}
            let isFav = data.markAsFavourite
            let isLiked = data.isLiked
            
            PersistentStorage.shared.addKaraokeCount(postID: postID)
            
            vm.updateFavLikes(type: type, isFav: isFav, isLiked: isLiked, postID: postID, postType: postType)
        }
        return cell
    }

    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if vm.karaokeListData.count == 0 {return}
        let data = vm.karaokeListData[indexPath.row]
        
        if let id = data.id{
            PersistentStorage.shared.addKaraokeCount(postID: id)
        }
        
        /*
         MAke logic for ads
         */
        if let adsData = AuthFunc.shareInstance.adsData, adsData.result?.filter({$0.forPage == AdsEnum.karaoke.rawValue}).first != nil{
            // check if ads data contains ad for webseries
        }else{
            /*
             Updated the top header data
             */
            vm.headerData = data
            vm.setHeaderData()
        }
        
        let sb = UIStoryboard(name: K.StoryBoard.Karaoke, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Karaoke.karaokeDetailsVC) as! KaraokeDetailsVC
        vcPush.modalPresentationStyle = .overCurrentContext
        vcPush.modalTransitionStyle = .crossDissolve
        vcPush.karaokeData = data
        vcPush.delegate = self
        self.present(vcPush, animated: true)
    }
}

// MARK: - Protocol Listener

extension KaraokeListingVC : ReloadSeriesFavLike{
    
    func updateRows(index: Int, type: FavCellCLick, isFav: Bool?, isLike: Bool? , id : Int?) {
        guard let id else{return}
        if let isFav{
            if let continueDataIndex = vm.continueWatchingData.firstIndex(where:{$0.id == id}) {
                vm.continueWatchingData[continueDataIndex].markAsFavourite = isFav
                continueWatchingCV.reloadItems(at: [IndexPath(row: continueDataIndex, section: 0)])
            }
            
            if let audioListDataIndex = vm.karaokeListData.firstIndex(where:{$0.id == id}) {
                vm.karaokeListData[audioListDataIndex].markAsFavourite = isFav
                karaokeListingTableView.reloadRows(at: [IndexPath(row: audioListDataIndex, section: 0)],with: .none)
            }
        }
        
        if let isLike{
            if let continueDataIndex = vm.continueWatchingData.firstIndex(where:{$0.id == id}) {
                vm.continueWatchingData[continueDataIndex].isLiked = isLike
                vm.continueWatchingData[continueDataIndex].likesCount! += isLike ? 1 : -1
                continueWatchingCV.reloadItems(at: [IndexPath(row: continueDataIndex, section: 0)])
            }
            
            if let audioListDataIndex = vm.karaokeListData.firstIndex(where:{$0.id == id}) {
                vm.karaokeListData[audioListDataIndex].isLiked = isLike
                vm.karaokeListData[audioListDataIndex].likesCount! += isLike ? 1 : -1
                karaokeListingTableView.reloadRows(at: [IndexPath(row: audioListDataIndex, section: 0)],with: .none)
            }
        }
    }
}

// MARK: - Google Ad Banner Delegate

extension KaraokeListingVC : GADBannerViewDelegate{
    func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
        switch bannerView{
        case vm.headerBannerView:
            headerView.stopShimmer()
        case vm.headerBannerBottomView:
            headerBtn.alpha = 0
            headerBtn.isEnabled = false
            selectedShowView.stopShimmer()
        default:
            break
        }
        print("bannerViewDidReceiveAd")
        bannerView.backgroundColor = #colorLiteral(red: 0.01960784314, green: 0, blue: 0.2196078431, alpha: 1)
    }
    
    func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
        switch bannerView{
        case vm.headerBannerView:
            headerView.stopShimmer()
        case vm.headerBannerBottomView:
            headerTitleLabel.isHidden = true
            headerBtn.isHidden = true
            selectedShowView.stopShimmer()
        default:
            break
        }
        print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
    }

    func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
      print("bannerViewDidRecordImpression")
    }

    func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
      print("bannerViewWillPresentScreen")
    }

    func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
      print("bannerViewWillDIsmissScreen")
    }

    func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
      print("bannerViewDidDismissScreen")
    }
}

// MARK: - Animating scrollView

extension KaraokeListingVC: UIScrollViewDelegate {
        
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // Get the current vertical offset of the scroll view
        let y = scrollView.contentOffset.y

        // Define the height range for the header view
        let minHeaderHeight: CGFloat = 0.0 // Height at which the header becomes invisible

        // Calculate the new height for the header view based on the scroll position
        let newHeaderHeight: CGFloat
        if y < 0 {
            // When scrolling up beyond the top, ensure the header view is fully expanded
            newHeaderHeight = vm.maxHeaderHeight
        } else {
            // Calculate the new height for the header view, ensuring it doesn't go below the minimum height
            newHeaderHeight = max(minHeaderHeight, vm.maxHeaderHeight - y)
        }

        // Update the header view's height constraint with the new height
        headerHeight.constant = newHeaderHeight

        // Animate the layout changes to smoothly transition the header height
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
        }
    }
}
