//
//  MusicEmptyView.swift
//  PhysicalWallPaper
//
//  Created by nkl on 2024/11/13.
//

import BetterSegmentedControl
import Combine
import Foundation
import GoogleMobileAds
import KLTips
import TSVideoKit
import UIKit

class SongListViewController: LWBGViewController {
    private var cancellables: [AnyCancellable] = []

    var viewModel: SongListViewModel = SongListViewModel()

    lazy var emptyView: MusicEmptyView = {
        let empty = MusicEmptyView(title: "No Music".localized(), algin: .top)
        empty.isHidden = true
        empty.jumpBtn.addTarget(self, action: #selector(emptyButtonAction), for: .touchUpInside)
        return empty
    }()

    lazy var manageButton: UIButton = {
        let bt = UIButton(frame: CGRect(x: 0, y: 0, width: 42, height: 42))
        bt.backgroundColor = UIColor.white.withAlphaComponent(0.1)
        bt.setImage(.icPlaylistMore, for: .normal)
        bt.customCornerRadius = 20
        bt.backgroundColor = .white
        bt.addTarget(self, action: #selector(showMenuAlert), for: .touchUpInside)
        return bt
    }()

    lazy var menuView: ManageMenuAlertView = {
        let mView = ManageMenuAlertView()
        mView.addTarget(self, action: #selector(dismissAlert(sender:)), for: .touchUpInside)
        mView.sortButton.addTarget(self, action: #selector(showSortOperateView), for: .touchUpInside)
        mView.manageButton.addTarget(self, action: #selector(showManageViewController), for: .touchUpInside)
        return mView
    }()

    lazy var listView: UITableView = {
        let tabView = UITableView()
        tabView.dataSource = viewModel
        tabView.delegate = self
        tabView.separatorStyle = .none
        tabView.register(SongListCell.self, forCellReuseIdentifier: "SongListCell")
        tabView.register(SongDownloadCell.self, forCellReuseIdentifier: "SongDownloadCell")
        tabView.backgroundColor = .clear
        tabView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 80, right: 0)

        return tabView
    }()

    //    lazy var guideBubble: GuideBubbleView = {
    //        let guide = GuideBubbleView()
    //        guide.addTarget(self, action: #selector(dismissGuideBubble), for: .touchUpInside)
    //        guide.tapArea.addTarget(self, action: #selector(bubbleClick), for: .touchUpInside)
    //        return guide
    //    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        bgImageView.image = nil
        navigationController?.navigationBar.isHidden = true
        navigationItem.leftBarButtonItems?.removeAll()
        viewModel.requestData()
        addNotifaction()
        
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
        listView.addGestureRecognizer(longPressGesture)        
    }

    override func addNotifaction() {
        super.addNotifaction()

        viewModel.$videos.receive(on: DispatchQueue.main).sink { [weak self] _ in
            guard let self = self else {
                return
            }
            self.emptyView.isHidden = !viewModel.isEmptyData
            self.listView.reloadData()
        }.store(in: &cancellables)

        NotificationCenter.default.addObserver(self, selector: #selector(reloadDatas), name: .K_ImportSuccessNotifaction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(reloadDatas), name: kDataChangedNotifactionName, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(reloadDatas), name: .K_RefreshNotifaction, object: nil)
    }

    //    @objc func bubbleClick() {
    //        showSearchViewController()
    //        dismissGuideBubble()
    //    }
    //
    //    @objc func dismissGuideBubble() {
    //        guideBubble.isHidden = true
    //        UserDefaults.standard.setValue("Guide", forKey: "GuideKey")
    //    }

    @objc func showMenuAlert() {
        if !view.contains(menuView) {
            view.addSubview(menuView)
            menuView.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.horizontalEdges.equalToSuperview()
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            }
        }
    }

    @objc func showManageViewController() {
        menuView.removeFromSuperview()
    }

    @objc func dismissAlert(sender: UIControl) {
        sender.removeFromSuperview()
    }

    @objc func reloadDatas() {
        viewModel.requestData()
    }

    override func addChildren() {
        super.addChildren()
        view.addSubview(listView)
        view.addSubview(emptyView)
    }

    @objc func showFavourtie() {
//        ADManager.shared.showAd(scene: ADScene.playlist, from: self) { state in
//            if state == .finished || state == .fail {
        let vModel: PlayListDetaiViewModel = .init()
        vModel.listType = .favourite
        let vc = PlaylistDetailViewController(viewModel: vModel)
        vc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(vc, animated: true)
//            }
//        }
    }

    @objc func showPlaylist() {
        let vc = PlaylistViewController()
        navigationController?.pushViewController(vc, animated: true)
    }

    @objc func showRecentlyList() {
        let vModel: PlayListDetaiViewModel = .init()
        vModel.listType = .recently
        let vc = PlaylistDetailViewController(viewModel: vModel)
        vc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(vc, animated: true)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        PlayerManager.shared.miniBar.isHidden = false
        PlayerManager.shared.rootVc?.moveUpMiniBar()
    }

    override func makeConstarints() {
        super.makeConstarints()

        listView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.top.equalToSuperview()
        }
        emptyView.snp.makeConstraints { make in
            make.edges.equalTo(listView)
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
//        print("TSConfiguration.isYs ===" , TSConfiguration.isYs)
//        if UserDefaults.standard.string(forKey: "GuideKey") == nil, TSConfiguration.isYs {
//            view.addSubview(guideBubble)
//            view.bringSubviewToFront(guideBubble)
//            guideBubble.snp.makeConstraints { make in
//                make.edges.equalToSuperview()
//            }
//        }
    }

    @objc func showSortOperateView() {
        menuView.removeFromSuperview()
        let vc = SortMenuViewController(type: viewModel.sortType)
        vc.modalPresentationStyle = .overFullScreen
        vc.didSelectedSortType = { type in
            self.viewModel.sortType = type
            self.viewModel.requestData()
        }
        present(vc, animated: true)
    }
}

extension SongListViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if indexPath.row < viewModel.unFinishedVideo.count {
                let vModel = viewModel.unFinishedVideo[indexPath.row]
                switch vModel.state {
                case .pause:
                    vModel.resumeDownload()
                default:
                    THUD.toast("Downloading".localized())
                    break
                }
            }
        } else {
            print("indexPath.row == \(indexPath.row) , count = \(viewModel.videos.count) ")
            if indexPath.row < viewModel.videos.count {
                let video = viewModel.videos[indexPath.row]
//                /// 多选模式 禁止点击
//                if viewModel.isMutiSelectModel {
//                    viewModel.addToSelectedList(video: video)
//                    listView.reloadData()
//                } else {
                PlayerManager.shared.playVideo(video: video, list: viewModel.videos, scene: .local, onceAdKey: "MinePlayVideo")
//                }
            }
        }
    }

    @objc func emptyButtonAction() {
        if TSConfiguration.isYs {
            let vc = SearchOnlineViewController()
            navigationController?.pushViewController(vc, animated: true)
        } else {
            ImportFilesManager.shared.openPhotoLibrary(parent: self)
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        menuView.removeFromSuperview()
    }
}
