@using Netina.AdminPanel.PWA.Models.Api
@using Netina.AdminPanel.PWA.Models
@using Netina.Domain.Entities.Blogs

@inject ISnackbar Snackbar
@inject IRestWrapper RestWrapper
@inject IUserUtility UserUtility

<MudDialog class="mx-auto">
    <DialogContent>
        <MudStack>
            <MudDivider class="-mt-3" />
            <MudStack Spacing="0">

                <MudText Typo="Typo.h6">اطلاعات کلی</MudText>
                <MudText Typo="Typo.caption">اطلاعات کلی دسته بندی را به دقت وارد کنید</MudText>
            </MudStack>
            <MudGrid>
                <MudItem sm="12">
                    <MudTextField T="string" Label="نام دسته بندی" @bind-Value="@_name" Variant="Variant.Outlined"></MudTextField>
                </MudItem>
                <MudItem sm="12">
                    <MudTextField T="string" Label="توضیحاتــ" @bind-Value="@_description" Variant="Variant.Outlined"></MudTextField>
                </MudItem>

            </MudGrid>
        </MudStack>
    </DialogContent>
    <DialogActions>
        <MudStack Row="true" class="w-full mx-4 mb-2">

            @if (_isEditing)
            {
                <BaseButtonUi class="w-64 rounded-md" IsProcessing="@_isProcessing"
                              Icon="@Icons.Material.Outlined.Check"
                              Variant="Variant.Filled" Color="Color.Success"
                              Content="ثبت ویرایش" OnClickCallback="SubmitEditAsync" />
            }
            else
            {
                <BaseButtonUi class="w-64 rounded-md" IsProcessing="@_isProcessing"
                              Icon="@Icons.Material.Outlined.Check"
                              Variant="Variant.Filled" Color="Color.Success"
                              Content="تایید" OnClickCallback="SubmitCreateAsync" />
            }
            <MudSpacer />
            <MudButton Variant="Variant.Outlined" Size="Size.Large" Color="Color.Error" OnClick="Cancel">بستن</MudButton>
        </MudStack>
    </DialogActions>
</MudDialog>
@code {
    [CascadingParameter] MudDialogInstance MudDialog { get; set; }
    [Parameter]
    public BlogCategorySDto? BlogCategory { get; set; }

    void Cancel() => MudDialog.Cancel();
    private bool _isProcessing = false;
    private string _name = string.Empty;
    private string _description = string.Empty;
    private bool _isEditing;

    protected override Task OnParametersSetAsync()
    {
        if (BlogCategory != null)
        {
            _isEditing = true;
            _description = BlogCategory.Description;
            _name = BlogCategory.Name;
        }
        return base.OnParametersSetAsync();
    }

    private async Task SubmitCreateAsync()
    {
        try
        {
            if (_name.IsNullOrEmpty())
                throw new AppException("لطفا نام  دسته بندی را وارد کنید");
            _isProcessing = true;
            var token = await UserUtility.GetBearerTokenAsync();
            var request = new BlogCategorySDto{Name = _name,Description = _description};
            await RestWrapper.CrudApiRest<BlogCategory, Guid>(Address.BlogCategoryController).Create<BlogCategorySDto>(request, token);
            MudDialog.Close(DialogResult.Ok(true));
        }
        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;
        }
    }


    private async Task SubmitEditAsync()
    {
        try
        {
            if (BlogCategory == null)
                throw new AppException("دسته بندی به درستی ارسال نشده است");
            if (_name.IsNullOrEmpty())
                throw new AppException("لطفا نام دسته بندی را وارد کنید");
            _isProcessing = true;
            await Task.Delay(1000);
            var token = await UserUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            var request = new BlogCategorySDto {Id = BlogCategory.Id , Name = _name, Description = _description };
            await RestWrapper.CrudApiRest<BlogCategory, Guid>(Address.BlogCategoryController).Update<BlogCategorySDto>(request, token);
            MudDialog.Close();
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            Snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
            MudDialog.Cancel();
        }
        catch (Exception e)
        {
            Snackbar.Add(e.Message, Severity.Error);
            MudDialog.Cancel();
        }
        finally
        {

            _isProcessing = false;
        }
    }
}