//
//  SearchOnlineViewController.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/11.
//

import Combine
import Foundation
import KLExtension
import SwiftUI
import UIKit

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

    lazy var searchBar: CWSearchTextBar = {
        let bar = CWSearchTextBar()
        bar.textFiled.delegate = self
        bar.backgroundColor = .white.withAlphaComponent(0.1)
        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)])
        bar.customCornerRadius = 8
        return bar
    }()

    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 searchButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("Search".localized(), for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14)
        btn.addTarget(self, action: #selector(searchKeyWord), for: .touchUpInside)
        return btn
    }()

    lazy var historyController: UIHostingController = {
        let tagView = TagListView { tag in
            self.beginSearchKeyword(history: tag)
        }
        let vc = UIHostingController(rootView: tagView)
        vc.view.backgroundColor = .clear
        return vc
    }()

    lazy var viewModel: SearchViewModel = SearchViewModel()

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

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

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

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

    override func addChildren() {
        super.addChildren()
        bgImageView.image = .viewMainBg
        addChild(historyController)
        view.addSubview(backButton)
        view.addSubview(searchBar)
        view.addSubview(searchButton)
        view.addSubview(listView)
        view.addSubview(historyController.view)
    }

    override func makeConstarints() {
        super.makeConstarints()
        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)
            make.trailing.equalTo(searchButton.snp.leading).offset(-8)
            make.height.equalTo(40)
            make.centerY.equalTo(backButton)
        }
        searchButton.sizeToFit()
        searchButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.centerY.equalTo(searchBar)
            make.height.equalTo(40)
            make.width.equalTo(searchButton.width)
        }

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

        historyController.view.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.top.equalTo(searchButton.snp.bottom)
        }
    }

    func beginSearchKeyword(history: HistoryModel) {
        let vc = SearchResultViewController()
        vc.viewModel.searchModel = .init(query: history.keyword)
        recordHistory(keyword: history.keyword)
        navigationController?.pushViewController(vc, animated: true)
    }

    @objc func searchKeyWord() {
        if searchBar.textFiled.text?.isEmpty == true {
            return
        }
        searchBar.textFiled.resignFirstResponder()
        viewModel.keyword = searchBar.textFiled.text ?? ""

        let vc = SearchResultViewController()
        vc.viewModel.searchModel = .init(query: searchBar.textFiled.text ?? "")
        recordHistory(keyword: searchBar.textFiled.text ?? "")
        navigationController?.pushViewController(vc, animated: true)
    }

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

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

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

    deinit {
        cancelSubscriptions()
    }
}

extension SearchOnlineViewController: UITextFieldDelegate, UITableViewDelegate, UIScrollViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let items = viewModel.relateModel?.relateItems ?? []
        if indexPath.row < items.count {
            if let keyword = viewModel.relateModel?.relateItems[indexPath.row] {
                let vc = SearchResultViewController()
                vc.viewModel.searchModel = .init(query: keyword)
                recordHistory(keyword: keyword)
                navigationController?.pushViewController(vc, animated: true)
            }
        }

        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
        historyController.view.isHidden = !updatedText.isEmpty
        viewModel.keyword = updatedText

        return true
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        searchKeyWord()
        return true
    }

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

    func recordHistory(keyword: String) {
        let model = HistoryModel(keyword: keyword, id: UUID().uuidString, date: Date())
        let storage = CodableStorage()
        do {
            var history: [HistoryModel] = try storage.fetch(for: kStore_History_Key)
            history.removeAll {
                $0.keyword == keyword
            }
            history.insert(model, at: 0)
            try storage.save(history, for: kStore_History_Key)
        } catch {
            let history: [HistoryModel] = [model]
            try? storage.save(history, for: kStore_History_Key)
        }
    }
}
