using Mapster;

namespace DocuMed.PWA.Pages;

public class MedicalHistoryActionPageViewModel : BaseViewModel<MedicalHistoryLDto>
{
    private readonly IRestWrapper _restWrapper;
    private readonly NavigationManager _navigationManager;
    private readonly ISnackbar _snackbar;
    private readonly IUserUtility _userUtility;
    private readonly Guid _medicalHistoryId;

    public MedicalHistoryActionPageViewModel(IRestWrapper restWrapper,
        NavigationManager navigationManager,
        ISnackbar snackbar,
        IUserUtility userUtility)
    {
        _restWrapper = restWrapper;
        _navigationManager = navigationManager;
        _snackbar = snackbar;
        _userUtility = userUtility;
    }


    public MedicalHistoryActionPageViewModel(IRestWrapper restWrapper,
        NavigationManager navigationManager,
        ISnackbar snackbar,
        IUserUtility userUtility,
        Guid medicalHistoryId)
    {
        _restWrapper = restWrapper;
        _navigationManager = navigationManager;
        _snackbar = snackbar;
        _userUtility = userUtility;
        _medicalHistoryId = medicalHistoryId;
        IsEditing = true;
    }

    public MedicalHistoryTemplateSDto SelectedTemplate { get; set; } = new();
    public MedicalHistoryTemplateLDto SelectedTemplateLDto { get; set; } = new();

    public bool IsEditing { get; set; } = false;

    public SectionSDto? SelectedSelection { get; set; }
    public List<MedicalHistoryAnswerSDto> PiAnswers { get; set; } = new();
    public List<MedicalHistoryAnswerSDto> PdhAnswers { get; set; } = new();
    public List<MedicalHistoryAnswerSDto> PshAnswers { get; set; } = new();
    public List<MedicalHistoryAnswerSDto> FhAnswers { get; set; } = new();
    public List<MedicalHistoryAnswerSDto> DhAnswers { get; set; } = new();
    public List<MedicalHistoryAnswerSDto> HhAnswers { get; set; } = new();
    public List<MedicalHistoryAnswerSDto> GaAnswers { get; set; } = new();
    public List<MedicalHistoryAnswerSDto> RosAnswers { get; set; } = new();

    public MudCarousel<object>? Carousel { get; set; }
    public int CurrentStep { get; set; } = 0;
    public string StepCounter { get; set; } = "1 / 5";
    public bool MedicalHistorySubmitted { get; set; } = false;

    public override async Task InitializeAsync()
    {
        if (_medicalHistoryId != Guid.Empty && IsEditing)
        {
            try
            {
                IsProcessing = true;
                var token = await _userUtility.GetBearerTokenAsync();
                var dto = await _restWrapper.CrudDtoApiRest<MedicalHistorySDto, MedicalHistoryLDto, Guid>(Address.MedicalHistoryController)
                    .ReadOne(_medicalHistoryId, token);
                PageDto = dto;
                SelectedSelection = dto.Section;
                PiAnswers.AddRange(dto.Answers.Where(q => q.Part == MedicalHistoryPart.PresentIllness));
                PdhAnswers.AddRange(dto.Answers.Where(q => q.Part == MedicalHistoryPart.PastDiseasesHistory));
                PshAnswers.AddRange(dto.Answers.Where(q => q.Part == MedicalHistoryPart.PastSurgeryHistory));
                FhAnswers.AddRange(dto.Answers.Where(q => q.Part == MedicalHistoryPart.FamilyHistory));
                DhAnswers.AddRange(dto.Answers.Where(q => q.Part == MedicalHistoryPart.DrugHistory));
                HhAnswers.AddRange(dto.Answers.Where(q => q.Part == MedicalHistoryPart.AddictionHistory));
                GaAnswers.AddRange(dto.Answers.Where(q => q.Part == MedicalHistoryPart.GeneralAppearance));
                RosAnswers.AddRange(dto.Answers.Where(q => q.Part == MedicalHistoryPart.ReviewOfSystem));
                if (dto.MedicalHistoryTemplateId != Guid.Empty)
                {
                    SelectedTemplate = new MedicalHistoryTemplateSDto { Id = dto.MedicalHistoryTemplateId };
                    await SelectTemplateAsync();
                }
            }
            catch (ApiException ex)
            {
                var exe = await ex.GetContentAsAsync<ApiResult>();
                _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
            }
            catch (Exception e)
            {
                _snackbar.Add(e.Message, Severity.Error);
            }
            finally
            {

                IsProcessing = false;
            }
        }
        await base.InitializeAsync();
    }

    public async Task CompleteStepClicked()
    {
        CurrentStep++;
        StepCounter = $"{CurrentStep + 1} / 5";
        if (CurrentStep == 1)
            await SelectTemplateAsync();
        if (CurrentStep == 5)
        {
            if (IsEditing)
                await EditMedicalHistoryAsync();
            else
                await SubmitMedicalHistoryAsync();
            MedicalHistorySubmitted = true;
        }
        Carousel?.MoveTo(CurrentStep);
    }

    private async Task SelectTemplateAsync()
    {
        try
        {
            if (SelectedTemplate.Id == Guid.Empty)
                return;

            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            var dto = await _restWrapper.CrudDtoApiRest<MedicalHistoryTemplateSDto, MedicalHistoryTemplateLDto, Guid>(Address.MedicalHistoryTemplateController)
                .ReadOne(SelectedTemplate.Id, token);

            SelectedTemplateLDto = dto;
            SelectedTemplate = dto.Adapt<MedicalHistoryTemplateSDto>();
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {

            IsProcessing = false;
        }
    }


    public async Task SubmitMedicalHistoryAsync()
    {
        try
        {
            IsProcessing = true;
            if (SelectedSelection == null)
                throw new Exception("لطفا بخش مورد نظر را انتخاب نمایید");
            PageDto.SectionId = SelectedSelection.Id;
            var token = await _userUtility.GetBearerTokenAsync();
            PageDto.Answers.AddRange(PiAnswers);
            PageDto.Answers.AddRange(PdhAnswers);
            PageDto.Answers.AddRange(PshAnswers);
            PageDto.Answers.AddRange(FhAnswers);
            PageDto.Answers.AddRange(DhAnswers);
            PageDto.Answers.AddRange(HhAnswers);
            PageDto.Answers.AddRange(GaAnswers);
            PageDto.Answers.AddRange(RosAnswers);
            await _restWrapper.CrudDtoApiRest<MedicalHistoryLDto, MedicalHistorySDto, Guid>(Address.MedicalHistoryController)
                .Create(PageDto, token);

        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {

            IsProcessing = false;
        }
    }

    public async Task EditMedicalHistoryAsync()
    {
        try
        {
            IsProcessing = true;
            if (SelectedSelection == null)
                throw new Exception("لطفا بخش مورد نظر را انتخاب نمایید");
            PageDto.SectionId = SelectedSelection.Id;
            var token = await _userUtility.GetBearerTokenAsync();
            PageDto.SectionId = SelectedSelection.Id;
            PageDto.Answers.AddRange(PiAnswers);
            PageDto.Answers.AddRange(PdhAnswers);
            PageDto.Answers.AddRange(PshAnswers);
            PageDto.Answers.AddRange(FhAnswers);
            PageDto.Answers.AddRange(DhAnswers);
            PageDto.Answers.AddRange(HhAnswers);
            PageDto.Answers.AddRange(GaAnswers);
            PageDto.Answers.AddRange(RosAnswers);
            await _restWrapper.CrudDtoApiRest<MedicalHistoryLDto, MedicalHistorySDto, Guid>(Address.MedicalHistoryController)
                .Update(PageDto, token);

        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {

            IsProcessing = false;
        }
    }

    public void RollBackStepClicked()
    {
        Carousel?.MoveTo(--CurrentStep);
        StepCounter = $"{CurrentStep + 1} / 5";
    }

    public void CompleteCreateMedicalHistory()
    {
        _navigationManager.NavigateTo("HomePage");
    }

}