namespace Netina.AdminPanel.PWA.Pages;

public class PagesSettingPageViewModel(NavigationManager navigationManager,
    ISnackbar snackbar,
    IUserUtility userUtility,
    IRestWrapper restWrapper,
    IDialogService dialogService) : BaseViewModel<PageSetting> (userUtility)
{
    public ObservableCollection<RedirectItem> RedirectItems { get; set; } = new ObservableCollection<RedirectItem> ();
    public ObservableCollection<DeletedPageItem> DeletedPages { get; set; } = new ObservableCollection<DeletedPageItem> ();

    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.SettingRestApi.GetSettingAsync<PageSetting>(nameof(PageSetting), token);
            PageDto = pages;
            RedirectItems.Clear();
            if (PageDto.RedirectItems.Count > 20)
                RedirectItemPageCount = RedirectItemsCurrentPage + 2;
            PageDto.RedirectItems.Skip(RedirectItemsCurrentPage * 20).Take(20).ToList().ForEach(a=>RedirectItems.Add(a));

            DeletedPages.Clear();
            if (PageDto.DeletedPages.Count > 20)
                DeletedPagesCount = DeletedPagesCurrentPage + 2;
            PageDto.DeletedPages.Skip(DeletedPagesCurrentPage * 20).Take(20).ToList().ForEach(a => DeletedPages.Add(a));
        }
        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 int RedirectItemsCurrentPage { get; set; } = 0;
    public int RedirectItemPageCount { get; set; } = 0;
    public void RedirectItemChangePageAsync(int page)
    {
        RedirectItemsCurrentPage = page - 1;

        if (PageDto.RedirectItems.Count > (RedirectItemsCurrentPage * 20))
            RedirectItemPageCount = RedirectItemsCurrentPage + 2;

        PageDto.RedirectItems.Skip(RedirectItemsCurrentPage * 20).Take(20).ToList().ForEach(a => RedirectItems.Add(a));
    }

    public RedirectItem NewRedirectItem { 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 (NewRedirectItem.OldUrl.IsNullOrEmpty())
                throw new AppException("لینک قدیمی را وارد کنید");
            if (NewRedirectItem.NewUrl.IsNullOrEmpty())
                throw new AppException("لینک جدید را وارد کنید");
            var newUrl = StringExtensions.GetSlug(NewRedirectItem.NewUrl);
            var oldUrl = StringExtensions.GetSlug(NewRedirectItem.OldUrl);
            var item = new RedirectItem
            {
                NewUrl = newUrl,
                OldUrl = oldUrl
            };
            if (PageDto.RedirectItems.Any(c => c.OldUrl == item.OldUrl))
                throw new AppException("لینک مورد نظر قبلا اضافه شده است");
            PageDto.RedirectItems.Add(item);
            await restWrapper.SettingRestApi.PostSettingAsync(nameof(PageSetting), PageDto, token);
            NewRedirectItem = new RedirectItem();
            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 RemovePageAsync(RedirectItem item)
    {
        try
        {
            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            PageDto.RedirectItems.Remove(item);
            await restWrapper.SettingRestApi.PostSettingAsync(nameof(PageSetting), PageDto, 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;
        }
    }

    public DeletedPageItem NewDeletedPage { get; set; } = new();
    public async Task AddDeletedPage()
    {

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

            if (NewDeletedPage.Url.IsNullOrEmpty())
                throw new AppException("لینک حذف شده را وارد کنید");
            var item = new DeletedPageItem()
            {
                Url = NewDeletedPage.Url
            };
            if (PageDto.DeletedPages.Any(c => c.Url == item.Url))
                throw new AppException("لینک مورد نظر قبلا اضافه شده است");

            PageDto.DeletedPages.Add(NewDeletedPage);
            DeletedPages.Add(NewDeletedPage);
            await restWrapper.SettingRestApi.PostSettingAsync(nameof(PageSetting), PageDto, token);
            NewRedirectItem = new RedirectItem();
            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 RemoveDeletedPageAsync(DeletedPageItem item)
    {
        try
        {
            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            PageDto.DeletedPages.Remove(item);
            await restWrapper.SettingRestApi.PostSettingAsync(nameof(PageSetting), PageDto, 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;
        }
    }

    public int DeletedPagesCurrentPage { get; set; } = 0;
    public int DeletedPagesCount { get; set; } = 0;
    public void DeletedPagesChangePageAsync(int page)
    {
        DeletedPagesCurrentPage = page - 1;

        if (PageDto.RedirectItems.Count > (DeletedPagesCurrentPage * 20))
            DeletedPagesCount = DeletedPagesCurrentPage + 2;

        PageDto.DeletedPages.Skip(DeletedPagesCurrentPage * 20).Take(20).ToList().ForEach(a => DeletedPages.Add(a));
    }
}