//
//  WebSeriesSeasonVC.swift
//  WOKA
//
//  Created by MacBook Pro on 20/06/24.
//

import UIKit
import JWPlayerKit

class WebSeriesSeasonVC: UIViewController {
    
    var vm = WebSeriesSeasonVM()
    
    @IBOutlet weak var seasonImage: UIImageView!
    @IBOutlet weak var seasonTitle: UILabel!
    @IBOutlet weak var seasonDate: UILabel!
    @IBOutlet weak var seasonEpisodes: UILabel!
    @IBOutlet weak var seasonMediaType: UILabel!
    @IBOutlet weak var seasonDesc: UILabel!
    
    @IBOutlet weak var categoryCV: UICollectionView!

    //Episode Outlet
    @IBOutlet weak var episodeTitle: UILabel!
    @IBOutlet weak var episodeTableView: UITableView!
    @IBOutlet weak var tableHeight: NSLayoutConstraint!
    
    //Teaser Outlet
    @IBOutlet weak var teaserTableView: UITableView!
    @IBOutlet weak var teaserTableHeight: NSLayoutConstraint!
    @IBOutlet weak var teaserTitle: LocalisedElementsLabel!
    
    @IBOutlet weak var addIcon: UIImageView!
    @IBOutlet weak var addLabel: UILabel!
    @IBOutlet weak var likeIcon: UIImageView!
    @IBOutlet weak var likeLabel: UILabel!
    @IBOutlet weak var totalLikes: UILabel!
    
    @IBOutlet weak var addView: UIView!
    @IBOutlet weak var shareView: UIView!
    @IBOutlet weak var likeView: UIView!
    
    @IBOutlet weak var loadMoreBtn: LocalisedElementsButton!
    @IBOutlet weak var loadMoreActivityIndicator: UIActivityIndicatorView!
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var noDataStack: UIStackView!
    
    var likeFavDelegate : ReloadSeriesFavLike?
    
    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)
    }
    
    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 playTrailerBtnTapped(_ sender: LocalisedElementsButton) {
        // 1-> english , 18- hindi
        var playerItems = [JwPlayerItemCreate]()
        guard let seasonData = vm.seasonListingData.filter({$0.id == vm.episodeSelectedCateogory}).first else{return}
        var url = String()
        guard let englishData = seasonData.seasonMoreDetails?.filter({$0.languageMasterID == 1}).first, let hindiData = seasonData.seasonMoreDetails?.filter({$0.languageMasterID == 2}).first else{return}
        
        if let seasonID = seasonData.id , let catID = vm.categoryID{
            PersistentStorage.shared.addWebSeries(catID: catID, postID: seasonID, postType: .season)
        }
        /*
         Based on selected Category language update the url
         */
        if vm.categoryID == 1{ //1- english , 18 - hindi
            url = englishData.trailerHDURL ?? ""
        }else{
            url = hindiData.trailerHDURL ?? ""
        }
        
        /*
         Based on language change the title
         */
        if AuthFunc.shareInstance.languageSelected == .english{
            playerItems.append(JwPlayerItemCreate(url: url, poster: seasonData.thumbnailPath, titles: englishData.title))
        }else{
            playerItems.append(JwPlayerItemCreate(url: url, poster: seasonData.thumbnailPath, titles: hindiData.title))
        }
        
        JWPlayerManager.shared.presentPlayer(from: self, playerItems: playerItems, startIndex: 0, contentType: .trailer, videoIDs: [0])
    }
    
    @IBAction func loadMoreBtnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addOthersCount()
        loadMoreBtn.isHidden = true
        vm.pageNo += 1
        loadMoreActivityIndicator.startAnimating()
        vm.getSeasonEpisode()
    }
    
    @IBAction func retryBtnTapped(_ sender: LocalisedElementsButton) {
        vm.getSeasonListing()
    }
    
}

// MARK: - TableView DataSource , Delegates

extension WebSeriesSeasonVC : TableViewSRC{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch tableView{
        case episodeTableView:
            return vm.seasonEpisodeData.count
        case teaserTableView:
            return vm.teaserData.count
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: K.CellIdentifier.WebSeries.webSeriesEpisodeCell) as! WebSeriesEpisodeCell
        switch tableView{
        case episodeTableView:
            let data = vm.seasonEpisodeData[indexPath.row]
            cell.setData(data: data)
        case teaserTableView:
            let data = vm.teaserData[indexPath.row]
            cell.setTeaserData(data: data)
        default:
            break
        }
        
        cell.btnTapped = { [self] () -> Void in

            var playerItems = [JwPlayerItemCreate]()
            
            switch tableView{
            case self.teaserTableView:
                let teaserData = vm.teaserData[indexPath.row]
                
                if let showID = teaserData.id, let catID = self.vm.categoryID{
                    PersistentStorage.shared.addWebSeries(catID: catID, postID: showID, postType: .teaser)
                }
                
                guard let englishData = teaserData.contentMoreDetails?.filter({$0.languageMasterID == 1}).first, let hindiData = teaserData.contentMoreDetails?.filter({$0.languageMasterID == 2}).first else{return}
                var url = String()
                /*
                 Based on selected Category language update the url
                 */
                if vm.categoryID == 1{ //1- english , 18 - hindi
                    url = englishData.contentHDURL ?? ""
                }else{
                    url = hindiData.contentHDURL ?? ""
                }
                
                /*
                 Based on language change the title
                 */
                if AuthFunc.shareInstance.languageSelected == .english{
                    playerItems.append(JwPlayerItemCreate(url: url, poster: teaserData.thumbnailPath, titles: englishData.title))
                }else{
                    playerItems.append(JwPlayerItemCreate(url: url, poster: teaserData.thumbnailPath, titles: hindiData.title))
                }
                
                JWPlayerManager.shared.presentPlayer(from: self, playerItems: playerItems, startIndex: indexPath.row, contentType: .trailer, videoIDs: [0])
            case self.episodeTableView:
                
                let episodeData = vm.seasonEpisodeData
                
                if let showID = episodeData[indexPath.row].id, let catID = self.vm.categoryID{
                    PersistentStorage.shared.addWebSeries(catID: catID, postID: showID, postType: .episode)
                }
                var videoIDs = [Int]()
                
                for i in episodeData{
                    var url = String()
                    guard let englishData = i.contentMoreDetails?.filter({$0.languageMasterID == 1}).first, let hindiData = i.contentMoreDetails?.filter({$0.languageMasterID == 2}).first else{return}
                    
                    if let id = i.id{
                        videoIDs.append(id)
                    }
                    /*
                     Based on selected Category language update the url
                     */
                    if vm.categoryID == 1{ //1- english , 18 - hindi
                        url = englishData.contentHDURL ?? ""
                    }else{
                        url = hindiData.contentHDURL ?? ""
                    }
                    
                    /*
                     Based on language change the title
                     */
                    if AuthFunc.shareInstance.languageSelected == .english{
                        playerItems.append(JwPlayerItemCreate(url: url, poster: i.thumbnailPath, titles: englishData.title))
                    }else{
                        playerItems.append(JwPlayerItemCreate(url: url, poster: i.thumbnailPath, titles: hindiData.title))
                    }
                }
                
                JWPlayerManager.shared.presentPlayer(from: self, playerItems: playerItems, startIndex: indexPath.row, contentType: .webSeries, videoIDs: videoIDs, catID: vm.categoryID)
            default:
                break
            }
            
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let sb = UIStoryboard(name: K.StoryBoard.webSeries, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.WebSeries.episodeDetailsVC) as! EpisodeDetailsVC

        switch tableView{
        case teaserTableView:
            let data = vm.teaserData[indexPath.row]
            if let showID = data.id, let catID = self.vm.categoryID{
                PersistentStorage.shared.addWebSeries(catID: catID, postID: showID, postType: .teaser)
            }
            vcPush.teaserData = data
        default:
            let data = vm.seasonEpisodeData[indexPath.row]
            if let showID = data.id, let catID = self.vm.categoryID{
                PersistentStorage.shared.addWebSeries(catID: catID, postID: showID, postType: .episode)
            }
            vcPush.episodeData = data
        }
        vcPush.onDoneBlock = { [weak self] in
            guard let self else{return}
            var playerItems = [JwPlayerItemCreate]()
            switch tableView{
            case self.teaserTableView:
                let teaserData = vm.teaserData[indexPath.row]
                
                guard let englishData = teaserData.contentMoreDetails?.filter({$0.languageMasterID == 1}).first, let hindiData = teaserData.contentMoreDetails?.filter({$0.languageMasterID == 2}).first else{return}
                var url = String()
                /*
                 Based on selected Category language update the url
                 */
                if vm.categoryID == 1{ //1- english , 18 - hindi
                    url = englishData.contentHDURL ?? ""
                }else{
                    url = hindiData.contentHDURL ?? ""
                }
                
                /*
                 Based on language change the title
                 */
                if AuthFunc.shareInstance.languageSelected == .english{
                    playerItems.append(JwPlayerItemCreate(url: url, poster: teaserData.thumbnailPath, titles: englishData.title))
                }else{
                    playerItems.append(JwPlayerItemCreate(url: url, poster: teaserData.thumbnailPath, titles: hindiData.title))
                }
                JWPlayerManager.shared.presentPlayer(from: self, playerItems: playerItems,startIndex: indexPath.row, contentType: .trailer, videoIDs: [0])
            case self.episodeTableView:
                let episodeData = vm.seasonEpisodeData
                var videoIDs = [Int]()
                for i in episodeData{
                    var url = String()
                    if let id = i.id{
                        videoIDs.append(id)
                    }
                    
                    guard let englishData = i.contentMoreDetails?.filter({$0.languageMasterID == 1}).first, let hindiData = i.contentMoreDetails?.filter({$0.languageMasterID == 2}).first else{return}
                    /*
                     Based on selected Category language update the url
                     */
                    if vm.categoryID == 1{ //1- english , 18 - hindi
                        url = englishData.contentHDURL ?? ""
                    }else{
                        url = hindiData.contentHDURL ?? ""
                    }
                    
                    /*
                     Based on language change the title
                     */
                    if AuthFunc.shareInstance.languageSelected == .english{
                        playerItems.append(JwPlayerItemCreate(url: url, poster: i.thumbnailPath, titles: englishData.title))
                    }else{
                        playerItems.append(JwPlayerItemCreate(url: url, poster: i.thumbnailPath, titles: hindiData.title))
                    }
                }
                
                JWPlayerManager.shared.presentPlayer(from: self, playerItems: playerItems, startIndex: indexPath.row, contentType: .webSeries, videoIDs: videoIDs,catID: vm.categoryID)
            default:
                break
            }
            
        }
        
        vcPush.modalPresentationStyle = .overCurrentContext
        vcPush.modalTransitionStyle = .crossDissolve
        self.present(vcPush, animated: true)
    }
}

// MARK: - CollectionView Delegate

extension WebSeriesSeasonVC : CollectionViewSRC{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return vm.seasonListingData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.CellIdentifier.WebSeries.seasonCategoryCell, for: indexPath) as! SeasonCategoryCell
        
        let data = vm.seasonListingData[indexPath.row]
        cell.setData(title: data.seasonNumber ?? "Season", iselected: data.id == vm.episodeSelectedCateogory)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let seasonID = vm.seasonListingData[indexPath.row].id , let catID = vm.categoryID{
            PersistentStorage.shared.addWebSeries(catID: catID, postID: seasonID, postType: .season)
        }
        
        if vm.episodeSelectedCateogory == vm.seasonListingData[indexPath.row].id{
            return
        }
        vm.episodeSelectedCateogory = vm.seasonListingData[indexPath.row].id
                
        vm.setSeasonData()
        episodeTitle.isHidden = false
        episodeTitle.text = ""
        vm.pageNo = 0
        vm.getSeasonEpisode()
        vm.getTeaserListing()
        self.categoryCV.reloadData()
    }
}

// MARK: - Collection Flow Layout

extension WebSeriesSeasonVC : UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // Generate a random string for testing purposes
        let randomText = vm.seasonListingData[indexPath.row].seasonNumber!

        // 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)
    }

}
