@page "/notifications/lists/create"
@page "/notifications/lists/{Id:int}/edit"
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
@inject INotificationRepository NotificationRepository
@inject NavigationManager NavigationManager

<div class="container-fluid mt-3">
    <button class="btn btn-link text-decoration-none ps-0 mb-2" @onclick="GoBack">&larr; Back</button>

    <h4 class="mb-3">@(Id.HasValue ? "Edit Notification List" : "Add Notification List")</h4>

    @if (_loading)
    {
        <LoadingSpinner IsLoading="true" />
    }
    else
    {
        <div class="card">
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Name</label>
                    <input type="text" class="form-control" @bind="_name" />
                </div>

                @if (_formError != null)
                {
                    <div class="text-danger small mb-2">@_formError</div>
                }

                <div class="d-flex gap-2">
                    <button class="btn btn-success" @onclick="Save">Save</button>
                    <button class="btn btn-outline-secondary" @onclick="GoBack">Cancel</button>
                </div>
            </div>
        </div>

        @if (Id.HasValue)
        {
            <h5 class="mt-4 mb-3">Recipients</h5>

            <div class="card mb-3">
                <div class="card-body">
                    <div class="mb-2">
                        <label class="form-label">Name</label>
                        <input type="text" class="form-control" @bind="_recipientName" />
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" @bind="_recipientEmail" />
                    </div>
                    @if (_recipientFormError != null)
                    {
                        <div class="text-danger small mt-2">@_recipientFormError</div>
                    }
                    <div class="mt-3">
                        <button class="btn btn-success" @onclick="SaveRecipient">Add</button>
                    </div>
                </div>
            </div>

            <table class="table table-sm table-striped">
                <thead class="table-light">
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th style="width:80px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @if (_recipients.Count == 0)
                    {
                        <tr><td colspan="3" class="text-muted small">No recipients.</td></tr>
                    }
                    else
                    {
                        @foreach (var r in _recipients)
                        {
                            <tr>
                                <td>@r.Name</td>
                                <td>@r.EmailAddress</td>
                                <td>
                                    <button class="btn btn-outline-danger btn-sm py-0 px-1" @onclick="() => DeleteRecipient(r)">Delete</button>
                                </td>
                            </tr>
                        }
                    }
                </tbody>
            </table>
        }
    }
</div>

@code {
    [Parameter] public int? Id { get; set; }

    private bool _loading = true;
    private string _name = "";
    private string? _formError;

    private NotificationList? _existing;

    // Recipients
    private List<NotificationRecipient> _recipients = new();
    private string _recipientName = "", _recipientEmail = "";
    private string? _recipientFormError;

    protected override async Task OnInitializedAsync()
    {
        if (Id.HasValue)
        {
            try
            {
                _existing = await NotificationRepository.GetNotificationListByIdAsync(Id.Value);
                if (_existing != null)
                {
                    _name = _existing.Name;
                }
                _recipients = (await NotificationRepository.GetRecipientsByListIdAsync(Id.Value)).ToList();
            }
            catch (Exception ex) { _formError = ex.Message; }
        }
        _loading = false;
    }

    private async Task Save()
    {
        _formError = null;
        if (string.IsNullOrWhiteSpace(_name))
        {
            _formError = "Name required.";
            return;
        }

        try
        {
            if (_existing != null)
            {
                _existing.Name = _name.Trim();
                await NotificationRepository.UpdateNotificationListAsync(_existing);
            }
            else
            {
                var nl = new NotificationList(_name.Trim());
                await NotificationRepository.AddNotificationListAsync(nl);
            }
            await NotificationRepository.SaveChangesAsync();
            NavigationManager.NavigateTo("/notifications/lists");
        }
        catch (Exception ex) { _formError = ex.Message; }
    }

    private async Task SaveRecipient()
    {
        _recipientFormError = null;
        if (string.IsNullOrWhiteSpace(_recipientName) || string.IsNullOrWhiteSpace(_recipientEmail))
        {
            _recipientFormError = "Name and email required.";
            return;
        }

        try
        {
            var r = new NotificationRecipient(_recipientName.Trim(), _recipientEmail.Trim())
            {
                NotificationListId = Id!.Value
            };
            await NotificationRepository.AddRecipientAsync(r);
            await NotificationRepository.SaveChangesAsync();
            _recipientName = _recipientEmail = string.Empty;
            _recipients = (await NotificationRepository.GetRecipientsByListIdAsync(Id.Value)).ToList();
        }
        catch (Exception ex) { _recipientFormError = ex.Message; }
    }

    private async Task DeleteRecipient(NotificationRecipient r)
    {
        try
        {
            await NotificationRepository.DeleteRecipientAsync(r.Id);
            await NotificationRepository.SaveChangesAsync();
            _recipients = (await NotificationRepository.GetRecipientsByListIdAsync(Id!.Value)).ToList();
        }
        catch (Exception ex) { _recipientFormError = ex.Message; }
    }

    private void GoBack() => NavigationManager.NavigateTo("/notifications/lists");
}
