//
//  SpeakEleTabbarViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/3.
//

import UIKit

class SpeakEleTabbarViewCtr: UIViewController {

    public var selectIndex = 0 {
        didSet {
            for (i,but) in tabBarItems.enumerated() {
                but.isSelected = (i == selectIndex)
            }
            UIView.animate(withDuration: 0.35, delay: 0, options: .curveEaseOut) {
                self.scroll.contentOffset = CGPointMake(CGFloat(self.selectIndex) * self.scroll.width, 0)
            }
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    private var tabBarItems:[TabbarButton] = [] {
        didSet {
            stack.arrangedSubviews.forEach({stack.removeArrangedSubview($0)})
            tabBarItems.forEach({stack.addArrangedSubview($0)})
        }
    }
    
    private var tabbarChildVc:[SpeakEleBaseViewCtr] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        SpeakElePublicManager.share.PublicData.state = .home
        AddchildVC()
        setup()
        selectIndex = 0
    }
    
    private func AddchildVC() -> Void {
        let home = TabbarButton(title: "Home", normalImage: "Icon-Tab-Home", selectImage: "Icon-Tab-Home-S")
        let homevc = SpeakEleHomeViewCtr()
        self.addChild(homevc)
        contentStack.addArrangedSubview(homevc.view)
        homevc.didMove(toParent: self)
        
        let Practice = TabbarButton(title: "Practice", normalImage: "Icon-Tab-Pra", selectImage: "Icon-Tab-Pra-S")
        let PracticeVc = SpeakElePracticeViewCtr()
        self.addChild(PracticeVc)
        contentStack.addArrangedSubview(PracticeVc.view)
        homevc.didMove(toParent: self)
        
        let pro = TabbarButton(title: "Progress", normalImage: "Icon-Tab-Progress", selectImage: "Icon-Tab-Progress-S")
        let provc = SpeakEleProgressViewCtr()
        self.addChild(provc)
        contentStack.addArrangedSubview(provc.view)
        provc.didMove(toParent: self)
        
        let profile = TabbarButton(title: "Profile", normalImage: "Icon-Tab-Pro", selectImage: "Icon-Tab-Pro-S")
        let profileVc = SpeakEleProfileViewCtr()
        self.addChild(profileVc)
        contentStack.addArrangedSubview(profileVc.view)
        profileVc.didMove(toParent: self)
        
        tabbarChildVc = [
            homevc,
            PracticeVc,
            provc,
            profileVc
        ]
        
        tabBarItems = [
            home,
            Practice,
            pro,
            profile
        ]
        for (i,btn) in tabBarItems.enumerated() {
            btn.tag = i
            btn.addTarget(self, action: #selector(SpeakTouches(_:)), for: .touchUpInside)
        }
    }
    
    @objc private func SpeakTouches(_ sender:UIButton) -> Void {
        if sender.tag == selectIndex {
            return
        }
        selectIndex = sender.tag
        tabbarChildVc[selectIndex].viewWillAppear(true)
    }
    
    private func setup() -> Void {
        scroll.snp.makeConstraints { make in
            make.left.right.bottom.top.equalToSuperview()
        }
        contentStack.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(self.tabBarItems.count)
            make.height.equalToSuperview()
        }
        tabbar.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(CGFloat(Dev.tabHeight) + (Dev.safeAreaInsets.bottom) )
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.view.layoutIfNeeded()
        view.bringSubviewToFront(stack)
        scroll.contentSize = CGSizeMake(CGFloat(self.tabBarItems.count) * scroll.width, 0)
        lineLayer.frame = CGRect(x: 0, y: 0, width: Dev.screenW, height: 0.6)
    }
    
    private lazy var tabbar: UIView = {
        let tab = UIView()
        tab.backgroundColor = .white
        view.addSubview(tab)
        return tab
    }()
    
    private lazy var stack: UIStackView = {
        let stack = UIStackView()
        stack.backgroundColor = .white
        stack.spacing = 0
        stack.distribution = .fillEqually
        stack.alignment = .fill
        stack.axis = .horizontal
        tabbar.addSubview(stack)
        stack.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(Dev.safeAreaInsets.bottom)
        }
        return stack
    }()
    
    private lazy var scroll: UIScrollView = {
        let scroll = UIScrollView()
        scroll.isPagingEnabled = true
        scroll.isScrollEnabled = false
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        view.addSubview(scroll)
        return scroll
    }()
    
    private lazy var contentStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.spacing = 0
        stack.distribution = .fillEqually
        stack.alignment = .fill
        scroll.addSubview(stack)
        return stack
    }()
    
    private lazy var lineLayer: CALayer = {
        let line = CALayer()
        stack.layer.addSublayer(line)
        line.backgroundColor = UIColor.init(hex: 0x000000 ,alpha: 0.12).cgColor
        return line
    }()
    
}


class TabbarButton: UIButton {
    
    convenience init(title:String?, normalImage:String?, selectImage:String?) {
        self.init(type: .custom)
        var configs = UIButton.Configuration.filled()
        configs.title = title
        configs.baseBackgroundColor = .clear
        configs.baseForegroundColor = .gray
        configs.imagePlacement = .top
        configs.imagePadding = 2
        configs.titleAlignment = .center
        configs.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer({ containar in
            var att = containar
            att.font = UIFont.systemFont(ofSize: 12, weight: .regular)
            return att
        })
        self.configuration = configs
        self.configurationUpdateHandler = { button in
            var updateConfigs = button.configuration
            if button.isSelected {
                updateConfigs?.baseForegroundColor = .init(with: "#3980F6")
                guard let simg = selectImage else { return }
                updateConfigs?.image = UIImage(named: simg)?.withRenderingMode(.alwaysOriginal)
            }else{
                updateConfigs?.baseForegroundColor = .gray
                guard let img = normalImage else { return}
                updateConfigs?.image = UIImage(named: img)?.withRenderingMode(.alwaysOriginal)
            }
            button.configuration = updateConfigs
        }
    }
    
}
