using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using QuizPleaseTest.Boot.Settings;
using QuizPleaseTest.Boot.UI;
using QuizPleaseTest.Common.StateMachine;
using UniRx;
using UnityEngine;

namespace QuizPleaseTest.Boot.States
{
    public class LoadState : IState
    {
        private readonly LoadingUIView _view;
        private readonly BootStatusUIView _statusView;
        private readonly BootSettings _settings;
        private readonly ReactiveProperty<float> _progress = new ReactiveProperty<float>(0f);

        public IReadOnlyReactiveProperty<float> Progress => _progress;

        public LoadState(LoadingUIView view, BootStatusUIView statusView, BootSettings settings)
        {
            _view = view;
            _statusView = statusView;
            _settings = settings;
        }

        public async UniTask EnterAsync(CancellationToken ct)
        {
            _progress.Value = 0f;
            _statusView.SetStatus("Loading 0%");
            _statusView.SetProgress(0f);

            _view.Bind(new LoadingUIViewModel(Progress));
            _view.Initialize();

            int loadSteps = _settings.LoadSteps > 0 ? _settings.LoadSteps : 1;
            int stepDurationMs = _settings.LoadStepDurationMs > 0 ? _settings.LoadStepDurationMs : 0;

            try
            {
                for (int step = 1; step <= loadSteps; step++)
                {
                    await UniTask.Delay(stepDurationMs, cancellationToken: ct);
                    float progress = (float)step / loadSteps;
                    _progress.Value = progress;
                    _statusView.SetStatus($"Loading {Mathf.RoundToInt(progress * 100f)}%");
                    _statusView.SetProgress(progress);
                }
            }
            catch (OperationCanceledException) when (ct.IsCancellationRequested)
            {
                _view.Release();
                throw;
            }
        }

        public UniTask ExitAsync(CancellationToken ct)
        {
            _view.Release();
            return UniTask.CompletedTask;
        }
    }
}
