@using Indotalent.Features.Setting.AutoNumberSequence.Cqrs
@using Indotalent.Shared.Utils
@using MudBlazor
@inject AutoNumberSequenceService AutoNumberSequenceService
@inject ISnackbar Snackbar

<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
    <div class="d-flex align-center gap-4">
        <MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
        <div>
            <MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@GetTitle()</MudText>
            <MudText Typo="Typo.body2" Style="color: #64748b;">Adjust the numbering rules and template formats for system entities.</MudText>
        </div>
    </div>
</MudPaper>

<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
    <MudForm @ref="_form" Model="_model">
        <MudGrid Spacing="3">
            <MudItem xs="12">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Entity Name</MudText>
                <MudTextField @bind-Value="_model.EntityName"
                              ReadOnly="true"
                              Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true"
                              HelperText="Entity name cannot be changed." />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Prefix Template</MudText>
                <MudTextField @bind-Value="_model.PrefixTemplate"
                              For="@(() => _model.PrefixTemplate)"
                              Validation="@(_validator.ValidateValue())"
                              ReadOnly="ReadOnly"
                              Placeholder="e.g., INV-"
                              Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Suffix Template</MudText>
                <MudTextField @bind-Value="_model.SuffixTemplate"
                              For="@(() => _model.SuffixTemplate)"
                              Validation="@(_validator.ValidateValue())"
                              ReadOnly="ReadOnly"
                              Placeholder="e.g., -EXT"
                              Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>

            @if (ReadOnly)
            {
                <MudItem xs="12" sm="4">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Current Sequence</MudText>
                    <MudTextField Value="@ExistingData?.CurrentSequence" ReadOnly="true" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
                </MudItem>
                <MudItem xs="12" sm="4">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Padding Length</MudText>
                    <MudTextField Value="@ExistingData?.PaddingLength" ReadOnly="true" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
                </MudItem>
                <MudItem xs="12" sm="4">
                    <MudText Typo="Typo.subtitle2" Class="mb-1">Period</MudText>
                    <MudTextField Value="@($"{ExistingData?.Year} / {ExistingData?.Month}")" ReadOnly="true" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
                </MudItem>
            }
        </MudGrid>

        <div class="d-flex justify-end gap-2 mt-8">
            <MudButton OnClick="() => OnCancel.InvokeAsync()"
                       Variant="Variant.Outlined"
                       Disabled="_processing"
                       Style="border-radius: 4px; border: 1px solid #e0e0e0; text-transform: none; font-weight: 700;">
                @(ReadOnly ? "Back to List" : "Cancel")
            </MudButton>

            @if (!ReadOnly)
            {
                <MudButton Color="Color.Primary"
                           Variant="Variant.Filled"
                           OnClick="Submit"
                           Disabled="_processing"
                           Style="border-radius: 4px; text-transform: none; font-weight: 700;">
                    @if (_processing)
                    {
                        <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
                        <MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
                    }
                    else
                    {
                        <MudText>Save Changes</MudText>
                    }
                </MudButton>
            }
        </div>
    </MudForm>
</MudPaper>

@code {
    [Parameter] public GetAutoNumberSequenceListResponse? ExistingData { get; set; }
    [Parameter] public bool ReadOnly { get; set; } = false;
    [Parameter] public EventCallback OnCancel { get; set; }
    [Parameter] public EventCallback OnSuccess { get; set; }

    private MudForm _form = default!;
    private UpdateAutoNumberSequenceValidator _validator = new();
    private UpdateAutoNumberSequenceRequest _model = new();
    private bool _processing = false;

    protected override void OnInitialized()
    {
        if (ExistingData != null)
        {
            _model = new UpdateAutoNumberSequenceRequest
            {
                Id = ExistingData.Id,
                EntityName = ExistingData.EntityName,
                PrefixTemplate = ExistingData.PrefixTemplate,
                SuffixTemplate = ExistingData.SuffixTemplate
            };
        }
    }

    private string GetTitle()
    {
        if (ReadOnly) return "Auto Number Details";
        return "Edit Auto Number Template";
    }

    private async Task Submit()
    {
        if (ReadOnly) return;

        await _form.Validate();
        if (!_form.IsValid) return;

        _processing = true;
        try
        {
            var response = await AutoNumberSequenceService.UpdateAutoNumberSequenceAsync(_model);

            await Task.Delay(500);

            if (response?.IsSuccess ?? false)
            {
                Snackbar.Add("Template updated successfully", Severity.Success);
                await OnSuccess.InvokeAsync();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"System Error: {ex.Message}", Severity.Error);
        }
        finally
        {
            _processing = false;
        }
    }
}