//
//  PlaylistViewController.swift
//  ColorfulWallpaper
//
//  Created by ni on 2024/9/18.
//

import Combine
import Foundation
import TSVideoKit

class PlaylistViewController: LWBGViewController, UITableViewDelegate {
    var viewModel: PlayListViewModel = .init()

    lazy var listView: UITableView = {
        let tabView = UITableView()
        tabView.dataSource = viewModel
        tabView.delegate = self
        tabView.separatorStyle = .none
        tabView.register(PlayListCell
            .self, forCellReuseIdentifier: "PlayListCell")
        tabView.register(PlayListAddCell.self, forCellReuseIdentifier: "PlayListAddCell")
        tabView.register(PlayListFavouriteCell.self, forCellReuseIdentifier: "PlayListFavouriteCell")
        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 = nil
        navigationController?.navigationBar.isHidden = true
        addNotifaction()
    }

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

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }

    override func addNotifaction() {
        super.addNotifaction()

        viewModel.$playLists.receive(on: DispatchQueue.main).sink { _ in
            self.reloadListData()
        }.store(in: &canncellable)

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

    }

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

    func reloadListData() {
        listView.reloadData()
    }

    func newPlaylist() {
        let alertVC = UIAlertController(title: nil, message: "Playlist Name".localized(), preferredStyle: .alert)
        alertVC.addTextField { textField in
            textField.placeholder = "input name".localized()
            textField.font = UIFont.systemFont(ofSize: 16)
        }
        let ok = UIAlertAction(title: "OK".localized(), style: .default) { [weak self] _ in
            if let name = alertVC.textFields?.first?.text, !name.isEmpty {
                self?.viewModel.creatPlayList(name: name) { listid in
                    if let id = listid {
                        self?.didFinishedCreatedPlaylist(id: id)
                    }
                }
            }
        }
        let cancel = UIAlertAction(title: "Cancel".localized(), style: .cancel)
        alertVC.addAction(cancel)
        alertVC.addAction(ok)
        present(alertVC, animated: true)
    }

    func didFinishedCreatedPlaylist(id: UUID) {
    }

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

    override func makeConstarints() {
        super.makeConstarints()

        listView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.bottom.leading.trailing.equalToSuperview()
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            newPlaylist()
        } else if indexPath.section == 1 {
            showLikeViewController()
        } else {
//            ADManager.shared.showAd(scene: ADScene.playlist, from: self) { state in
//                if state == .finished || state == .fail {
//                    if indexPath.row < self.viewModel.playLists.count {
            let list = viewModel.playLists[indexPath.row]
            let vModel: PlayListDetaiViewModel = .init()
            vModel.playlist = list
            vModel.listType = .playlist
            let vc = PlaylistDetailViewController(viewModel: vModel)
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
//                    }
//                }
//            }
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
        canncellable.removeAll()
    }
}
