@page "/db-admin"
@attribute [Authorize]
@inject IDbAdminService DbAdminSvc
@inject ILocalizationService Loc
@inject NavigationManager Navigation
@inject IAuthService AuthService

<PageTitle>Datenbank Administration - Author Buddy</PageTitle>

<div class="dbadmin-page">
    <h3>Datenbank Administration</h3>

    <div class="dbadmin-toolbar">
        <select @bind="selectedCollection" @bind:after="LoadRecords">
            @foreach (var c in collections)
            {
                <option value="@c.Name">@c.Name (@c.Count Einträge)</option>
            }
        </select>
        <span style="font-size:12px;color:var(--border-color);margin-left:8px;">
            @records.Count Einträge in "@selectedCollection"
        </span>
    </div>

    @if (records.Count == 0)
    {
        <p style="padding:24px;color:var(--border-color);">Leere Sammlung.</p>
    }
    else
    {
        <div class="dbadmin-table-wrapper">
            <table class="dbadmin-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        @foreach (var key in columnOrder)
                        {
                            <th>@key</th>
                        }
                        <th style="width:130px;">Aktionen</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var record in records)
                    {
                        <tr>
                            <td><strong>@record.Id</strong></td>
                            @foreach (var key in columnOrder)
                            {
                                <td class="dbadmin-cell" title="@(record.Fields.GetValueOrDefault(key) ?? "(null)")">
                                    @Truncate(record.Fields.GetValueOrDefault(key), 60)
                                </td>
                            }
                            <td class="dbadmin-actions">
                                <button class="btn btn-sm" @onclick="() => StartEdit(record)">Bearbeiten</button>
                                <button class="btn btn-sm btn-danger" @onclick="() => ConfirmDelete(record)">Löschen</button>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    }

    @if (!string.IsNullOrEmpty(statusMessage))
    {
        <div class="dbadmin-status">@statusMessage</div>
    }

    <button class="btn btn-secondary" @onclick='() => Navigation.NavigateTo("/settings")' style="margin-top:12px;">Zurück</button>
</div>

@if (editingRecord != null)
{
    <div class="modal-overlay" @onclick="CancelEdit">
        <div class="modal-dialog" @onclick:stopPropagation>
            <div class="modal-title">Datensatz bearbeiten (ID: @editingRecord.Id) — @selectedCollection</div>
            <div class="modal-body">
                @foreach (var key in columnOrder)
                {
                    var idx = key;
                    <div class="form-group">
                        <label>@key</label>
                        <input value="@(editValues.GetValueOrDefault(idx) ?? string.Empty)" @onchange="(ChangeEventArgs e) => { editValues[idx] = e.Value?.ToString() ?? string.Empty; }" />
                    </div>
                }
            </div>
            <div class="modal-actions">
                <button @onclick="CancelEdit">Abbrechen</button>
                <button @onclick="SaveEdit" class="primary">Speichern</button>
            </div>
        </div>
    </div>
}

@if (deletingRecord != null)
{
    <div class="modal-overlay" @onclick="CancelDelete">
        <div class="modal-dialog modal-sm" @onclick:stopPropagation>
            <div class="modal-title">Löschen bestätigen</div>
            <div class="modal-body">
                <p>Datensatz <strong>ID @deletingRecord.Id</strong> aus <strong>@selectedCollection</strong> löschen?</p>
                <p style="font-size:12px;color:var(--border-color);">Diese Aktion kann nicht rückgängig gemacht werden.</p>
            </div>
            <div class="modal-actions">
                <button @onclick="CancelDelete">Abbrechen</button>
                <button @onclick="DeleteRecord" class="btn-danger">Löschen</button>
            </div>
        </div>
    </div>
}

@code {
    private List<DbCollectionInfo> collections = new();
    private string selectedCollection = "users";
    private List<DbRecord> records = new();
    private List<string> columnOrder = new();
    private string statusMessage = string.Empty;

    private DbRecord? editingRecord;
    private Dictionary<string, string?> editValues = new();

    private DbRecord? deletingRecord;

    protected override void OnInitialized()
    {
        var user = AuthService.CurrentUser;
        if (user?.Role != UserRole.Administrator)
        {
            Navigation.NavigateTo("/");
            return;
        }

        collections = DbAdminSvc.GetCollections();
        if (collections.Count > 0)
            selectedCollection = collections[0].Name;
        LoadRecords();
    }

    private void LoadRecords()
    {
        records = DbAdminSvc.GetAll(selectedCollection);
        columnOrder = records.Count > 0
            ? records[0].Fields.Keys.ToList()
            : new List<string>();
        statusMessage = string.Empty;
    }

    private void StartEdit(DbRecord record)
    {
        editingRecord = record;
        editValues = new Dictionary<string, string?>(record.Fields);
    }

    private void CancelEdit()
    {
        editingRecord = null;
        editValues.Clear();
    }

    private void SaveEdit()
    {
        if (editingRecord == null) return;
        var ok = DbAdminSvc.Update(selectedCollection, editingRecord.Id, editValues);
        statusMessage = ok ? "Gespeichert." : "Fehler beim Speichern.";
        editingRecord = null;
        editValues.Clear();
        LoadRecords();
    }

    private void ConfirmDelete(DbRecord record)
    {
        deletingRecord = record;
    }

    private void CancelDelete()
    {
        deletingRecord = null;
    }

    private void DeleteRecord()
    {
        if (deletingRecord == null) return;
        var ok = DbAdminSvc.Delete(selectedCollection, deletingRecord.Id);
        statusMessage = ok ? "Gelöscht." : "Fehler beim Löschen.";
        deletingRecord = null;
        LoadRecords();
    }

    private static string? Truncate(string? val, int max)
    {
        if (val == null) return null;
        return val.Length > max ? val[..max] + "..." : val;
    }
}
