//
//  YHSurveyMatchingViewController.swift
//  galaxy
//
//  Created by alexzzw on 2025/3/27.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import Lottie
import UIKit

class YHSurveyMatchingViewController: YHBaseViewController {
    private lazy var viewModel = YHSurveyViewModel()

    private var timer: Timer?
    private var startTime: Date?
    private var isRequestCompleted = false

    private lazy var lottieView: LottieAnimationView = {
        let aniView = LottieAnimationView(name: "survey_file_scan")
        aniView.isUserInteractionEnabled = false
        aniView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenWidth)
        aniView.contentMode = .scaleAspectFit
        aniView.loopMode = .loop
        return aniView
    }()

    private lazy var infoTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "智能匹配中"
        label.textColor = .mainTextColor
        label.font = .PFSC_B(ofSize: 26)
        label.textAlignment = .center
        return label
    }()

    private lazy var infoContentLabel: UILabel = {
        let label = UILabel()
        label.text = "正在为您制定香港身份续签至永居方案"
        label.textColor = UIColor(hex: 0x6A7586)
        label.font = .PFSC_R(ofSize: 15)
        label.textAlignment = .center
        label.numberOfLines = 0
        return label
    }()

    private lazy var progressView: UIProgressView = {
        let view = UIProgressView()
        view.progressTintColor = .mainTextColor
        view.trackTintColor = UIColor(hexString: "#F5F6F8")
        view.progress = 0.6
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        startLoading()
    }

    private func setupUI() {
        gk_navTitle = "香港身份方案评估"
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white

        view.backgroundColor = UIColor.white
        view.addSubview(lottieView)
        view.addSubview(infoTitleLabel)
        view.addSubview(infoContentLabel)
        view.addSubview(progressView)
        lottieView.snp.makeConstraints { make in
            make.width.equalTo(248)
            make.height.equalTo(248)
            make.top.equalToSuperview().offset(32 + k_Height_NavigationtBarAndStatuBar)
            make.centerX.equalToSuperview()
        }
        infoTitleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(lottieView.snp.bottom).offset(18)
        }
        infoContentLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(infoTitleLabel.snp.bottom).offset(8)
            make.left.greaterThanOrEqualToSuperview().offset(16)
            make.right.lessThanOrEqualToSuperview().offset(-16)
        }
        progressView.snp.makeConstraints { make in
            make.width.equalTo(220)
            make.height.equalTo(4)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(view.layoutMarginsGuide.snp.bottom).offset(-90)
        }
    }

    private func startLoading() {
        startAnimation()
        // 重置状态
        progressView.progress = 0
        isRequestCompleted = false
        startTime = Date()
        timer = Timer.scheduledTimer(withTimeInterval: 0.016, repeats: true, block: { [weak self] _ in
            guard let self = self else { return }
            guard let startTime = self.startTime else { return }
            let elapsed = Date().timeIntervalSince(startTime)
            let totalDuration: TimeInterval = 4.0 // 总时长4秒

            if elapsed < totalDuration {
                // 前4秒内，进度条从0%到90%
                let progress = Float(elapsed / totalDuration) * 0.9
                self.progressView.progress = progress
            } else {
                // 4秒后
                self.timer?.invalidate()
                self.timer = nil

                if self.isRequestCompleted {
                    // 如果请求已完成，直接到100%
                    self.progressView.progress = 1.0
                    self.loadingCompleted()
                } else {
                    // 如果请求未完成，保持90%，等待请求完成
                    self.progressView.progress = 0.9
                }
                self.requestState()
            }
        })
        // requestState()
    }

    private func requestState() {
        viewModel.getRenewalPlanState { [weak self] _, _ in
            guard let self = self else {
                return
            }
            self.isRequestCompleted = true
            if self.timer == nil {
                // 如果计时器已经结束（超过4秒），直接完成进度条
                self.progressView.progress = 1.0
                self.loadingCompleted()
            }
        }
    }

    private func loadingCompleted() {
        stopAnimation()
        if let state = viewModel.planState, state.isGeneratePlan {
            gotoMatchResultVC(true)
        } else {
            gotoMatchResultVC(false)
        }
    }

    private func gotoMatchResultVC(_ isSucess: Bool) {
        let ctl = YHSurveyMatchResultViewController(isSucess ? .success : .failure)
        if !isSucess {
            ctl.matchAgainEvent = { [weak self] in
                self?.startLoading()
            }
        }
        navigationController?.pushViewController(ctl)
    }

    private func startAnimation() {
        lottieView.play(completion: { _ in
            //
        })
    }

    private func stopAnimation() {
        lottieView.stop()
    }
}
