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

import Combine
import Foundation
import TSVideoKit

class LocalSearchViewController: LWBGViewController {
    private var cancellables = [AnyCancellable]()

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

    lazy var searchBar: CWSearchTextBar = {
        let bar = CWSearchTextBar()
        bar.textFiled.delegate = self
        bar.textFiled.textColor = .white
        bar.textFiled.attributedPlaceholder = NSAttributedString(string: "Search Music".localized(), attributes: [
            .foregroundColor: UIColor.hexColor("#FFFFFF").withAlphaComponent(0.4),
            .font: UIFont.systemFont(ofSize: 14)])
        return bar
    }()

    lazy var viewModel: LocalSearchViewModel = LocalSearchViewModel()

    lazy var listView: UITableView = {
        let tabView = UITableView()
        tabView.dataSource = viewModel
        tabView.backgroundColor = .clear
        tabView.delegate = self
        tabView.separatorStyle = .none
        tabView.register(SongListCell.self, forCellReuseIdentifier: "SongListCell")
        return tabView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        bgImageView.image = .viewMainBg
        addChildren()
        makeConstraints()
        addNotifaction()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        searchBar.textFiled.becomeFirstResponder()
    }

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

    override func addNotifaction() {
        super.addNotifaction()

        viewModel.$videos.receive(on: DispatchQueue.main).sink { [weak self] _ in
            self?.listView.reloadData()
        }.store(in: &cancellables)

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

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

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

    func cancelSubscriptions() {
        // 取消所有订阅
        cancellables.removeAll()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
        cancelSubscriptions()
    }
}

extension LocalSearchViewController: UITextFieldDelegate, UITableViewDelegate, UIScrollViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let items = viewModel.videos
        if indexPath.row < items.count {
            let video = items[indexPath.row]
            let list = TSVideoOperator.shared.dataManager.fetchCachedVideos(sort: viewModel.sort)
            PlayerManager.shared.playVideo(video: video, list: list, scene: .local, onceAdKey: "")
        }
        searchBar.textFiled.resignFirstResponder()
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let originalText = textField.text ?? ""
        // Calculate the new text after replacement
        let updatedText = (originalText as NSString).replacingCharacters(in: range, with: string)
        listView.isHidden = updatedText.isEmpty
        viewModel.keyword = updatedText

        return true
    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        searchBar.textFiled.resignFirstResponder()
    }
}

extension LocalSearchViewController {
    func makeConstraints() {
        backButton.snp.makeConstraints { make in
            make.width.height.equalTo(40)
            make.leading.equalToSuperview().offset(8)
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
        }

        searchBar.snp.makeConstraints { make in
            make.leading.equalTo(backButton.snp.trailing).offset(6)
            make.trailing.equalToSuperview().offset(-16)
            make.height.equalTo(40)
            make.centerY.equalTo(backButton)
        }

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