//
//  MusicContainerViewController.swift
//  DiaryWallPaper
//
//  Created by 倪锴伦 on 2025/1/20.
//

import BetterSegmentedControl
import Foundation
import TSVideoKit

class MusicContainerViewController: LWBGViewController {
    lazy var navBar: LWRightNavigationBar = LWRightNavigationBar()
    lazy var searchBar: MusicSearchBar = MusicSearchBar()
    weak var importMenuView: BubbleMenuView?

    lazy var importButton: UIButton = {
        let bt = UIButton(frame: CGRect(x: 0, y: 0, width: 42, height: 42))
        bt.setImage(.icNavImport, for: .normal)
        return bt
    }()

    lazy var pageControl: BetterSegmentedControl = {
        let tracks = CustomSegementItem(text: "Tracks",
                                        normalBackgroundColor: .clear,
                                        normalFont: .systemFont14,
                                        normalTextColor: .white,
                                        selectedBackgroundColor: .hexColor("#111111"),
                                        selectedFont: .systemFont14,
                                        selectedTextColor: .black)
        let catalog = CustomSegementItem(text: "Playlist",
                                         normalBackgroundColor: .clear,
                                         normalFont: .systemFont14,
                                         normalTextColor: .white,
                                         selectedBackgroundColor: .hexColor("#111111"),
                                         selectedFont: .systemFont14,
                                         selectedTextColor: .black)
        let page = BetterSegmentedControl(frame: CGRect(x: 0, y: 0, width: 200, height: 30), segments: [tracks, catalog])
        page.animationDuration = 0
        page.indicatorViewBackgroundColor = .clear
        page.backgroundColor = .white.withAlphaComponent(0.1)
        page.layer.cornerRadius = 6
        page.addTarget(self, action: #selector(changeSegement(sender:)), for: .valueChanged)
        return page
    }()

    lazy var songlistVc: SongListViewController = SongListViewController()
    lazy var playlistVc: PlaylistViewController = PlaylistViewController()

    var viewModel: MusicContainerViewModel = MusicContainerViewModel()

    var childVcs: [LWBaseViewController] {
        [songlistVc, playlistVc]
    }

    // 添加 PageViewController
    private lazy var pageViewController: UIPageViewController = {
        let pageVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        pageVC.dataSource = self
        pageVC.delegate = self
        return pageVC
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        bgImageView.image = .viewMainBg
        addTargets()
    }

    override func addNotifaction() {
        super.addNotifaction()
//        topSegementBar.$type.receive(on: DispatchQueue.main).sink { [weak self] type in
//            self?.handleTypeChange(type)
//        }.store(in: &cancellable)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        PlayerManager.shared.rootVc?.moveUpMiniBar()
    }

    func addTargets() {
        searchBar.addTarget(self, action: #selector(showSearchViewController), for: .touchUpInside)
        importButton.addTarget(self, action: #selector(showImportMenuView), for: .touchUpInside)
    }

    @objc func changeSegement(sender: BetterSegmentedControl) {
        let index: Int = sender.index
        // 获取当前可见的视图控制器
        guard let currentViewController = pageViewController.viewControllers?.first else { return }
        // 计算方向
        let direction: UIPageViewController.NavigationDirection
        if childVcs.firstIndex(of: currentViewController as! LWBaseViewController) ?? -1 < index {
            direction = .forward // 从左向右
        } else {
            direction = .reverse // 从右向左
        }
        // 切换到目标视图控制器
        let targetViewController = childVcs[index]
        pageViewController.setViewControllers([targetViewController], direction: direction, animated: true, completion: nil)
    }

    @objc func showImportMenuView() {
        let menuView = BubbleMenuView()
        menuView.position = FitManager.isAr ? .topLeft : .topRight
        menuView.actionHanlder = { type in
            self.menuClick(type: type)
        }
        view.addSubview(menuView)
        menuView.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.top.equalTo(self.importButton.snp.bottom).offset(0)
        }
        importMenuView = menuView
    }

    func menuClick(type: ImportSource) {
        importMenuView?.removeFromSuperview()
        if type == .library {
            ImportFilesManager.shared.openPhotoLibrary(parent: self)
        } else if type == .file {
            ImportFilesManager.shared.openFileDocument(parent: self, completion: nil)
        }
    }

    @objc func showSearchViewController() {
//        if PurchaseManager.default.isVip {
//        if TSConfiguration.isYs {
            let vc = SearchOnlineViewController()
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
//        } else {
//            let vc = LocalSearchViewController()
//            vc.hidesBottomBarWhenPushed = true
//            navigationController?.pushViewController(vc, animated: true)
//        }
//        } else {
//            ADManager.shared.showAd(scene: ADScene.searchInsert, from: self) { state in
//                if state == .finished || state == .fail {
//                    if TSConfiguration.isYs {
//                        ADManager.shared.prepareAd(scenes: [ADScene.downloadInsert])
//                        let vc = SearchOnlineViewController()
//                        vc.hidesBottomBarWhenPushed = true
//                        self.navigationController?.pushViewController(vc, animated: true)
//                    } else {
//                        let vc = LocalSearchViewController()
//                        vc.hidesBottomBarWhenPushed = true
//                        self.navigationController?.pushViewController(vc, animated: true)
//                    }
//                }
//            }
//        }
    }

    override func addChildren() {
        super.addChildren()
        view.addSubview(navBar)
        navBar.appendRightItem(item: importButton)
        view.addSubview(searchBar)
        view.addSubview(pageControl)
        addChild(pageViewController)
        view.addSubview(pageViewController.view)
        pageViewController.didMove(toParent: self)

        if let firstViewController = childVcs.first {
            pageViewController.setViewControllers([firstViewController], direction: .forward, animated: false, completion: nil)
        }
    }

    override func makeConstarints() {
        super.makeConstarints()
        navBar.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.horizontalEdges.equalToSuperview()
            make.height.equalTo(k_Height_NavBar)
        }
        searchBar.snp.makeConstraints { make in
            make.top.equalTo(navBar.snp.bottom)
            make.horizontalEdges.equalToSuperview().inset(16)
            make.height.equalTo(44)
        }

        pageControl.snp.makeConstraints { make in
            make.width.equalTo(260)
            make.centerX.equalToSuperview()
            make.top.equalTo(searchBar.snp.bottom).offset(20)
            make.height.equalTo(32)
        }

        pageViewController.view.snp.makeConstraints { make in
            make.top.equalTo(pageControl.snp.bottom).offset(16)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.left.right.equalToSuperview()
        }
    }
}

// MARK: - UIPageViewControllerDataSource & Delegate

extension MusicContainerViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate {
    // 返回当前页面之前的视图控制器
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard let currentIndex = childVcs.firstIndex(of: viewController as! LWBaseViewController) else { return nil }
        let previousIndex = currentIndex - 1
        guard previousIndex >= 0 else { return nil }
        return childVcs[previousIndex]
    }

    // 返回当前页面之后的视图控制器
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let currentIndex = childVcs.firstIndex(of: viewController as! LWBaseViewController) else { return nil }
        let nextIndex = currentIndex + 1
        guard nextIndex < childVcs.count else { return nil }
        return childVcs[nextIndex]
    }

    // 设置页面显示的初始视图控制器
    func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo viewControllers: [UIViewController]) {
        // 可以在这里更新 SegmentBar 的状态
    }

    // 页面切换完成后调用
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted: Bool) {
        if transitionCompleted, let visibleViewController = pageViewController.viewControllers?.first {
            if let index = childVcs.firstIndex(of: visibleViewController as! LWBaseViewController) {
                pageControl.setIndex(index)
            }
        }
    }
}
