@page "/admin/ldap-mappings"
@attribute [Authorize(Policy = AuthorizationPolicies.RequireAdmin)]
@using ScadaLink.Commons.Entities.Security
@using ScadaLink.Commons.Interfaces.Repositories
@using ScadaLink.Security
@inject ISecurityRepository SecurityRepository
@inject NavigationManager NavigationManager

<div class="container-fluid mt-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="mb-0">LDAP Group Mappings</h4>
        <button class="btn btn-primary btn-sm" @onclick='() => NavigationManager.NavigateTo("/admin/ldap-mappings/create")'>Add Mapping</button>
    </div>

    @if (_loading)
    {
        <p class="text-muted">Loading...</p>
    }
    else if (_errorMessage != null)
    {
        <div class="alert alert-danger">@_errorMessage</div>
    }
    else
    {
        <div class="mb-3" style="max-width: 320px;">
            <input class="form-control form-control-sm"
                   placeholder="Filter by name, LDAP group, or role…"
                   @bind="_search" @bind:event="oninput" />
        </div>

        @if (_mappings.Count == 0)
        {
            <p class="text-muted text-center">No mappings configured.</p>
        }
        else if (!FilteredMappings.Any())
        {
            <p class="text-muted small">No mappings match the filter.</p>
        }
        else
        {
            <table class="table table-sm table-striped table-hover">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>LDAP Group Name</th>
                        <th>Role</th>
                        <th>Site Scope</th>
                        <th style="width: 160px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var mapping in FilteredMappings)
                    {
                        var rules = _scopeRules.GetValueOrDefault(mapping.Id);
                        var ruleCount = rules?.Count ?? 0;
                        <tr @key="mapping.Id">
                            <td>@mapping.Id</td>
                            <td>@mapping.LdapGroupName</td>
                            <td><span class="badge bg-secondary">@mapping.Role</span></td>
                            <td>
                                @if (ruleCount > 0)
                                {
                                    <span class="badge bg-info text-dark">@ruleCount rule(s)</span>
                                }
                                else
                                {
                                    <span class="text-muted small">All sites</span>
                                }
                            </td>
                            <td>
                                <div class="d-flex gap-1">
                                    <button class="btn btn-outline-primary btn-sm py-0 px-2"
                                            @onclick='() => NavigationManager.NavigateTo($"/admin/ldap-mappings/{mapping.Id}/edit")'>Edit</button>
                                    <div class="dropdown">
                                        <button class="btn btn-outline-secondary btn-sm py-0 px-2"
                                                data-bs-toggle="dropdown"
                                                aria-label="@($"More actions for {mapping.LdapGroupName}")">⋮</button>
                                        <ul class="dropdown-menu dropdown-menu-end">
                                            <li>
                                                <button class="dropdown-item text-danger"
                                                        @onclick="() => DeleteMapping(mapping.Id)">
                                                    Delete
                                                </button>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        }
    }
</div>

@code {
    private List<LdapGroupMapping> _mappings = new();
    private Dictionary<int, List<SiteScopeRule>> _scopeRules = new();
    private bool _loading = true;
    private string? _errorMessage;
    private string _search = string.Empty;

    private IEnumerable<LdapGroupMapping> FilteredMappings =>
        string.IsNullOrWhiteSpace(_search)
            ? _mappings
            : _mappings.Where(m =>
                (m.LdapGroupName?.Contains(_search, StringComparison.OrdinalIgnoreCase) ?? false) ||
                (m.Role?.Contains(_search, StringComparison.OrdinalIgnoreCase) ?? false));

    protected override async Task OnInitializedAsync()
    {
        await LoadDataAsync();
    }

    private async Task LoadDataAsync()
    {
        _loading = true;
        _errorMessage = null;
        try
        {
            _mappings = (await SecurityRepository.GetAllMappingsAsync()).ToList();
            _scopeRules.Clear();
            foreach (var mapping in _mappings)
            {
                var rules = await SecurityRepository.GetScopeRulesForMappingAsync(mapping.Id);
                if (rules.Count > 0)
                {
                    _scopeRules[mapping.Id] = rules.ToList();
                }
            }
        }
        catch (Exception ex)
        {
            _errorMessage = $"Failed to load mappings: {ex.Message}";
        }
        _loading = false;
    }

    private async Task DeleteMapping(int id)
    {
        try
        {
            // Also delete scope rules for this mapping
            var rules = await SecurityRepository.GetScopeRulesForMappingAsync(id);
            foreach (var rule in rules)
            {
                await SecurityRepository.DeleteScopeRuleAsync(rule.Id);
            }
            await SecurityRepository.DeleteMappingAsync(id);
            await SecurityRepository.SaveChangesAsync();
            await LoadDataAsync();
        }
        catch (Exception ex)
        {
            _errorMessage = $"Delete failed: {ex.Message}";
        }
    }

}
