//
//  FilterBarViewController.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/10.
//

import Combine
import Foundation
import TSVideoKit

protocol FilterBarViewControllerDelegate: AnyObject {
    /// 全选video回调
    /// - Parameter videos: selectedVideos
    func selectedAllVideo()
    
    /// 完成管理
    /// - Parameter videos: selectedVideos
    func doneMutiManage()

    /// 是否进入多选状态
    /// - Parameter barType: 视图type切换回调
    func topBarTypeDidChange(barType: MineRingTopType)

    /// 排序规则改变回调
    /// - Parameter sortType: 排序类型
    func sortTypeDidChange(sortType: SortType)

    /// 本地搜索回调
    /// - Parameter
    func localSearchDidClicked()
}

class FilterBarViewController: UIViewController {
    lazy var topHeader: FilterBarView = FilterBarView()
    var viewModel: FilterBarViewModel?
    weak var delegate: FilterBarViewControllerDelegate?
    var needSearch: Bool = true

    private var cancellables: [AnyCancellable] = []

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

    override func viewDidLoad() {
        super.viewDidLoad()
        addChildren()
        makeConstraints()
        addNotifaction()
    }

    func addNotifaction() {
        viewModel?.$selectedVideos.receive(on: DispatchQueue.main).sink { videos in
            PlayerManager.shared.selectedVideos = videos
            PlayerManager.shared.removePlaylist = self.viewModel?.playlist
            self.updateBarInfo()
        }.store(in: &cancellables)

        viewModel?.$barType.receive(on: DispatchQueue.main).sink { type in
            self.updateBarInfo()
            self.topHeader.type = type
            if type == .mutiselect {
                self.topHeader.searchButton.isHidden = true
            } else {
                self.topHeader.searchButton.isHidden = !self.needSearch
            }

            self.delegate?.topBarTypeDidChange(barType: type)
        }.store(in: &cancellables)

        viewModel?.$sortType.receive(on: DispatchQueue.main).sink { sortType in
            self.updateBarInfo()
            self.delegate?.sortTypeDidChange(sortType: sortType)
        }.store(in: &cancellables)
    }

    func updateBarInfo() {
        guard let viewModel = viewModel else { return }
        topHeader.playButton.setTitle(viewModel.playTitle, for: .normal)
        topHeader.selectButton.setTitle(viewModel.selectTitle, for: .normal)
        topHeader.selectButton.isSelected = viewModel.selectedVideos.count == viewModel.videos.count
        if viewModel.sortType == .downName || viewModel.sortType == .downTime {
            topHeader.sortButton.setImage(UIImage(named: "ic_mine_ring_sort_down"), for: .normal)
        } else {
            topHeader.sortButton.setImage(UIImage(named: "ic_mine_ring_sort_up"), for: .normal)
        }
    }

    func addChildren() {
        view.addSubview(topHeader)
        addTargets()
    }

    func addTargets() {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(playAllMusic))
        topHeader.playIcon.addGestureRecognizer(gesture)
        topHeader.playButton.addTarget(self, action: #selector(playAllMusic), for: .touchUpInside)
        topHeader.mutiButton.addTarget(self, action: #selector(mutiButtonClickEvent), for: .touchUpInside)
        topHeader.finishMutiButton.addTarget(self, action: #selector(mutiDoneButtonClicked), for: .touchUpInside)
        topHeader.selectButton.addTarget(self, action: #selector(selectAllVideos(sender:)), for: .touchUpInside)
        topHeader.sortButton.addTarget(self, action: #selector(showSortAlertController), for: .touchUpInside)
        topHeader.searchButton.addTarget(self, action: #selector(goToLocalSearch), for: .touchUpInside)
    }

    func addToSelectedList(video: TSVideo) {
        viewModel?.addToSelectedList(video: video)
    }

    func makeConstraints() {
        topHeader.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}

extension FilterBarViewController {
    @objc func showSortAlertController() {
        viewModel?.showSortOperateView(parent: self)
    }

    @objc func selectAllVideos(sender: UIButton) {
        delegate?.selectedAllVideo()
    }

    @objc func mutiButtonClickEvent() {
        guard let viewModel = viewModel else { return }
        viewModel.beginMutiSelect()
    }

    @objc func mutiDoneButtonClicked() {
        guard let viewModel = viewModel else { return }
        topHeader.selectButton.isSelected = false
        viewModel.doneMutiSelect()
        self.delegate?.doneMutiManage()
    }

    @objc func playAllMusic() {
        guard let viewModel = viewModel else { return }
        viewModel.playAllVideos()
    }

    @objc func goToLocalSearch() {
        delegate?.localSearchDidClicked()
    }
}
