@namespace OpenArchival.Blazor.AdminPages.Shared
@using System.ComponentModel.DataAnnotations;
@using OpenArchival.DataAccess;
@using MudBlazor

<MudDialog>
    <TitleContent>
        <MudText Typo="Typo.h6">Create a Category</MudText>
    </TitleContent>
    <DialogContent>
        <MudForm @ref="_form">
            <MudTextField @bind-Value="ValidationModel.Name"
                          For="@(() => ValidationModel.Name)"
                          Label="Category Name"
                          Variant="Variant.Filled" />

            <MudDivider Class="pt-4" DividerType="DividerType.Middle"/>

            <MudText Typo="Typo.h6">Item Tag Identifier</MudText>
            <MudText Typo="Typo.subtitle2">This will be the format of the identifier used for each archive entry.</MudText>
            
            <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
                <MudText Typo="Typo.body2">Format Preview: </MudText>
                <MudText Type="Typo.body2" Color="Color.Primary">@FormatPreview</MudText>
            </MudStack>
            
            <MudTextField @bind-Value="ValidationModel.FieldSeparator"
                          @bind-Value:after="UpdateFormatPreview"
                          For="@(() => ValidationModel.FieldSeparator)"
                          Label="Field Separator"
                          Variant="Variant.Filled"
                          MaxLength="1" />

            <MudDivider Class="pt-4" />

            <MudNumericField 
                Value="ValidationModel.NumFields"
                ValueChanged="@((int newCount) => OnNumFieldsChanged(newCount))"
                Label="Number of fields in the item identifiers" 
                Variant="Variant.Filled" 
                Min="1"></MudNumericField>
            
            <MudDivider Class="pt-4" />

            <MudGrid Class="pr-2 pt-2 pb-2 pl-8" Justify="Justify.FlexStart" Spacing="3">
                @for (int index = 0; index < ValidationModel.FieldNames.Count; ++index)
                {
                    var localIndex = index;

                    <MudItem xs="12" sm="6" md="6">
                        <CategoryFieldCardComponent Index="localIndex"
                                                    FieldName="@ValidationModel.FieldNames[localIndex]"
                                                    FieldDescription="@ValidationModel.FieldDescriptions[localIndex]"
                                                    OnNameUpdate="HandleNameUpdate"
                                                    OnDescriptionUpdate="HandleDescriptionUpdate"/>
                    </MudItem>
                }
            </MudGrid>
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">Cancel</MudButton>
        <MudButton Color="Color.Primary" OnClick="Submit">OK</MudButton>
    </DialogActions>
</MudDialog>

@inject IArchiveCategoryProvider CategoryProvider;

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

    [Parameter]
    public CategoryValidationModel ValidationModel { get; set; } = default!;

    [Parameter]
    public bool IsUpdate { get; set; }

    [Parameter]
    public string OriginalName { get; set; } = string.Empty;


    private MudForm _form = default!;
    private string FormatPreview { get; set; } = string.Empty;

    protected override void OnParametersSet()
    {
        if (ValidationModel is null)
        {
            ValidationModel = new CategoryValidationModel { NumFields = 1 };
        } else
        {
            ValidationModel.NumFields = ValidationModel.FieldNames.Count; 
        }
    }

    private void OnNumFieldsChanged(int newCount)
    {
        if (newCount < 1) return; 
        ValidationModel.NumFields = newCount;
        UpdateStateFromModel();
    }

    private void UpdateStateFromModel()
    {
        ValidationModel.FieldNames ??= new List<string>();
        ValidationModel.FieldDescriptions ??= new List<string>();

        while (ValidationModel.FieldNames.Count < ValidationModel.NumFields)
        {
            ValidationModel.FieldNames.Add($"Field {ValidationModel.FieldNames.Count + 1}");
        }
        while (ValidationModel.FieldNames.Count > ValidationModel.NumFields)
        {
            ValidationModel.FieldNames.RemoveAt(ValidationModel.FieldNames.Count - 1);
        }

        while (ValidationModel.FieldDescriptions.Count < ValidationModel.NumFields)
        {
            ValidationModel.FieldDescriptions.Add("");
        }
        while (ValidationModel.FieldDescriptions.Count > ValidationModel.NumFields)
        {
            ValidationModel.FieldDescriptions.RemoveAt(ValidationModel.FieldDescriptions.Count - 1);
        }

        UpdateFormatPreview();
        StateHasChanged(); 
    }

    private void UpdateFormatPreview()
    {
        var fieldNames = ValidationModel.FieldNames.Select(name => string.IsNullOrEmpty(name) ? "<...>" : $"<{name}>");
        FormatPreview = string.Join(ValidationModel.FieldSeparator, fieldNames);
    }

    private async Task Submit()
    {
        await _form.Validate();
        if (!_form.IsValid) return;

        MudDialog.Close(DialogResult.Ok(ValidationModel));
    }

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

    // In your MudDialog component's @code block

    private void HandleNameUpdate((int Index, string NewValue) data)
    {
        if (data.Index < ValidationModel.FieldNames.Count)
        {
            ValidationModel.FieldNames[data.Index] = data.NewValue;
            UpdateFormatPreview(); // Update the preview in real-time
        }
    }

    private void HandleDescriptionUpdate((int Index, string NewValue) data)
    {
        if (data.Index < ValidationModel.FieldDescriptions.Count)
        {
            ValidationModel.FieldDescriptions[data.Index] = data.NewValue;
        }
    }
}