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

import Combine
import Foundation
import KLTips
import TSVideoKit

class AddPlayListViewController: LWBaseViewController, UITableViewDelegate {
    var viewModel: AddPlayListViewModel = .init()
    lazy var backView: UIView = .simpleView(color: .hexColor("#222222"))
    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.backgroundColor = .clear
        tabView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 80, right: 0)
        return tabView
    }()

    lazy var titleLabel: UILabel = .simpleLabel(text: "Add to playlist".localized(), font: .boldSystemFont18, color: .white)
    lazy var closeButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "ic-close"), for: .normal)
        btn.addTarget(self, action: #selector(dismissCurrent), for: .touchUpInside)
        return btn
    }()

    lazy var disappearArea: UIControl = .init()

    private var canncellable: [AnyCancellable] = []

    var addSuccessBlock: () -> Void = {}

    var video: TSVideo?
    var videos: [TSVideo] = []

    convenience init(video: TSVideo) {
        self.init()
        self.video = video
        viewModel.needMore = false
    }

    convenience init(videos: [TSVideo]) {
        self.init()
        self.videos = videos
        viewModel.needMore = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.isHidden = true
        addNotifaction()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        viewModel.requestData()
    }

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

    override func addNotifaction() {
        super.addNotifaction()

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

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

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

    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)
    }

    override func addChildren() {
        super.addChildren()
        disappearArea.backgroundColor = .black.withAlphaComponent(0.4)
        disappearArea.addTarget(self, action: #selector(dismissCurrent), for: .touchUpInside)
        backView.layer.cornerRadius = 16
        backView.layer.masksToBounds = true
        view.addSubview(disappearArea)
        view.addSubview(backView)
        backView.addSubview(titleLabel)
        backView.addSubview(closeButton)
        backView.addSubview(listView)
    }

    @objc func dismissCurrent() {
        dismiss(animated: true)
    }

    override func makeConstarints() {
        super.makeConstarints()
        disappearArea.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.bottom.equalTo(backView.snp.top)
        }
        backView.snp.makeConstraints { make in
            make.bottom.leading.trailing.equalToSuperview()
            make.height.equalToSuperview().multipliedBy(0.6)
        }

        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalToSuperview().offset(16)
            make.height.equalTo(54)
        }

        closeButton.snp.makeConstraints { make in
            make.width.height.equalTo(54)
            make.trailing.equalToSuperview()
            make.centerY.equalTo(titleLabel)
        }

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

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            newPlaylist()
        } else {
            if indexPath.row >= viewModel.playLists.count {
                return
            }
            let playList = viewModel.playLists[indexPath.row]
            if videos.isEmpty {
                addToPlayList(playlist: playList)
            } else {
                addVideosToPlaylist(playlist: playList)
            }
            reloadData()
        }
    }

    func didFinishedCreatedPlaylist(id: UUID) {
        if let playlist = TSVideoOperator.shared.dataManager.fetchPlaylist(id: id) {
            if videos.isEmpty {
                addToPlayList(playlist: playlist)
            } else {
                addVideosToPlaylist(playlist: playlist)
            }
        }
    }

    func addVideosToPlaylist(playlist: TSPlayList) {
        TSVideoOperator.shared.dataManager.addVideosToPlaylist(videos: videos, to: playlist) { _ in

            dismiss(animated: true) {
                self.addSuccessBlock()
            }
        }
    }

    func addToPlayList(playlist: TSPlayList) {
        if let mVideo = video {
            TSVideoOperator.shared.dataManager.addVideoToPlaylist(video: mVideo, to: playlist) { success in
                if !success {
                    THUD.toast("Already Exists".localized())
                } else {
                    dismiss(animated: true) {
                        self.addSuccessBlock()
                    }
                }
            }
        }
    }

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