//
//  TSDiscoLightVC.swift
//  Girly
//
//  Created by 100Years on 2025/1/9.
//


private let defaultColor:UIColor = .white
private let baseColor:UIColor = .black
class TSDiscoLightVC: TSBaseVC {

    private var isOpen = false
    private var currentColor:UIColor = defaultColor
    private var currentFrequency:CGFloat = 0.5
    lazy var setToolView: TSDiscoSetToolView = {
        let setToolView = TSDiscoSetToolView()
        setToolView.changedValueComplete = { [weak self] value,isEnd in
            guard let self = self else { return }
            currentFrequency = value
            if isEnd,isOpen{
                startAlphaAnimation(duration: currentFrequency)
            }
        }
        
        setToolView.changedColorComplete = { [weak self] value,isEnd in
            guard let self = self else { return }
            currentColor = value
            
            if isOpen {
                if isEnd{
                    startAlphaAnimation(duration: currentFrequency)
                }
            }else{
                self.view.backgroundColor = currentColor
            }
        }
        
        setToolView.clickDoneComplete = { [weak self]  in
            guard let self = self else { return }
            
            isOpen = !isOpen
            
            if isOpen{
                UIView.animate(withDuration: 0.5, delay: 0, options: []) {
                    setToolView.isHidden = true
                }
                startAlphaAnimation(duration: currentFrequency)
                UIDevice.allowScreenSleep()
            }else {
                stopAlphaAnimation()
            }
            self.setToolView.submitBtn.setTitle(self.isOpen ? "Close" : "Open", for: .normal)
        }
        
        return setToolView
    }()
    

    override func createView() {
        addNormalNavBarView()
        setTitleText("")
        _ = setNavigationItem("", imageName: "navi_back_gary", direction: .left, action: #selector(navBarClickLeftAction))
        
        view.backgroundColor = currentColor
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showToView)))
        
        
        contentView.addSubview(setToolView)
        setToolView.snp.makeConstraints { make in
            make.leading.trailing.equalTo(0)
            make.bottom.equalTo(0)
            make.height.equalTo(282.0)
        }

    }
    
    @objc func showToView() {
        if setToolView.isHidden == true {
            UIView.animate(withDuration: 0.5, delay: 0, options: []) {
                self.setToolView.isHidden = false
            }
            
            UIDevice.allowScreenSleep()
        }
    }
    

    /// 颜色循环动画
    /// - Parameters:
    ///   - minAlpha: 颜色
    ///   - duration: 动画时长（单次透明度变化的时长，默认为 1 秒）
    func startAlphaAnimation(duration: TimeInterval = 1.0) {
        // 防止重复添加动画
        stopAlphaAnimation()
        
        kDelayMainShort {
            // 开始动画
            UIView.animate(withDuration: duration, delay: 0, options: [.autoreverse, .repeat,.allowUserInteraction]) {
                self.view.backgroundColor = baseColor
            } completion: { _ in
                self.view.backgroundColor = self.currentColor
            }
        }
  
    }
    
    /// 停止颜色循环动画
    func stopAlphaAnimation() {
        self.view.layer.removeAllAnimations()
        self.view.backgroundColor = self.currentColor
    }
    
    deinit {
        UIDevice.allowScreenSleep()
    }

}


class TSDiscoSetToolView: TSBaseView {
    var changedColorComplete:((UIColor,Bool)->Void)?
    var clickDoneComplete:(()->Void)?
    var changedValueComplete:((CGFloat,Bool)->Void)?{
        didSet{
            flashSliderView.changedValueComplete = changedValueComplete
        }
    }

    lazy var bottomView: UIView = {
        let bottomView = UIView()
        bottomView.backgroundColor = .cardBgColor
        return bottomView
    }()
    
    var isShow = true
    
    lazy var titleLabel1: UILabel = {
        let titleLabel1 = UILabel.createLabel(text: "Flicker Frequency".localized,font: .font(size: 14,weight: .medium),textColor: .white)
        return titleLabel1
    }()
    
    lazy var titleLabel2: UILabel = {
        let titleLabel1 = UILabel.createLabel(text: "Flash Color".localized,font: .font(size: 14,weight: .medium),textColor: .white)
        return titleLabel1
    }()
    
    lazy var colorSlider: ColorSlider = {
        let colorSlider = kCommonColorSlider()
        colorSlider.color = defaultColor
        colorSlider.addTarget(self, action: #selector(changedColor(slider:)), for: .valueChanged)
        colorSlider.addTarget(self, action: #selector(endColor(slider:)), for: .touchCancel)
        return colorSlider
    }()

    lazy var submitBtn: UIButton = {
        let submitBtn = createNormalSubmitBtn(title: "Open".localized) { [weak self]  in
            guard let self = self else { return }
            isShow = !isShow
            clickDoneComplete?()
        }
        submitBtn.cornerRadius = 22.0;
        return submitBtn
    }()
    
    lazy var flashSliderView: TSFlashSliderView = {
        let flashSliderView = TSFlashSliderView()
        flashSliderView.setSliderValue(minimumValue: 0.1, maximumValue: 1.0, value: 0.5)
        flashSliderView.setSliderImage(leftImage: UIImage(named: "low_frequency")!, rightImage: UIImage(named: "high_frequency")!)
        return flashSliderView
    }()
    
    override func creatUI() {
        
        contentView.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        
        let cell1 = creatCell(subView: titleLabel1)
        bottomView.addSubview(cell1)
        cell1.snp.makeConstraints { make in
            make.leading.equalTo(0)
            make.trailing.equalTo(0)
            make.top.equalTo(20)
            make.height.equalTo(44)
        }
        
        bottomView.addSubview(flashSliderView)
        flashSliderView.snp.makeConstraints { make in
            make.top.equalTo(cell1.snp.bottom)
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(48)
        }

        
        let cell2 = creatCell(subView: titleLabel2)
        bottomView.addSubview(cell2)
        cell2.snp.makeConstraints { make in
            make.leading.equalTo(0)
            make.trailing.equalTo(0)
            make.top.equalTo(124)
            make.height.equalTo(44)
        }
        
        bottomView.addSubview(colorSlider)
        colorSlider.snp.makeConstraints { make in
            make.top.equalTo(cell2.snp.bottom)
            make.trailing.equalTo(-30)
            make.leading.equalTo(30)
            make.height.equalTo(6)
        }
        
        bottomView.addSubview(submitBtn)
        submitBtn.snp.makeConstraints { make in
            make.leading.equalTo(50)
            make.trailing.equalTo(-51)
            make.bottom.equalTo(-34)
            make.height.equalTo(44)
        }

        kDelayMainShort {
            self.bottomView.cornersRound(radius: 20, corner: [.topLeft,.topRight])
            
//            let x = self.colorSlider.gradientView.calculateSliderProgress(for: self.colorSlider.internalColor)
//            self.colorSlider.previewView?.transition(to: .active)
//            self.colorSlider.centerPreview(at: CGPoint(x: x * self.colorSlider.bounds.width, y: x * self.colorSlider.bounds.height))
        }
        
    }
    
    func creatCell(subView:UIView) -> UIView{
        let view = UIView()
        view.addSubview(subView)
        subView.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(0)
            make.centerY.equalToSuperview()
        }
        return view
    }
    
    @objc func changedColor(slider: ColorSlider) {
        changedColorComplete?(slider.color,false)
    }
    @objc func endColor(slider: ColorSlider) {
        changedColorComplete?(slider.color,true)
    }
}
