@page "/admin/sites/create"
@page "/admin/sites/{Id:int}/edit"
@using ScadaLink.Security
@using ScadaLink.Commons.Entities.Sites
@using ScadaLink.Commons.Interfaces.Repositories
@using ScadaLink.Communication
@attribute [Authorize(Policy = AuthorizationPolicies.RequireAdmin)]
@inject ISiteRepository SiteRepository
@inject CommunicationService CommunicationService
@inject NavigationManager NavigationManager

<div class="container-fluid mt-3">
    <div class="mb-3">
        <button class="btn btn-outline-secondary btn-sm" @onclick="GoBack">
            &larr; Back
        </button>
    </div>

    <ToastNotification @ref="_toast" />

    <div class="card mb-3">
        <div class="card-body">
            <h6 class="card-title">@(IsEditMode ? "Edit Site" : "Add Site")</h6>
            <div class="mb-2">
                <label class="form-label small">Identifier</label>
                <input type="text" class="form-control form-control-sm" @bind="_formIdentifier"
                       disabled="@IsEditMode" />
            </div>
            <div class="mb-2">
                <label class="form-label small">Name</label>
                <input type="text" class="form-control form-control-sm" @bind="_formName" />
            </div>
            <div class="mb-3">
                <label class="form-label small">Description</label>
                <input type="text" class="form-control form-control-sm" @bind="_formDescription" />
            </div>

            <h6 class="text-muted border-bottom pb-1">Node A</h6>
            <div class="mb-2">
                <label class="form-label small">Akka Address</label>
                <input type="text" class="form-control form-control-sm" @bind="_formNodeAAddress"
                       placeholder="akka.tcp://scadalink@host:port/user/site-communication" />
            </div>
            <div class="mb-3">
                <label class="form-label small">gRPC Address</label>
                <input type="text" class="form-control form-control-sm" @bind="_formGrpcNodeAAddress"
                       placeholder="http://host:8083" />
            </div>

            <h6 class="text-muted border-bottom pb-1">Node B</h6>
            <div class="mb-2">
                <label class="form-label small">Akka Address</label>
                <input type="text" class="form-control form-control-sm" @bind="_formNodeBAddress"
                       placeholder="akka.tcp://scadalink@host:port/user/site-communication" />
            </div>
            <div class="mb-3">
                <label class="form-label small">gRPC Address</label>
                <input type="text" class="form-control form-control-sm" @bind="_formGrpcNodeBAddress"
                       placeholder="http://host:8083" />
            </div>

            @if (_formError != null)
            {
                <div class="text-danger small mt-2">@_formError</div>
            }
            <div class="mt-3">
                <button class="btn btn-success btn-sm me-1" @onclick="SaveSite">Save</button>
                <button class="btn btn-outline-secondary btn-sm" @onclick="GoBack">Cancel</button>
            </div>
        </div>
    </div>
</div>

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

    private bool IsEditMode => Id.HasValue;

    private Site? _editingSite;
    private string _formName = string.Empty;
    private string _formIdentifier = string.Empty;
    private string? _formDescription;
    private string? _formNodeAAddress;
    private string? _formNodeBAddress;
    private string? _formGrpcNodeAAddress;
    private string? _formGrpcNodeBAddress;
    private string? _formError;

    private ToastNotification _toast = default!;

    protected override async Task OnInitializedAsync()
    {
        if (Id.HasValue)
        {
            _editingSite = await SiteRepository.GetSiteByIdAsync(Id.Value);
            if (_editingSite != null)
            {
                _formName = _editingSite.Name;
                _formIdentifier = _editingSite.SiteIdentifier;
                _formDescription = _editingSite.Description;
                _formNodeAAddress = _editingSite.NodeAAddress;
                _formNodeBAddress = _editingSite.NodeBAddress;
                _formGrpcNodeAAddress = _editingSite.GrpcNodeAAddress;
                _formGrpcNodeBAddress = _editingSite.GrpcNodeBAddress;
            }
        }
    }

    private void GoBack()
    {
        NavigationManager.NavigateTo("/admin/sites");
    }

    private async Task SaveSite()
    {
        _formError = null;

        if (string.IsNullOrWhiteSpace(_formName))
        {
            _formError = "Name is required.";
            return;
        }

        try
        {
            if (_editingSite != null)
            {
                _editingSite.Name = _formName.Trim();
                _editingSite.Description = _formDescription?.Trim();
                _editingSite.NodeAAddress = _formNodeAAddress?.Trim();
                _editingSite.NodeBAddress = _formNodeBAddress?.Trim();
                _editingSite.GrpcNodeAAddress = _formGrpcNodeAAddress?.Trim();
                _editingSite.GrpcNodeBAddress = _formGrpcNodeBAddress?.Trim();
                await SiteRepository.UpdateSiteAsync(_editingSite);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(_formIdentifier))
                {
                    _formError = "Identifier is required.";
                    return;
                }
                var site = new Site(_formName.Trim(), _formIdentifier.Trim())
                {
                    Description = _formDescription?.Trim(),
                    NodeAAddress = _formNodeAAddress?.Trim(),
                    NodeBAddress = _formNodeBAddress?.Trim(),
                    GrpcNodeAAddress = _formGrpcNodeAAddress?.Trim(),
                    GrpcNodeBAddress = _formGrpcNodeBAddress?.Trim()
                };
                await SiteRepository.AddSiteAsync(site);
            }

            await SiteRepository.SaveChangesAsync();
            CommunicationService.RefreshSiteAddresses();
            NavigationManager.NavigateTo("/admin/sites");
        }
        catch (Exception ex)
        {
            _formError = $"Save failed: {ex.Message}";
        }
    }
}
