//
//  ChargeGuideController.swift
//  PhoneManager
//
//  Created by edy on 2025/4/7.
//

import Foundation

class ChargeGuideController : BaseViewController,UIScrollViewDelegate,UINavigationControllerDelegate, UIGestureRecognizerDelegate {
    
    
    
    let imageString : [String] = [
        "img_phone_battery_02 1",
        "img_phone_battery_03",
        "img_phone_battery_04",
        "img_phone_battery_05",
        "img_phone_battery_06",
        "img_phone_battery_07"
    ]
    
    let tipString : [String] = [
        "Animation Works with Apple Shortcuts",
        "Tap to New Automation to add an automation",
        "Scroll the page and select Charger section",
        "Select 'ls Connected' and 'Run lmmediately',then tap on Next",
        "Tap on New Blank Automation to connect the app",
        "Type 'PhoneManager' & select Run Charging Animation and tap on Done!"
    ]
    
    let numberOfPages = 7
    
    var pageControl: UIPageControl = {
        let view = UIPageControl()
        view.numberOfPages = 7
        view.currentPage = 0
        view.pageIndicatorTintColor = .white
        view.currentPageIndicatorTintColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        return view
    }()
    
    
    lazy var guideScrollView: UIScrollView = {
        let view = UIScrollView(frame: self.view.bounds)
        view.contentSize = CGSize(width: self.view.bounds.width * CGFloat(7), height: self.view.bounds.height)
        view.isPagingEnabled = true
        view.showsHorizontalScrollIndicator = false
        view.delegate = self
        return view
    }()
    
    lazy var closeButton : UIButton = {
        let view = UIButton()
        view.backgroundColor = .clear
        view.setImage(UIImage(named: "ic_close_charging"), for: .normal)
        view.addTarget(self, action: #selector(closeCurrentPage), for: .touchUpInside)
        return view
    }()
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.guideScrollView)
        self.view.addSubview(self.closeButton)
        self.view.addSubview(self.pageControl)
        titleView.model.isBackBtnShow = false
        navigationController?.isNavigationBarHidden = true
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        navigationController?.interactivePopGestureRecognizer?.delegate = self;
        self.closeButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(statusBarHeight + 15)
            make.width.height.equalTo(28)
        }
        self.pageControl.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.height.equalTo(8)
            make.width.equalTo(250)
            make.bottom.equalToSuperview().offset(-62)
        }
        
        for i in 0..<6{
            let view = ChargeGuideNormalView(frame: CGRect(x: self.view.bounds.width * CGFloat(i), y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
            view.guideView.image = UIImage(named: self.imageString[i])
            view.tipTitleLabel.text = self.tipString[i]
            if i==0 {
                view.detailTipTitleLabel.isHidden = false
                // 在滑动的第一个添加一个button
//                let jumpButton = UIButton(type: .custom)
//                jumpButton.setTitle("Open shortcut command", for: .normal)
//                jumpButton.setTitleColor(.white, for: .normal)
//                jumpButton.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
//                jumpButton.layer.cornerRadius = 25
//                jumpButton.clipsToBounds = true
//                view.addSubview(jumpButton)
//                jumpButton.snp.makeConstraints { make in
//                    make.left.equalToSuperview().offset(32)
//                    make.right.equalToSuperview().offset(-32)
//                    make.height.equalTo(50)
//                    make.bottom.equalToSuperview().offset(-122 * RScreenH())
//                }
//                jumpButton.addTarget(self, action: #selector(jumpButtonAction), for: .touchUpInside)
                let tap = UITapGestureRecognizer(target: self, action: #selector(jumpButtonAction(_:)))
                view.guideView.isUserInteractionEnabled = true
                view.guideView.addGestureRecognizer(tap)
            }else {
                view.detailTipTitleLabel.isHidden = true
            }
            self.guideScrollView.addSubview(view)
            view.orderFlag = i
            view.callback = {[weak self] text in
                guard let self else {return}
                if text as! String == "next" {
                    self.guideScrollView.contentOffset = CGPointMake(self.guideScrollView.contentOffset.x + self.view.bounds.width, 0)
                }
                if text as! String == "back" {
                    self.guideScrollView.contentOffset = CGPointMake(self.guideScrollView.contentOffset.x - self.view.bounds.width, 0)
                }
            }
        }
        
        let endView = ChargeGuideEndView(frame: CGRect(x: self.view.bounds.width * 6, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
        endView.callback = {[weak self] text in
            guard let self else {return}
            if text as! String == "over" {
                self.guideScrollView.contentOffset = CGPointMake(0, 0)
            }
        }
        self.guideScrollView.addSubview(endView)
    }

    @objc func closeCurrentPage(){
        let vc = self.navigationController?.viewControllers.first
        vc?.dismiss(animated: true)
    }
    
    @objc func jumpButtonAction(_ ges:UIGestureRecognizer){
    
        let point = ges.location(in: ges.view)
        var frame = ges.view?.frame ?? CGRect()
        frame.origin.y = (frame.height) - 205
        frame.size.height = 100
        if CGRectContainsPoint(frame, point) {
            if let url = URL(string: "shortcuts://") {
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            }
        }
    }
    
    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        if operation == .pop {
            return CustomPopAnimator()
        }
        return nil
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageIndex = round(scrollView.contentOffset.x / scrollView.bounds.width)
        if Int(pageIndex) == (self.numberOfPages - 1){
            self.pageControl.isHidden = true
        }else{
            self.pageControl.isHidden = false
        }
        self.pageControl.currentPage = Int(pageIndex)
    }
}

// 自定义转场动画类
class CustomPopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromVC = transitionContext.viewController(forKey:.from),
              let toVC = transitionContext.viewController(forKey:.to) else {
            return
        }
        
        let containerView = transitionContext.containerView
        containerView.insertSubview(toVC.view, belowSubview: fromVC.view)
        
        let screenBounds = UIScreen.main.bounds
        let finalFrame = CGRect(x: 0, y: screenBounds.height * 2, width: screenBounds.width, height: screenBounds.height)
        
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            fromVC.view.frame = finalFrame
        }) { (finished) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}
