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

import UIKit
import JWPlayerKit
import AVFoundation

class KaraokeDetailsVC: UIViewController {
    
    @IBOutlet weak var watchingImage: UIImageView!
    @IBOutlet weak var watchingTitle: UILabel!
    @IBOutlet weak var watchingDesc: UITextView!
    @IBOutlet weak var releaseDate: UILabel!
    
    @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 singNowBtn: LocalisedElementsButton!
    
    @IBOutlet weak var outerView: UIView!
    @IBOutlet weak var contentView: UIView!
    
    var karaokeData : KaraokeListingDM.KaraokeDatum?
//    var delegate : ReloadAudioBooksFavLike?
    
    var delegate : ReloadSeriesFavLike?

    var karaokeIndex = 0
    
    typealias btnTappedBlock = ( _ from : FavCellCLick) -> Void 
    var btnTapped : btnTappedBlock?
    
    var reloadType : FavCellCLick?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
        tapHandler()
        
        singNowBtn.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor
        singNowBtn.layer.shadowOffset = CGSize(width: 0, height: 3)
        singNowBtn.layer.shadowOpacity = 1.0
        singNowBtn.layer.shadowRadius = 10.0
        singNowBtn.layer.masksToBounds = false
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        outerView.addGestureRecognizer(tapGesture)
    }
    
    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: outerView)
        if !contentView.frame.contains(location) {
            if let karaokeData , let postID = karaokeData.id{
                PersistentStorage.shared.addKaraokeCount(postID: postID)
            }
            
            if let reloadType{
                if btnTapped != nil {
                    btnTapped?(reloadType)
                }
            }
            self.dismiss(animated: true)
        }
    }
    
    func initView(){
        if let karaokeData{
            if let url = karaokeData.thumbnailPath{
                watchingImage.imageURL(url, color: .white)
            }
            
            totalLikes.text = karaokeData.likesCount?.toString() ?? "0"
            
            if let releaseDate = karaokeData.releaseDate{
                if let formatDate = DateFormatterLib.dateMods(dateStr: releaseDate, dateCurrentFormat: .yyyy_MM_dd_HH_mm_ss, dateReturnFormat: .yyyy, stringOrDate: .string).0{
                    self.releaseDate.text = formatDate
                }
            }
            
            if let like = karaokeData.isLiked{
                switch like{
                case true:
                    likeIcon.image = UIImage(systemName: "hand.thumbsup.fill")
                    likeLabel.text = "LIKED".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                case false:
                    likeIcon.image = UIImage(systemName: "hand.thumbsup")
                    likeLabel.text = "LIKE".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                }
            }
            
            if let favourite = karaokeData.markAsFavourite{
                if favourite == true{
                    addIcon.image = UIImage(systemName: "heart.fill")
                    addLabel.text = "ADDED".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                }else{
                    addIcon.image = UIImage(systemName: "heart")
                    addLabel.text = "ADD".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                }
            }
            
            if AuthFunc.shareInstance.getDefaultLanguage() == .english{
                if let englishData = karaokeData.contentMoreDetails?.filter({$0.languageMasterID == 1}).first{
                    watchingTitle.text = englishData.title
                    if let desc = englishData.description?.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
                        let sizeText = NSMutableAttributedString(attributedString: desc)
                        sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 15),color: UIColor.appColor(.TextDarkBlue)!)
                        self.watchingDesc.attributedText = sizeText
                    }
                }
            }else{
                if let hindiData = karaokeData.contentMoreDetails?.filter({$0.languageMasterID == 2}).first{
                    watchingTitle.text = hindiData.title
                    if let desc = hindiData.description?.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
                        let sizeText = NSMutableAttributedString(attributedString: desc)
                        sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 15),color: UIColor.appColor(.TextDarkBlue)!)
                        self.watchingDesc.attributedText = sizeText
                    }
                }
            }
        }
    }
    
    func tapHandler(){
        
        addView.addTapGesture { [weak self] in
            if AuthFunc.shareInstance.guestUserLoginPopUp() { return}

            guard let self else{return}
            
            if let karaokeData{
                guard  let showID = karaokeData.id, let isFav = karaokeData.markAsFavourite, let postType = karaokeData.contentMoreDetails?.first?.postType else{return}

                PersistentStorage.shared.addKaraokeCount(postID: showID)
                if isFav {
                    LikeFavCommonFunc.shareInstance.removeFavourite(postID: showID, postType: postType, categoryID: 0, vc: self) { isDone in
                        self.karaokeData?.markAsFavourite = false
                        
//                        if let index = MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.firstIndex(where: {$0.id == showID}){
//                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.remove(at: index)
//                            K.GVar.myListSoftReload = true
//                        }
                        K.GVar.reloadKaraoke = true
                        self.reloadType = .favourite
                        //if coming from mylist
                        self.delegate?.updateRows(index: self.karaokeIndex, type: .favourite, isFav: false, isLike: nil, id: showID)
                        self.initView()
                    }
                }else{
                    LikeFavCommonFunc.shareInstance.addFavourite(postID: showID, postType: postType, categoryID: 0, vc: self) { isDone in
                        self.karaokeData?.markAsFavourite = true
                        
//                        if let karaokeData = self.karaokeData{
//                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.append(karaokeData)
//                            K.GVar.myListSoftReload = true
//                        }
                        K.GVar.reloadKaraoke = true
                        self.reloadType = .favourite
                        //if coming from mylist
                        self.delegate?.updateRows(index: self.karaokeIndex, type: .favourite, isFav: true, isLike: nil, id: showID)
                        self.initView()
                    }
                }
            }
        }
        
        likeView.addTapGesture { [weak self] in
            if AuthFunc.shareInstance.guestUserLoginPopUp() { return}

            guard let self else{return}
            
            if let karaokeData{
                guard let showID = karaokeData.id, let isLiked = karaokeData.isLiked, let postType = karaokeData.contentMoreDetails?.first?.postType else{return}
                PersistentStorage.shared.addKaraokeCount(postID: showID)

                if isLiked{
                    LikeFavCommonFunc.shareInstance.unlikePost(postID: showID, postType: postType, vc: self) { isDone in
                        self.karaokeData?.isLiked = false
                        self.karaokeData?.likesCount! -= 1
                        if let index = MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?[index].isLiked = false
                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?[index].likesCount! -= 1
                            K.GVar.myListSoftReload = true
                        }
                        self.reloadType = .liked
                        self.delegate?.updateRows(index: self.karaokeIndex, type: .liked, isFav: nil, isLike: false, id: showID)

                        self.initView()
                    }
                }else{
                    LikeFavCommonFunc.shareInstance.likePost(postID: showID, postType: postType, vc: self) { isDone in
                        self.karaokeData?.isLiked = true
                        self.karaokeData?.likesCount! += 1
                        
                        if let index = MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?[index].isLiked = true
                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?[index].likesCount! += 1
                            K.GVar.myListSoftReload = true
                        }
                        self.reloadType = .liked
                        self.delegate?.updateRows(index: self.karaokeIndex, type: .liked, isFav: nil, isLike: true, id: showID)
                        self.initView()
                    }
                }
            }
        }
        
        shareView.addTapGesture { [weak self] in
            guard let self else{return}
            
            if let karaokeData, let showID = karaokeData.id{
                PersistentStorage.shared.addKaraokeCount(postID: showID)
            }

            if let name = URL(string: "https://apps.apple.com/in/app/woka/id6465305185"), !name.absoluteString.isEmpty {
              let objectsToShare = [name]
              let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
                self.present(activityVC, animated: true, completion: nil)
            } else {
              // show alert for not available
            }
        }
    }
    
    @IBAction func playNowBtnTapped(_ sender: LocalisedElementsButton) {
        
//        let sb = UIStoryboard(name: K.StoryBoard.Karaoke, bundle: nil)
//        let vcPush = sb.instantiateViewController(withIdentifier: "AVPlayerTesting") as! AVPlayerTesting
//        self.present(vcPush, animated: true)
//        return
        
        var itemBuild = JwPlayerItemCreate(url: "")
        var mp4URL = String()
        
        guard let postID = karaokeData?.id else{return}
        PersistentStorage.shared.addKaraokeCount(postID: postID)

        
        if AuthFunc.shareInstance.getDefaultLanguage() == .english{
            if let englishData = karaokeData?.contentMoreDetails?.filter({$0.languageMasterID == 1}).first{
                guard let url = englishData.url , let title = englishData.title, let englishMp4URL = englishData.videoUrlHd else{return}
                mp4URL = englishMp4URL
                itemBuild = JwPlayerItemCreate(url: url, poster: karaokeData?.thumbnailPath, titles: title)
            }
        }else{
            if let hindiData = karaokeData?.contentMoreDetails?.filter({$0.languageMasterID == 2}).first{
                guard let url = hindiData.url , let title = hindiData.title , let hindiMp4URL = hindiData.videoUrlHd else{return}
                mp4URL = hindiMp4URL
                itemBuild = JwPlayerItemCreate(url: url, poster: karaokeData?.thumbnailPath, titles: title)
            }
        }
        
        DispatchQueue.main.async { [weak self] in
            guard let self else{return}
            Utilities.startProgressHUD()
            FileManager.default.clearTmpDirectory()
            let sb = UIStoryboard(name: K.StoryBoard.Karaoke, bundle: nil)
            let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Karaoke.jwKaraokePlayerVC) as! JWKaraokePlayerVC
            do {
                
                // Create a JWPlayerItem
                let item = try JWPlayerItemBuilder()
                    .file(URL(string: itemBuild.url)!)
                    .posterImage(URL(string: itemBuild.poster ?? "")!)
                    .title(itemBuild.titles ?? "Karaoke")
                    .build()
                
                // Create a JWPlayerConfiguration
                let config = try JWPlayerConfigurationBuilder()
                    .playlist(items: [item])
                    .autostart(true)
                    .build()
                
                vc.config = config
                vc.vm.videoTitle = itemBuild.titles
                vc.vm.videoUrl = mp4URL
                vc.vm.postID = postID
                vc.modalPresentationStyle = .overFullScreen
                vc.modalTransitionStyle = .crossDissolve
//                vc.documentAudioUrl = url
                Utilities.dismissProgressHUD()
                // Present the PlayerVC
                self.present(vc, animated: true)
            } catch {
                print("Error creating JWPlayer configuration: \(error)")
                Utilities.dismissProgressHUD()
            }
            
            // Dismiss the progress HUD after the view controller presentation
            Utilities.dismissProgressHUD()
            
        }        

    }

    @IBAction func closeBtnTapped(_ sender: UIButton) {
        PersistentStorage.shared.addOthersCount()
        if let reloadType{
            if btnTapped != nil {
                btnTapped?(reloadType)
            }
        }
        self.dismiss(animated: true)
    }
}
