@using CouchLog.Data
@using Microsoft.EntityFrameworkCore
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Identity
@using System.ComponentModel.DataAnnotations

@inject ApplicationDbContext CouchLogDB
@inject UserManager<ApplicationUser> UserManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
@inject ISnackbar Snackbar

<style>
    .mud-file-upload-dragarea {
        height: 400px;
        width: 100%;
    }
</style>

<MudDialog>
    <TitleContent>
        <MudText Typo="Typo.h6">Add Global Entity</MudText>
    </TitleContent>

    <DialogContent>
        <EditForm EditContext="_editContext" OnSubmit="HandleSubmit">
            <DataAnnotationsValidator />

            <MudStack Row="true" Spacing="3" AlignItems="AlignItems.Start" Style="min-height: 400px;">
                <!--<editor-fold desc="Picture-Upload">-->
                <MudPaper Class="pa-0" Elevation="0" Width="280px" MinWidth="280px">
                    @if (!string.IsNullOrWhiteSpace(_imagePreview))
                    {
                        <MudImage Src="@_imagePreview"
                                  ObjectFit="ObjectFit.Contain"
                                  Class="rounded" 
                                  Style="width: 280px; height: 400px;"/>
                    }
                    else
                    {
                        <MudFileUpload @bind-Files="_pictureFile"
                                       DragAndDrop="true"
                                       OnFilesChanged="OnPictureUploaded"
                                       Accept="image/*"
                                       InputClass="null"
                                       Class="mud-file-upload-dragarea">
                            <SelectedTemplate Context="SelectedTemplateContext"/>
                        </MudFileUpload>
                    }
                </MudPaper>
                <!--</editor-fold>-->
                
                <MudPaper Class="flex-grow-1" Elevation="0">
                    <MudStack Spacing="3">

                        <MudTextField @bind-Value="_form.Title"
                                      Label="Title"
                                      For="@(() => _form.Title)"
                                      Variant="Variant.Outlined" />

                        <MudSelect T="int"
                                   @bind-Value="_selectedMediaTypeId"
                                   Label="Type"
                                   Variant="Variant.Outlined">
                            @foreach (var type in _mediaTypes)
                            {
                                <MudSelectItem T="int" Value="@type.Id">@type.Name</MudSelectItem>
                            }
                        </MudSelect>

                        <MudSelect T="int"
                                   Label="Genres"
                                   MultiSelection="true"
                                   @bind-SelectedValues="_selectedGenreIds"
                                   Variant="Variant.Outlined">
                            @foreach (var genre in _genres)
                            {
                                <MudSelectItem T="int" Value="@genre.Id">@genre.Name</MudSelectItem>
                            }
                        </MudSelect>
                        <MudCheckBox @bind-Value="_isPrivate" Label="Is Private" Color="Color.Primary" />
                        <MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Success" Disabled="_isSaving" Class="mt-3">
                            @if (_isSaving)
                            {
                                <MudProgressCircular Indeterminate="true" Size="Size.Small" Class="mr-2" />
                                <span>Saving...</span>
                            }
                            else
                            {
                                <span>Create Global Entity</span>
                            }
                        </MudButton>
                    </MudStack>
                </MudPaper>
            </MudStack>
        </EditForm>
    </DialogContent>

    <DialogActions>
        <MudButton OnClick="Cancel" Variant="Variant.Text" Disabled="_isSaving">Cancel</MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter]
    private IMudDialogInstance MudDialog { get; set; } = null!;

    private ApplicationUser? _appUser;
    private EditContext _editContext = null!;

    private List<MediaType> _mediaTypes = new();
    private List<Genre> _genres = new();

    private GlobalEntityFormModel _form = new();
    private string? _imagePreview;
    private int _selectedMediaTypeId;
    private bool _isPrivate;
    private bool _isSaving;
    private IReadOnlyCollection<int> _selectedGenreIds = Array.Empty<int>();
    
    //Picture
    private IBrowserFile? _pictureFile;

    private class GlobalEntityFormModel
    {
        [Required(ErrorMessage = "Title is required.")]
        [MaxLength(200, ErrorMessage = "Title may not exceed 200 characters.")]
        public string Title { get; set; } = string.Empty;
    }

    protected override async Task OnInitializedAsync()
    {
        _editContext = new EditContext(_form);

        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        _appUser = await UserManager.GetUserAsync(authState.User);

        if (_appUser is null)
        {
            Snackbar.Add("Not authenticated.", Severity.Error);
            MudDialog.Cancel();
            return;
        }

        _mediaTypes = await CouchLogDB.MediaType.OrderBy(t => t.Id).ToListAsync();
        _genres = await CouchLogDB.Genres.OrderBy(t => t.Id).ToListAsync();

        if (_mediaTypes.Count > 0)
            _selectedMediaTypeId = _mediaTypes.First().Id;
    }

    private async Task OnPictureUploaded()
    {
        if (_pictureFile == null)
        {
            Snackbar.Add("No file selected!", Severity.Warning);
            return;
        }
        if (_pictureFile.Size > 5242880)
        {
            Snackbar.Add("File size exceeds 5MB!", Severity.Error);
            return;
        }
        await using var stream = _pictureFile.OpenReadStream(5242880);
        using var ms = new MemoryStream();
        await stream.CopyToAsync(ms);

        var base64 = Convert.ToBase64String(ms.ToArray());
        _imagePreview = $"data:{_pictureFile.ContentType};base64,{base64}";
    }

    private void Cancel() => MudDialog.Cancel();

    private async Task HandleSubmit(EditContext ctx)
    {
        if (!ctx.Validate()) return;

        if (_pictureFile is null)
        {
            Snackbar.Add("Please upload a picture.", Severity.Warning);
            return;
        }

        if (_selectedMediaTypeId == 0)
        {
            Snackbar.Add("Please select a media type.", Severity.Warning);
            return;
        }

        _isSaving = true;

        try
        {
            string fileName = $"{Guid.NewGuid()}{Path.GetExtension(_pictureFile.Name)}";
            string picturePath = Path.Combine("wwwroot", "Pictures", fileName);

            await using (var fs = File.Create(picturePath))
            {
                await _pictureFile.OpenReadStream(maxAllowedSize: 10_000_000).CopyToAsync(fs);
            }

            var entity = new GlobalEntity
            {
                Title = _form.Title,
                PicturePath = $"Pictures/{fileName}",
                CreatorId = _appUser!.Id,
                TypeId = _selectedMediaTypeId,
                CreationTime = DateTime.UtcNow,
                IsPrivate = _isPrivate
            };

            CouchLogDB.Add(entity);
            await CouchLogDB.SaveChangesAsync();

            foreach (int genreId in _selectedGenreIds)
            {
                CouchLogDB.Add(new LinkTableGlobalGenre
                {
                    GenreId = genreId,
                    GlobalEntityId = entity.Id
                });
            }

            await CouchLogDB.SaveChangesAsync();

            Snackbar.Add("Global Entity created!", Severity.Success);
            MudDialog.Close(DialogResult.Ok(entity));
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Error: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSaving = false;
        }
    }
}