using System.Net.Http.Json;

namespace Netina.AdminPanel.PWA.Pages.Personalization;

public class PersonalizationPageViewModel(IDialogService dialogService, IRestWrapper restWrapper,
        ISnackbar snackbar, NavigationManager navigationManager, IUserUtility userUtility)
    : BaseViewModel<PersonalizationSetting>(userUtility: userUtility)
{

    public override async Task InitializeAsync()
    {
        try
        {
            var token = await userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            var personalizationSetting = await restWrapper.SettingRestApi.GetSettingAsync<PersonalizationSetting>(nameof(PersonalizationSetting), token);
            personalizationSetting.Catalog = personalizationSetting.Catalog.OrderBy(c => c.Row).ToList();
            PageDto = personalizationSetting;
        }
        catch (ApiException ex)
        {

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


        await base.InitializeAsync();
    }

    public async Task SubmitSettingAsync()
    {
        try
        {
            var token = await userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");
            await restWrapper.SettingRestApi.PostSettingAsync(nameof(PersonalizationSetting), PageDto, token);
            snackbar.Add("تنظیمات شخصی سازی با موفقیت تغییر یافت", Severity.Success);

        }
        catch (ApiException ex)
        {

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

    public BannerItemModel NewBanner { get; set; } = new();
    public CatalogItemModel NewCatalogItem { get; set; } = new();

    public void AddBanner()
    {
        try
        {
            if (NewBanner.ImageLocation.IsNullOrEmpty())
                throw new Exception("تصویر بنر انتخاب نشده است");
            if (NewBanner.Title.IsNullOrEmpty())
                throw new Exception("عنوان بنر انتخاب نشده است");

            PageDto.Banners.Add(NewBanner);
            NewBanner = new BannerItemModel();
        }
        catch (Exception e)
        {
            snackbar.Add(e.Message, Severity.Error);
        }
    }
    public async Task SelectFileAsync()
    {
        DialogOptions maxWidth = new DialogOptions() { MaxWidth = MaxWidth.Large, FullWidth = true, DisableBackdropClick = true };
        var dialog = await dialogService.ShowAsync<StorageDialogBox>("انتخاب عکس", maxWidth);
        var result = await dialog.Result;
        var file = result.Data;
        if (file is StorageFileSDto storageFile)
        {
            NewBanner.ImageLocation = storageFile.FileLocation;

        }
    }

    public CatalogItemModel? SelectedCatalog { get; set; }
    public async Task<IEnumerable<CatalogItemModel>> SearchCatalog(string catelogName)
    {
        try
        {
            if (catelogName.IsNullOrEmpty())
                return PageDto.Catalog;
            return PageDto.Catalog.Where(f => f.PersianName.Contains(catelogName));
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
            return new List<CatalogItemModel>();
        }
        catch (Exception e)
        {
            snackbar.Add(e.Message, Severity.Error);
            return new List<CatalogItemModel>();
        }
    }

    public string CatalogImage { get; set; } = string.Empty;
    public async Task SelectCatalogFileAsync()
    {
        DialogOptions maxWidth = new DialogOptions() { MaxWidth = MaxWidth.Large, FullWidth = true, DisableBackdropClick = true };
        var dialog = await dialogService.ShowAsync<StorageDialogBox>("انتخاب عکس", maxWidth);
        var result = await dialog.Result;
        var file = result.Data;
        if (file is StorageFileSDto storageFile)
        {
            CatalogImage = storageFile.FileLocation;
        }
    }
    public void AddCatalogItem()
    {
        try
        {
            if (NewCatalogItem.EnglishName.IsNullOrEmpty())
                throw new Exception("نام انگلیسی را وارد کنید");
            if (NewCatalogItem.PersianName.IsNullOrEmpty())
                throw new Exception("نام فارسی ایتم کاتالوگ را وارد کنید");
            if (NewCatalogItem.Query.IsNullOrEmpty())
                throw new Exception("کوئری ایتم کاتالوگ را وارد کنید");
            if (SelectedCatalog != null)
            {
                NewCatalogItem.ParentId = SelectedCatalog.Id;
                NewCatalogItem.ParentName = SelectedCatalog.PersianName;
            }
            else
                NewCatalogItem.IsMain = true;

            if (!CatalogImage.IsNullOrEmpty())
                NewCatalogItem.ImageLocation = CatalogImage;
            CatalogImage = string.Empty;
            NewCatalogItem.Id = Guid.NewGuid();
            PageDto.Catalog.Add(NewCatalogItem);
            PageDto.Catalog = PageDto.Catalog.OrderBy(c => c.Row).ToList();
            NewCatalogItem = new CatalogItemModel();
        }
        catch (Exception e)
        {
            snackbar.Add(e.Message, Severity.Error);
        }
    }
}