//
//  SpeakEleGeneratePlanViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/17.
//

import UIKit

class SpeakEleGeneratePlanViewCtr: SpeakEleBaseViewCtr, UIScrollViewDelegate {

    // MARK: - ib
    @IBOutlet weak var SpeakStackView: UIStackView!
    @IBOutlet weak var SpeakContinueBtn: UIButton!
    
    @IBOutlet var SpeakContentV: [UIView]!
    
    
    @IBOutlet var SpeakPlanIcons: [UIImageView]!
    @IBOutlet var SpeakPlanName: [UILabel]!
    @IBOutlet var SpeakPlanDescptions: [UILabel]!
    
    
    @IBOutlet weak var SpeakScroll: UIScrollView!
    @IBOutlet weak var StackView: UIStackView!
    @IBOutlet var SpeakPages: [UIView]!
    
    private let viewModel = SpeakUserNetViewModel()
    private let viewModelQA = SpeakEleQAViewModel()
    
    private var offset:Double = 0
    
    private var selectIdx:CGFloat = -1
    
    private var dataProgress:[Int] = []
    
    private var SpeakPlanChilds:[SpeakEleGeneratePlanView] = [
        SpeakEleGeneratePlanView(string: "Creating diverse topics"),
        SpeakEleGeneratePlanView(string: "Preparing interactive dialogues"),
        SpeakEleGeneratePlanView(string: "Optimizing your learning path"),
        SpeakEleGeneratePlanView(string: "Finalizing your plan")
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        SpeakPlanChilds.forEach { plan in
            SpeakStackView.addArrangedSubview(plan)
        }
        timer.fire()
        dataProgress = Array(0...35).filter({$0%3==0})
        dataProgress.append(contentsOf: Array(0..<3).map({_ in
            return 35
        }))
        dataProgress.append(contentsOf: Array(0..<3).map({_ in
            return 36
        }))
        dataProgress.append(contentsOf: Array(0..<3).map({_ in
            return 37
        }))
        dataProgress.append(contentsOf: Array(0..<3).map({_ in
            return 38
        }))
        dataProgress.append(contentsOf: Array(40...97).filter({$0%3==0}))
        dataProgress.append(contentsOf: Array(0...2).map({ _ in
            return 98
        }))
        dataProgress.append(contentsOf: Array(0...2).map({ _ in
            return 99
        }))
        dataProgress.append(contentsOf: Array(101...155).filter({$0%3==0}))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 156
        }))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 157
        }))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 158
        }))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 159
        }))
        dataProgress.append(contentsOf: Array(162...196).filter({$0%3==0}))
        dataProgress.append(contentsOf: Array(0...2).map({ _ in
            return 198
        }))
        dataProgress.append(contentsOf: Array(0...2).map({ _ in
            return 199
        }))
        dataProgress.append(contentsOf: Array(201...237).filter({$0%3==0}))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 238
        }))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 239
        }))
        dataProgress.append(contentsOf: Array(0...4).map({ _ in
            return 240
        }))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 241
        }))
        dataProgress.append(contentsOf: Array(243...297).filter({$0%3==0}))
        dataProgress.append(contentsOf: Array(0...2).map({ _ in
            return 298
        }))
        dataProgress.append(contentsOf: Array(0...2).map({ _ in
            return 299
        }))
        dataProgress.append(contentsOf: Array(301...377).filter({$0%3==0}))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 378
        }))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 379
        }))
        dataProgress.append(contentsOf: Array(0...3).map({ _ in
            return 380
        }))
        dataProgress.append(contentsOf: Array(381...397).filter({$0%3==0}))
        dataProgress.append(contentsOf: Array(0...2).map({ _ in
            return 398
        }))
        dataProgress.append(contentsOf: Array(0...2).map({ _ in
            return 399
        }))
        dataProgress.append(contentsOf: Array(0...1).map({ _ in
            return 400
        }))
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        titleView.isHidden = true
        updateUserInformation()
        setPages(0)
        let plans = SpeakReviewViewModel.Loading
        for (i,v) in plans.enumerated() {
            SpeakPlanIcons[safe:i]?.image = UIImage(named: v.image)
            SpeakPlanName[safe:i]?.text = v.name
            SpeakPlanDescptions[safe:i]?.text = v.descption
        }
        SpeakScroll.delegate = self;
        self.view.layoutIfNeeded()
        SpeakPlanChilds.forEach { view in
            view.layoutIfNeeded()
        }
        DispatchQueue.main.async {
            self.start()
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.view.layoutIfNeeded()
        SpeakContentV.forEach { contentV in
            contentV.shadow(cornerRadius: 16, shadowColor: .init(hex: 0x000000,alpha: 0.06), offset: CGSizeMake(0, 0), opacity: 1, radius: 3)
        }
    }
    
    @IBAction func SpeakCountiueTaps(_ sender: Any) {
        if !IAPViewModel.share.isSubscribed {
            let iap = SpeakEleIAPViewCtr()
            iap.state = .plan
            self.navigationController?.AnimationState = .present
            self.navigationController?.pushViewController(iap, animated: true)
        }else if !SpeakElePublicManager.share.userInfo.isLogin() {
            let login = SpeakEleFLoginViewCtr()
            self.navigationController?.pushViewController(login, animated: true)
        }else{
            let nav = SpeakEleBaseNavigationCtr(rootViewController: SpeakEleTabbarViewCtr())
            SpWindow.switchToController(nav)
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        display.isPaused = true
        display.invalidate()
    }
    
    private func start() -> Void {
        offset = 0
        display.preferredFramesPerSecond = 10
        display.isPaused = false
    }
    
    override func SpeakUpdate() {
        offset += 1
        let progree = dataProgress[safe: Int(offset)] ?? 0
        self.view.layoutIfNeeded()
        switch progree {
        case 0..<100:
            let child = SpeakPlanChilds.first
            child?.state = .start
            child?.startRotation()
            child?.offset = progree
            break
        case 100..<200:
            let child = SpeakPlanChilds[0]
            if child.state != .finish {
                child.stop()
                child.offset = 100
                child.state = .finish
            }
            
            let child1 = SpeakPlanChilds[1]
            child1.state = .start
            child1.startRotation()
            child1.offset = progree-100
            break
        case 200..<300:
            let child = SpeakPlanChilds[1]
            if child.state != .finish {
                child.stop()
                child.offset = 100
                child.state = .finish
            }
            
            let child2 = SpeakPlanChilds[2]
            child2.state = .start
            child2.startRotation()
            child2.offset = progree-200
            break
            
        default:
            let child = SpeakPlanChilds[2]
            if child.state != .finish {
                child.stop()
                child.offset = 100
                child.state = .finish
            }
            let child1 = SpeakPlanChilds[3]
            child1.state = .start
            child1.startRotation()
            child1.offset = progree-300
            if progree - 300 >= 100 {
                child1.offset = 100
                child1.state = .finish
                UIView.animate(withDuration: 0.1, delay: 0.5) {
                    self.SpeakContinueBtn.alpha = 1
                }
                display.isPaused = true
            }
            break
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if timer.isValid {
            timer.invalidate()
        }
    }
    
    private lazy var pagectrol: UIView = {
        let p = UIView()
        p.corners = 3
        p.backgroundColor = .init(hex: 0x3980F6)
        StackView.addSubview(p)
        return p
    }()
    
    private func setPages(_ select:Int) -> Void {
        self.view.setNeedsLayout()
        let v = SpeakPages[safe:select] ?? UIView()
        pagectrol.snp.remakeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.centerX.equalTo(v.snp.centerX)
            make.width.equalTo(15)
            self.view.layoutIfNeeded()
        }
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.x
        setPages(Int(offset / scrollView.width) )
    }
    
    private lazy var timer: Timer = {
        let tim = Timer(timeInterval: 3, repeats: true) {[weak self] tm in
            Print("timer 1111111111")
            self?.selectIdx += 1
            if (self?.selectIdx ?? 3) < 3 {
                UIView.animate(withDuration: 0.8) {
                    self?.SpeakScroll.contentOffset = CGPoint(x: (self?.SpeakScroll.width ?? 0.0) * (self?.selectIdx ?? 0), y: 0)
                } completion: { su in
                    self?.setPages(Int(self?.selectIdx ?? 0))
                }
            }else{
                tm.invalidate()
            }
        }
        RunLoop.main.add(tim, forMode: .common)
        return tim
    }()
}
