//
//  CustomTabBarController.swift
//  KittensTravelNotes
//
//  Created by 100Years on 2025/6/30.
//

import UIKit

class CustomTabBarController: UITabBarController {
    
    // MARK: - 自定义属性
    var tabBarHeight: CGFloat = 56 // 可自定义高度
    var tabBarPosition: CGPoint = .zero // 可自定义位置
    private var selectionIndicatorView = UIView()
    var buttonWidth:CGFloat = 0.0
    var buttonHeight:CGFloat = 48.0
    private var observation: NSKeyValueObservation?
    
    lazy var customTabBar: UIView = {
        let customTabBar = UIView()
        customTabBar.backgroundColor = UIColor.white
        customTabBar.layer.cornerRadius = 28
        customTabBar.layer.masksToBounds = true
        return customTabBar
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViewControllers()
        setupCustomTabBar()
 
    }
    // MARK: - 设置视图控制器
    private func setupViewControllers() {
        let plogVC = createNavController(rootViewController: TSPlogVC(),
                                         title: "Plog",
                                         image: UIImage(resource: .tabbarUnSelectPic),
                                         selectedImage:UIImage(resource: .tabbarSelectPic))
        
        let recollectionVC = createNavController(rootViewController: TSRecollectionVC(),
                                                 title: "Recollection",
                                                 image: UIImage(resource: .tabbarUnSelectHistory),
                                                 selectedImage:UIImage(resource: .tabbarSelectHistory))
        
        let settingVC = createNavController(rootViewController: TSSetingVC(),
                                            title: "Setting",
                                            image: UIImage(resource: .tabbarUnSelectSetting),
                                            selectedImage:UIImage(resource: .tabbarSelectSetting))
        
        // 2. 设置视图控制器数组
        viewControllers = [plogVC, recollectionVC, settingVC]
    }
    

    // MARK: - 设置自定义TabBar
    private func setupCustomTabBar() {
        
        buttonWidth = (view.bounds.width - 40) / CGFloat(tabBar.items!.count)
        
        // 1. 移除系统TabBar
        disableSystemTabBar()
        
        // 2. 创建自定义TabBar容器
        view.addSubview(customTabBar)
        customTabBar.snp.makeConstraints { make in
            make.leading.equalTo(16.0)
            make.trailing.equalTo(-16.0)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom())
            make.height.equalTo(56)
        }

        
        // 4. 添加选中指示器
        selectionIndicatorView.backgroundColor = .themeColor
        selectionIndicatorView.layer.cornerRadius = buttonHeight/2.0
        customTabBar.addSubview(selectionIndicatorView)
        self.selectionIndicatorView.snp.makeConstraints { make in
            make.leading.equalTo(4)
            make.centerY.equalToSuperview()
            make.width.equalTo(buttonWidth)
            make.height.equalTo(buttonHeight)
        }
        dePrint("aaa")
        // 5. 添加Tab按钮
        self.setupTabButtons(in: customTabBar)

    }
    
    // MARK: - 设置Tab按钮
    private func setupTabButtons(in container: UIView) {
        guard let items = tabBar.items else { return }
        for (index, item) in items.enumerated() {
            let button = TSVerticalButton()
            button.tag = index
            button.addTarget(self, action: #selector(tabButtonTapped(_:)), for: .touchUpInside)
            
            button.setAttributedTitle(NSAttributedString(
                string: item.title!,
                attributes: [
                    .font: UIFont.font(size: 10),
                    .foregroundColor: UIColor.lesserText
                ]
            ), for: .normal)
            
            button.setAttributedTitle(NSAttributedString(
                string: item.title!,
                attributes: [
                    .font: UIFont.font(name:.PoppinsBoldItalic,size: 10),
                    .foregroundColor: UIColor.mainText
                ]
            ), for: .selected)
            
            button.setImage(item.image, for: .normal)
            button.setImage(item.selectedImage, for: .selected)
      
            container.addSubview(button)
            button.snp.makeConstraints { make in
                make.leading.equalTo(CGFloat(index) * buttonWidth+4)
                make.centerY.equalToSuperview()
                make.width.equalTo(buttonWidth)
                make.height.equalTo(buttonHeight)
            }
        }
        
        // 初始选中位置
        changeSelectedIndex(index: 0,animated: false)
    }

    
    // MARK: - 创建导航控制器
    private func createNavController(rootViewController: UIViewController,
                                   title: String?,
                                   image: UIImage?,
                                selectedImage:UIImage?
    ) -> UINavigationController {
        let navController = TSBaseNavigationC(rootViewController: rootViewController)
        navController.view.backgroundColor = UIColor.white
        navController.tabBarItem.title = title
        navController.tabBarItem.image = image
        navController.tabBarItem.selectedImage = selectedImage
        return navController
    }
    
    // MARK: - 按钮点击事件
    @objc private func tabButtonTapped(_ sender: UIButton) {
        changeSelectedIndex(index: sender.tag)
    }

    
    // MARK: - 更新选中指示器
    private func updateSelectionIndicator(position: Int, animated: Bool) {
        
        self.selectionIndicatorView.snp.updateConstraints { make in
            make.leading.equalTo(CGFloat(position) * self.buttonWidth + 4)
        }
        
        if animated {
            UIView.animate(withDuration: 0.3,
                          delay: 0,
                          usingSpringWithDamping: 0.7,
                          initialSpringVelocity: 0.5,
                          options: .curveEaseInOut,
                          animations: {
                self.selectionIndicatorView.superview?.layoutIfNeeded()
            })
        }
    }
    
    // MARK: - 更新按钮外观
    private func updateButtonAppearance(selectedIndex: Int) {
        for (index, button) in customTabBar.subviews.enumerated() {
            if let btn = button as? UIButton {
                btn.isSelected = btn.tag == selectedIndex
            }
        }
    }

    // MARK: - 外部可调用的方法
    func setTabBarHeight(_ height: CGFloat) {
        tabBarHeight = height
        // 更新布局
        view.setNeedsLayout()
        view.layoutIfNeeded()
    }
    
    func setTabBarPosition(_ position: CGPoint) {
        tabBarPosition = position
        // 更新布局
        view.setNeedsLayout()
        view.layoutIfNeeded()
    }

}

extension CustomTabBarController {
    func changeSelectedIndex(index:Int, animated: Bool = true){
        selectedIndex = index
        updateSelectionIndicator(position: index, animated: animated)
        updateButtonAppearance(selectedIndex: index)// 更新按钮状态
    }
}

extension CustomTabBarController {

    private func disableSystemTabBar() {
        tabBar.isHidden = true
        tabBar.alpha = 0
        tabBar.frame = .zero
    }
    
    private func setupObservers() {
         // 观察selectedViewController的变化
         observation = observe(\.selectedViewController, options: [.new]) { [weak self] _, _ in
             self?.updateCustomTabBarVisibility()
             
             // 设置新控制器的导航代理
             if let nav = self?.selectedViewController as? UINavigationController {
                 nav.delegate = self
             }
         }
         
         // 初始设置导航代理
         if let nav = selectedViewController as? UINavigationController {
             nav.delegate = self
         }
     }
    
    private func updateCustomTabBarVisibility() {
        guard let selectedVC = selectedViewController else { return }
        
        let shouldHide: Bool
        if let nav = selectedVC as? UINavigationController {
            shouldHide = nav.topViewController?.hidesBottomBarWhenPushed ?? false
        } else {
            shouldHide = selectedVC.hidesBottomBarWhenPushed
        }
        
        self.customTabBar.isHidden = shouldHide
        
//        UIView.animate(withDuration: 0.25) {
//            self.customTabBar.alpha = shouldHide ? 0 : 1
//            self.customTabBar.isUserInteractionEnabled = !shouldHide
//        }
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        disableSystemTabBar()
        updateCustomTabBarVisibility()
    }
}
extension CustomTabBarController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        disableSystemTabBar()
        updateCustomTabBarVisibility()
    }
}
