//
//  PlaylistDetailViewController.swift
//  ColorfulWallpaper
//
//  Created by ni on 2024/9/19.
//

import Combine
import Foundation
import GoogleMobileAds
import TSVideoKit

class PlaylistDetailViewController: LWBGViewController, UITableViewDelegate {
    var viewModel: PlayListDetaiViewModel?

    lazy var navBar: LWSubNavigationBar = {
        let bar = LWSubNavigationBar()
        bar.backButton.addTarget(self, action: #selector(popupCurrentVc), for: .touchUpInside)
        return bar
    }()

    lazy var moreButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "ic_playlist_more"), for: .normal)
        btn.addTarget(self, action: #selector(moreButtonAction), for: .touchUpInside)
        return btn
    }()

    lazy var sortButton: UIButton = {
        let bt = UIButton(frame: CGRect(x: 0, y: 0, width: 42, height: 42))
        bt.backgroundColor = UIColor.white.withAlphaComponent(0.1)
        bt.setImage(.icNavSort, for: .normal)
        bt.customCornerRadius = 16
        bt.backgroundColor = .white
        bt.addTarget(self, action: #selector(showSortOperateView), for: .touchUpInside)

        return bt
    }()

    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(.icNavManage, for: .normal)
        bt.customCornerRadius = 16
        bt.backgroundColor = .white
        bt.addTarget(self, action: #selector(showManageViewController), for: .touchUpInside)
        return bt
    }()

    lazy var emptyView: MusicEmptyView = .init(algin: .center, needButton: false)
    lazy var filterVc: FilterBarViewController = {
        let vModel = FilterBarViewModel(videos: viewModel?.videos ?? [], barTyle: .default, selectedVideos: [], sortType: .downTime)
        vModel.isFromPlaylist = true
        vModel.playlist = viewModel?.playlist
        let top = FilterBarViewController(viewModel: vModel)
        top.needSearch = false
        top.delegate = self
        return top
    }()

    lazy var topView: SongListTopView = {
        let top = SongListTopView()
        top.playAllBtn.addTarget(self, action: #selector(playAllButtonAction), for: .touchUpInside)
        top.shuffleBtn.addTarget(self, action: #selector(shuffleButtonAction), for: .touchUpInside)
        return top
    }()

//    lazy var manageView: PlayListManageView = {
//        let manage = PlayListManageView()
//        manage.sortButton.addTarget(self, action: #selector(showSortOperateView), for: .touchUpInside)
//        manage.manageButton.addTarget(self, action: #selector(showManageViewController), for: .touchUpInside)
//        return manage
//    }()

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

    private var canncellable: [AnyCancellable] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        bgImageView.image = .viewMainBg

        switch viewModel?.listType {
        case .favourite:
            navBar.titleLabel.text = "Like".localized()
            moreButton.isHidden = true
            manageButton.isHidden = true
        case .recently:
            navBar.titleLabel.text = "Recently".localized()
            moreButton.isHidden = true
            manageButton.isHidden = true
        case .playlist:
            navBar.titleLabel.text = viewModel?.playlist?.title
            moreButton.isHidden = false
            manageButton.isHidden = false
        case nil:
            navBar.titleLabel.text = viewModel?.playlist?.title
            moreButton.isHidden = false
            manageButton.isHidden = true
        }
    }

    convenience init(viewModel: PlayListDetaiViewModel) {
        self.init()
        self.viewModel = viewModel
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        PlayerManager.shared.rootVc?.moveDownMiniBar()
        viewModel?.requestData()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        filterVc.viewModel?.doneMutiSelect()
    }

    override func addNotifaction() {
        super.addNotifaction()
        viewModel?.$videos.receive(on: DispatchQueue.main).sink(receiveValue: { [weak self] _ in
            guard let self = self else {
                return
            }
            self.emptyView.isHidden = self.viewModel?.videos.isEmpty == false
            self.refreshViews()
        }).store(in: &canncellable)

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

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

    @objc func moreButtonAction() {
        // 创建 UIAlertController，样式为 actionSheet
        let alert = UIAlertController()

        // 添加第一个选项
        let option1 = UIAlertAction(title: "Rename".localized(), style: .default) { [weak self] _ in
            guard let self = self else { return }
            if let mPlaylist = self.viewModel?.playlist {
                CWOperateViewController.renamePlaylist(playlist: mPlaylist) { name in
                    self.navBar.titleLabel.text = name
                }
            }
        }
        alert.addAction(option1)

        // 添加第二个选项
        let option2 = UIAlertAction(title: "Delete Playlist".localized(), style: .destructive) { [weak self] _ in
            guard let self = self else { return }
            if let mPlaylist = self.viewModel?.playlist {
                CWOperateViewController.deletePlaylist(playlist: mPlaylist) {
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
        alert.addAction(option2)

        // 添加取消按钮
        let cancelAction = UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil)
        alert.addAction(cancelAction)

        // 弹出弹窗
        PlayerManager.shared.rootVc?.present(alert, animated: true, completion: nil)
    }

    @objc func playAllButtonAction() {
        guard let mViewModel = viewModel else {
            return
        }
        if let firstVideo = mViewModel.videos.first {
            PlayerManager.shared.player?.playControl.viewModel.loopMode = .cyclic
            PlayerManager.shared.playVideo(video: firstVideo, list: mViewModel.videos, scene: .local, onceAdKey: "PlaylistDetail_PlayAll")
            listView.reloadData()
        }
    }

    @objc func shuffleButtonAction() {
        guard let mViewModel = viewModel else {
            return
        }
        if let firstVideo = mViewModel.videos.randomElement() {
            PlayerManager.shared.player?.playControl.viewModel.loopMode = .random
            PlayerManager.shared.playVideo(video: firstVideo, list: mViewModel.videos, scene: .local, onceAdKey: "PlaylistDetail_Shuffle")
            listView.reloadData()
        }
    }

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

    @objc func showManageViewController() {
    }

    func refreshViews() {
        if viewModel?.videos.isEmpty == true {
            filterVc.view.isHidden = true
        } else {
            filterVc.view.isHidden = false
        }
        filterVc.viewModel?.selectedVideos = []
        filterVc.viewModel?.videos = viewModel?.videos ?? []
        filterVc.updateBarInfo()
        filterVc.mutiDoneButtonClicked()
        listView.reloadData()
        resetViews()
    }

    override func addChildren() {
        super.addChildren()
        addChild(filterVc)
        view.addSubview(navBar)
        view.addSubview(filterVc.view)
        filterVc.didMove(toParent: self)

//        navBar.appendRightItem(item: sortButton)
//        navBar.appendRightItem(item: manageButton)
//        navBar.appendRightItem(item: moreButton)

//        view.addSubview(topView)
        view.addSubview(listView)
        view.addSubview(emptyView)
    }

    override func makeConstarints() {
        super.makeConstarints()
        navBar.snp.makeConstraints { make in
            make.height.equalTo(44)
            make.horizontalEdges.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
        }

//        topView.snp.makeConstraints { make in
//            make.horizontalEdges.equalToSuperview().inset(16)
//            make.top.equalTo(navBar.snp.bottom).offset(16)
//            make.height.equalTo(44)
//        }
        filterVc.view.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(navBar.snp.bottom)
            make.height.equalTo(40)
        }

        listView.snp.makeConstraints { make in
            make.top.equalTo(filterVc.view.snp.bottom).offset(12)
            make.bottom.leading.trailing.equalToSuperview()
        }
        emptyView.snp.makeConstraints { make in
            make.top.equalTo(navBar.snp.bottom)
            make.bottom.leading.trailing.equalToSuperview()
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let vM = viewModel, indexPath.row < vM.videos.count {
            let model = vM.videos[indexPath.row]
            if viewModel?.isMuti == true {
                vM.addToSelectedList(video: model)
                filterVc.viewModel?.selectedVideos = vM.selectedVideos
                listView.reloadData()
            } else {
                var key = viewModel?.playlist?.id?.uuidString ?? "DefaultPlaylist"
                if viewModel?.listType == .favourite {
                    key = "FavouritePlaylist"
                }
                PlayerManager.shared.playVideo(video: model, list: vM.videos, scene: .local, onceAdKey: key)
            }
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)

        canncellable.removeAll()
    }
}

extension PlaylistDetailViewController: FilterBarViewControllerDelegate {
    func selectedAllVideo() {
        guard let viewModel = viewModel else { return }
        if filterVc.viewModel?.selectedVideos.count == viewModel.videos.count {
            viewModel.selectedVideos = []
        } else {
            viewModel.selectedVideos = viewModel.videos
        }
        filterVc.viewModel?.selectedVideos = viewModel.selectedVideos
        listView.reloadData()
    }

    func doneMutiManage() {
        guard let viewModel = viewModel else { return }

        viewModel.selectedVideos = []
        filterVc.viewModel?.selectedVideos = viewModel.selectedVideos
        listView.reloadData()
    }

    func resetViews() {
        listView.snp.updateConstraints { make in
            if viewModel?.isMuti == true {
                make.bottom.equalToSuperview().offset(-(k_TabBar_Height + 62))
            } else {
                make.bottom.equalToSuperview()
            }
        }
        emptyView.snp.updateConstraints { make in
            if viewModel?.isMuti == true {
                make.bottom.equalToSuperview().offset(-(k_TabBar_Height + 62))
            } else {
                make.bottom.equalToSuperview()
            }
        }
    }

    func localSearchDidClicked() {
    }

    func topBarTypeDidChange(barType: MineRingTopType) {
        viewModel?.isMuti = barType == .mutiselect
        listView.reloadData()
        resetViews()
    }

    func sortTypeDidChange(sortType: SortType) {
        viewModel?.sortType = sortType
        viewModel?.requestData()
        if viewModel?.videos.isEmpty == false {
            listView.scrollToRow(at: .init(row: 0, section: 0), at: .top, animated: false)
        }
    }
}
