//
//  TSTabBarController.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import UIKit

class TSTabBarController: UITabBarController {
        
    lazy var miniBar: PlayMiniBar = PlayMiniBar()
    lazy var playerVc: PlayDetailViewController = .init()
    lazy var multiSelectView: CWMutiSelectOpeateView = {
        let mView = CWMutiSelectOpeateView()
        mView.isHidden = true
//        mView.deleteButton.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
//        mView.addPlaylist.addTarget(self, action: #selector(addToPlaylistAction), for: .touchUpInside)
        return mView
    }()

    private var viewControllerArray: [String] = []
    private var titleArray: [String] = []
    private var selectedImageArray: [String] = []
    private var unselectedImageArray: [String] = []
    private let markWidth = k_ScreenWidth / 4
    private lazy var markView: UIView = {
        let bgView = UIView()
        let imageView = UIImageView.createImageView(imageName: "tabbar_select_mark")
        bgView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.top.centerX.equalToSuperview()
            make.width.equalTo(24)
            make.height.equalTo(8)
        }
        return bgView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
        createUI()
        setUpData()
    }

    @objc private func setUpData() {
        viewControllerArray = ["TSHomeVC", "TSRandomWallpaperVC", "MusicContainerViewController", "TSMineVC"]

        selectedImageArray = [
            "tabbar_select_home",
            "tabbar_select_random",
            "tabbar_select_music",
            "tabbar_select_mine",
        ]
        unselectedImageArray = [
            "tabbar_unSelect_home",
            "tabbar_unSelect_random",
            "tabbar_unSelect_music",
            "tabbar_unSelect_mine",
        ]

        var tabArray: [UINavigationController] = []

        for i in 0 ..< viewControllerArray.count {
            if let rootViewController = viewControllerArray[i].toInstance(of: UIViewController.self) {
                let nav = TSBaseNavigationC(rootViewController: rootViewController)
                nav.view.backgroundColor = UIColor.black
                nav.tabBarItem = tabBarItem(
                    title: "titleArray[i].localized",
                    image: UIImage(named: unselectedImageArray[i]),
                    selectedImage: UIImage(named: selectedImageArray[i]),
                    tag: i
                )
                tabArray.append(nav)
            }
        }

        viewControllers = tabArray
    }

    private func createUI() {
        tabBar.barStyle = .black
        tabBar.isTranslucent = true

        if #available(iOS 13.0, *) {
            let appearance = UITabBarAppearance()
            appearance.backgroundEffect = UIBlurEffect(style: .dark) // 使用高斯模糊
            tabBar.standardAppearance = appearance

            if #available(iOS 15.0, *) {
                tabBar.scrollEdgeAppearance = appearance // 针对滚动边缘的外观
            }
        }

        tabBar.addSubview(markView)
        markView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.width.equalTo(markWidth)
            make.height.equalTo(8)
        }

        addMusicAndMiniBar()
    }

    func updateMarkViewFrame() {
        markView.snp.updateConstraints { make in
            make.left.equalTo(CGFloat(selectedIndex) * markWidth)
        }
    }

    private func tabBarItem(title: String, image: UIImage?, selectedImage: UIImage?, tag: Int) -> UITabBarItem {
        let tabBarItem = UITabBarItem()
        tabBarItem.image = image?.withRenderingMode(.alwaysOriginal)
        tabBarItem.selectedImage = selectedImage?.withRenderingMode(.alwaysOriginal)
        tabBarItem.imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: -8, right: 0) // 向下移动图标
        return tabBarItem
    }

    var currentNav: UINavigationController? {
        if selectedIndex < (viewControllers?.count ?? 0) {
            return viewControllers?[selectedIndex] as? UINavigationController
        }
        return nil
    }

    deinit {
        debugPrint("TSTabBarController deinit")
        NotificationCenter.default.removeObserver(self)
    }
}

extension TSTabBarController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        updateMarkViewFrame()
    }
}

// MARK: 音乐布局相关

extension TSTabBarController {
    private func addMusicAndMiniBar() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(showPlayDetailVc))
        miniBar.bgImageView.addGestureRecognizer(tap)
        miniBar.layer.cornerRadius = 16
        miniBar.layer.masksToBounds = true
        view.addSubview(miniBar)
        view.addSubview(playerVc.view)
        view.addSubview(multiSelectView)
        view.bringSubviewToFront(multiSelectView)
        makeMusicConstraints()
    }

    private func makeMusicConstraints() {
        miniBar.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-UIDevice.tabBarHeight)
            make.leading.equalToSuperview().offset(10)
            make.trailing.equalToSuperview().offset(-10)
            make.height.equalTo(62)
        }

        playerVc.view.snp.makeConstraints { make in
            make.top.equalTo(view.snp.bottom)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(UIScreen.kScreenHeight)
        }

        multiSelectView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(miniBar.snp.top)
        }
    }

    func moveDownMiniBar() {
        miniBar.snp.remakeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.leading.equalToSuperview().offset(10)
            make.trailing.equalToSuperview().offset(-10)
            make.height.equalTo(62)
        }
    }

    func moveUpMiniBar() {
        miniBar.snp.remakeConstraints { make in
            make.bottom.equalToSuperview().offset(-UIDevice.tabBarHeight)
            make.leading.equalToSuperview().offset(10)
            make.trailing.equalToSuperview().offset(-10)
            make.height.equalTo(62)
        }
    }
}

// MARK: 音乐操作相关

extension TSTabBarController {
    @objc func deleteButtonAction() {
        PlayerManager.shared.deleteSelectedVideos()
    }

    @objc func addToPlaylistAction() {
        PlayerManager.shared.addVideosToPlaylist()
    }

    @objc func showPlayDetailVc() {
        showPlayerVc()
    }

    func showPlayerVc() {
//        ADManager.shared.prepareAd(scenes: [ADScene.downloadReward])
        UIView.animate(withDuration: 0.2) {
            self.playerVc.view.snp.remakeConstraints { make in
                make.top.equalToSuperview()
                make.leading.trailing.equalToSuperview()
                make.height.equalTo(UIScreen.kScreenHeight)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
            self.view.bringSubviewToFront(self.playerVc.view)
        }
    }

    func hidePlayerVc() {
        UIView.animate(withDuration: 0.2) {
            self.playerVc.view.snp.remakeConstraints { make in
                make.top.equalToSuperview().offset(UIScreen.kScreenHeight)
                make.leading.trailing.equalToSuperview()
                make.height.equalTo(UIScreen.kScreenHeight)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
            self.view.bringSubviewToFront(self.playerVc.view)
        }
    }
}

// MARK: 进到首页后需要做的处理

extension TSTabBarController {
    /// 暂时没用，后续迭代
    func scheduleDailyNotification() {
        // 创建通知内容
        let content = UNMutableNotificationContent()
        content.title = "🎧 ≡ ◁◁ ❚❚ ▷▷ ↻"
        content.body = "♬ ♬ ♩ ♡ ♪ ♪ ♫ ♭ ♫ ♡"
        content.sound = UNNotificationSound.default

        // 创建通知触发条件
        var dateComponents = DateComponents()
        dateComponents.hour = 21 // 24小时制，20点即晚上8点

        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

        // 创建通知请求
        let request = UNNotificationRequest(identifier: "DailyNotification", content: content, trigger: trigger)

        // 将通知添加到通知中心
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("添加通知失败: \(error.localizedDescription)")
            }
        }
    }
}
