namespace Netina.AdminPanel.PWA.Dialogs;

public class ProductCategoryActionDialogBoxViewModel:BaseViewModel
{
    private readonly ISnackbar _snackbar;
    private readonly IRestWrapper _restWrapper;
    private readonly IUserUtility _userUtility;
    private readonly MudDialogInstance _mudDialog;
    private readonly IDialogService _dialogService;

    public ProductCategoryActionDialogBoxViewModel(ISnackbar snackbar, IRestWrapper restWrapper, IUserUtility userUtility, MudDialogInstance mudDialog, IDialogService dialogService)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _userUtility = userUtility;
        _mudDialog = mudDialog;
        _dialogService = dialogService;
    }

    public ProductCategoryActionDialogBoxViewModel(ISnackbar snackbar, IRestWrapper restWrapper, IUserUtility userUtility, MudDialogInstance mudDialog, IDialogService dialogService,ProductCategorySDto category)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _userUtility = userUtility;
        _mudDialog = mudDialog;
        _dialogService = dialogService;
        Category = category;
    }
    public void Cancel() => _mudDialog.Cancel();

    public string Name = string.Empty;
    public string Description = string.Empty;
    public bool IsMain;
    public bool IsEditing = false;
    public readonly ObservableCollection<StorageFileSDto> Files = new ObservableCollection<StorageFileSDto>();

    private ProductCategorySDto? _category = null;
    [Parameter]
    public ProductCategorySDto? Category
    {
        get => _category;
        set
        {
            _category = value;
            if (_category != null)
            {
                IsEditing = true;
            }
        }
    }

    public override async Task InitializeAsync()
    {
        if (IsEditing && Category != null)
        {
            try
            {
                IsProcessing = true;
                var response = await _restWrapper.CrudDtoApiRest<ProductCategory,ProductCategoryLDto,Guid>(Address.ProductCategoryController).ReadOne(Category.Id);
                var categoryLDto = response;
                categoryLDto.Files.ForEach(f => Files.Add(f));
                SelectedCategory = new ProductCategorySDto { Id = categoryLDto.ParentId, Name = categoryLDto.ParentName };
                Name = categoryLDto.Name;
                Description = categoryLDto.Description;
                IsMain = categoryLDto.IsMain;
            }
            catch (ApiException ex)
            {
                var exe = await ex.GetContentAsAsync<ApiResult>();
                if (exe != null)
                    _snackbar.Add(exe.Message, Severity.Error);
                _snackbar.Add(ex.Content, Severity.Error);
                _mudDialog.Cancel();
            }
            catch (Exception e)
            {
                _snackbar.Add(e.Message, Severity.Error);
                _mudDialog.Cancel();
            }
            finally
            {

                IsProcessing = false;
            }
        };
    }
    public async Task SubmitCreateAsync()
    {
        try
        {
            if (Name.IsNullOrEmpty())
                throw new AppException("لطفا نام دسته را وارد کنید");
            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new AppException("Token is null");
            var request = new CreateProductCategoryCommand(Name,
                Description, 
                IsMain,
                SelectedCategory?.Id ?? default,
                Files.ToList(),
                Faqs,
                new Dictionary<string, string>());
            await _restWrapper.CrudApiRest<ProductCategory, Guid>(Address.ProductCategoryController).Create<CreateProductCategoryCommand>(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);
            _mudDialog.Cancel();
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
            _mudDialog.Cancel();
        }
        finally
        {

            IsProcessing = false;
        }
    }

    public async Task SubmitEditAsync()
    {
        try
        {
            if (Category == null)
                throw new AppException("دسته به درستی ارسال نشده است");
            if (Name.IsNullOrEmpty())
                throw new AppException("لطفا نام دسته را وارد کنید");
            IsProcessing = true;
            await Task.Delay(1000);
            var token = await _userUtility.GetBearerTokenAsync();
            var request = new UpdateProductCategoryCommand(Category.Id,
                Name,
                Description,
                IsMain,
                SelectedCategory?.Id ?? default,
                Files.ToList(),
                Faqs,
                new Dictionary<string, string>());
            await _restWrapper.CrudApiRest<ProductCategory, Guid>(Address.ProductCategoryController).Update<UpdateProductCategoryCommand>(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);
            _mudDialog.Cancel();
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
            _mudDialog.Cancel();
        }
        finally
        {

            IsProcessing = false;
        }
    }

    private List<ProductCategorySDto> _productCategories = new List<ProductCategorySDto>();
    public ProductCategorySDto? SelectedCategory;
    public async Task<IEnumerable<ProductCategorySDto>> SearchCategory(string city)
    {
        try
        {
            if (_productCategories.Count == 0)
            {
                _productCategories = await _restWrapper.ProductCategoryRestApi.ReadAll();
            }
            if (city.IsNullOrEmpty())
                return _productCategories;
            return _productCategories.Where(c => c.Name.Contains(city));
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
            return _productCategories;
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
            return _productCategories;
        }
    }



    public string FaqQuestion { get; set; } = string.Empty;
    public string FaqAnswer { get; set; } = string.Empty;
    public Dictionary<string, string> Faqs = new();
    public void AddFaq()
    {
        try
        {
            if (FaqAnswer.IsNullOrEmpty())
                throw new Exception("لطفا پاسخ را وارد کنید");

            if (FaqQuestion.IsNullOrEmpty())
                throw new Exception("لطفا سوال را وارد کنید");

            Faqs.Add(FaqQuestion, FaqAnswer);
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
        }
    }

    public async Task SelectFileAsync()
    {
        DialogOptions maxWidth = new DialogOptions() { MaxWidth = MaxWidth.Medium, 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)
            Files.Add(storageFile);
    }

    public void RemoveFile(StorageFileSDto file)
    {
        Files.Remove(file);
    }
}