using Force.DeepCloner;

namespace Netina.AdminPanel.PWA.Pages;

public class PagesManagementPageViewModel(
    NavigationManager navigationManager,
    ISnackbar snackbar,
    IUserUtility userUtility,
    IRestWrapper restWrapper,
    IDialogService dialogService)
    : BaseViewModel<ObservableCollection<BasePageSDto>>(userUtility)
{
    private readonly IUserUtility _userUtility = userUtility;
    private readonly IDialogService _dialogService = dialogService;

    public override async Task InitializeAsync()
    {
        try
        {
            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            var pages = await restWrapper.PageRestApi.ReadAll(token);
            PageDto.Clear();
            pages.ForEach(p=>PageDto.Add(p));
        }
        catch (ApiException e)
        {
            var exe = await e.GetContentAsAsync<ApiResult>();
            if (e.StatusCode == HttpStatusCode.Unauthorized)
            {
                await _userUtility.LogoutAsync();
                navigationManager.NavigateTo("login", true, true);
            }
            snackbar.Add(exe != null ? exe.Message : e.Content, Severity.Error);
        }
        catch (Exception ex)
        {
            snackbar.Add(ex.Message, Severity.Error);
        }
        finally
        {
            IsProcessing = false;
        }

        await base.InitializeAsync();
    }

    public PageActionRequestDto NewPageDto { get; set; } = new();

    public async Task AddPageAsync()
    {
        try
        {
            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");

            if (NewPageDto.Title.IsNullOrEmpty())
                throw new AppException("عنوان صفحه را وارد کنید");
            if (NewPageDto.Slug.IsNullOrEmpty())
                throw new AppException("اسلاگ صفحه را وارد کنید");

            await restWrapper.PageRestApi.CreatePage(NewPageDto.DeepClone(), token);
            NewPageDto = new PageActionRequestDto();
            snackbar.Add("برگه مورد نظر با موفقیت افزوده شد", Severity.Success);
            await InitializeAsync();

        }
        catch (ApiException e)
        {
            var exe = await e.GetContentAsAsync<ApiResult>();
            if (e.StatusCode == HttpStatusCode.Unauthorized)
            {
                await _userUtility.LogoutAsync();
                navigationManager.NavigateTo("login", true, true);
            }
            snackbar.Add(exe != null ? exe.Message : e.Content, Severity.Error);
        }
        catch (Exception ex)
        {
            snackbar.Add(ex.Message, Severity.Error);
        }
        finally
        {
            IsProcessing = false;
        }
    }

    public async Task EditPageAsync(BasePageSDto page)
    {
        DialogOptions maxWidth = new DialogOptions() { MaxWidth = MaxWidth.Medium, FullWidth = true, DisableBackdropClick = true };
        var parameters = new DialogParameters<PageActionDialogBox>();
        parameters.Add(x => x.Page, page);
        var dialogResult = await dialogService.ShowAsync<PageActionDialogBox>($"ویرایش صفحه {page.Title}", parameters, maxWidth);
        var result = await dialogResult.Result;
        if (!result.Canceled && result.Data is bool and true)
        {
            await InitializeAsync();
        }
    }

    public async Task RemovePageAsync(Guid pageId)
    {
        try
        {
            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");

            await restWrapper.PageRestApi.DeletePage(pageId, token);
            snackbar.Add("برگه مورد نظر با موفقیت حذف شد", Severity.Success);
            await InitializeAsync();


        }
        catch (ApiException e)
        {
            var exe = await e.GetContentAsAsync<ApiResult>();
            if (e.StatusCode == HttpStatusCode.Unauthorized)
            {
                await _userUtility.LogoutAsync();
                navigationManager.NavigateTo("login", true, true);
            }
            snackbar.Add(exe != null ? exe.Message : e.Content, Severity.Error);
        }
        catch (Exception ex)
        {
            snackbar.Add(ex.Message, Severity.Error);
        }
        finally
        {
            IsProcessing = false;
        }
    }

}