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

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

<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 lg="6" md="6">
                    <MudTextField T="string" Label="نام فارسی برند" @bind-Value="@_persianName" Variant="Variant.Outlined"></MudTextField>
                </MudItem>
                <MudItem lg="6" md="6">
                    <MudTextField T="string" Label="نام انگلیسی برند" @bind-Value="@_englishName" Variant="Variant.Outlined"></MudTextField>
                </MudItem>
                <MudItem lg="6" md="6">
                    <MudSelect T="bool" Label="آیا صفحه شخصی دارد ؟" @bind-Value="@_hasSpecialPage" ToStringFunc="b=>b.ToPersianString()" Variant="Variant.Outlined" AnchorOrigin="Origin.BottomCenter">
                        <MudSelectItem T="bool" Value="true"></MudSelectItem>
                        <MudSelectItem T="bool" Value="false" />
                    </MudSelect>
                </MudItem>
                <MudItem lg="6" md="6">
                    <MudTextField T="string" Label="لینک صفحه شخصی برند" @bind-Value="@_pageUrl" Variant="Variant.Outlined"></MudTextField>
                </MudItem>
                <MudItem lg="12" md="12">
                    <MudTextField T="string" Label="توضیحاتــ" @bind-Value="@_description" Variant="Variant.Outlined"></MudTextField>
                </MudItem>
                <MudItem sm="12" md="12" lg="12">
                    <MudStack class="mt-1 mb-4" Spacing="0">

                        <MudText Typo="Typo.h6">تصاویر برند</MudText>
                        <MudText Typo="Typo.caption">می توانید برای برند چند تصویر اپلود کنید</MudText>
                    </MudStack>
                    <MudStack Row="true">
                        <MudIconButton HtmlTag="label"
                                       Color="Color.Info"
                                       Variant="Variant.Outlined"
                                       class="w-28 h-28"
                                       Size="Size.Large"
                                       Icon="@Icons.Material.Outlined.Wallpaper"
                                       OnClick="async () => await SelectFileAsync()">
                        </MudIconButton>
                        @foreach (var item in Files)
                        {
                            <div class="w-28 h-28">
                                <MudImage Src="@item.GetLink()" Elevation="25" Class="rounded-lg w-28 h-28 absolute" />

                                <MudIconButton DisableElevation="true"
                                               class="absolute m-1.5"
                                               Size="@Size.Small"
                                               Variant="@Variant.Filled"
                                               OnClick="() => RemoveFile(item)"
                                               Color="@Color.Error"
                                               Icon="@Icons.Material.Outlined.Delete" />
                                @if (item.IsHeader)
                                {
                                    <p class="bg-pink-500 px-1.5 py-0.5 absolute bottom-0 mr-2 rounded-lg text-white">هدر</p>
                                }
                                @if (item.IsPrimary)
                                {
                                    <p class="bg-blue-500 px-1.5 py-0.5 absolute bottom-0 mr-2 rounded-lg text-white">اصلی</p>
                                }
                            </div>
                        }

                    </MudStack>
                </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 BrandSDto? Brand { get; set; }

    void Cancel() => MudDialog.Cancel();
    public readonly ObservableCollection<StorageFileSDto> Files = new ObservableCollection<StorageFileSDto>();
    private bool _isProcessing = false;
    private string _persianName = string.Empty;
    private string _englishName = string.Empty;
    private string _description = string.Empty;
    private bool _hasSpecialPage;
    private bool _isEditing;
    private string _pageUrl = string.Empty;

    protected override async Task OnParametersSetAsync()
    {
        if (Brand != null)
        {
            _isEditing = true;
            try
            {
                _isProcessing = true;
                var response = await RestWrapper.CrudDtoApiRest<Brand, BrandLDto, Guid>(Address.BrandController).ReadOne(Brand.Id);
                var brandLDto = response;
                brandLDto.Files.ForEach(f => Files.Add(f));
                
                _hasSpecialPage = brandLDto.HasSpecialPage;
                _description = brandLDto.Description;
                _englishName = brandLDto.EnglishName;
                _persianName = brandLDto.PersianName;
            }
            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;
            }

        }
        await base.OnParametersSetAsync();
    }

    private async Task SubmitCreateAsync()
    {
        try
        {
            if (_englishName.IsNullOrEmpty())
                throw new AppException("لطفا نام  برند را وارد کنید");
            _isProcessing = true;
            var token = await UserUtility.GetBearerTokenAsync();
            if (token == null)
                throw new AppException("Token is null");
            var request = new CreateBrandCommand(_persianName, _englishName, _description, _hasSpecialPage, _pageUrl, Files.ToList());
            await RestWrapper.CrudApiRest<Brand, Guid>(Address.BrandController).Create<CreateBrandCommand>(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 (Brand == null)
                throw new AppException("برند به درستی ارسال نشده است");
            if (_englishName.IsNullOrEmpty())
                throw new AppException("لطفا نام برند را وارد کنید");
            _isProcessing = true;
            var token = await UserUtility.GetBearerTokenAsync();
            if (token == null)
                throw new AppException("Token is null");
            var request = new UpdateBrandCommand(Brand.Id, _persianName, _englishName, _description, _hasSpecialPage, _pageUrl, Files.ToList());
            await RestWrapper.CrudApiRest<Brand, Guid>(Address.BrandController).Update<UpdateBrandCommand>(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;
        }
    }


    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);
    }
}