@using EntKube.Web.Data
@using EntKube.Web.Services
@using Microsoft.EntityFrameworkCore
@inject IncidentService IncidentService
@inject IDbContextFactory<ApplicationDbContext> DbFactory
@inject AuthenticationStateProvider AuthStateProvider

<div class="d-flex justify-content-between align-items-center mb-3">
    <h6 class="mb-0">Maintenance Windows</h6>
    <button class="btn btn-sm btn-primary" @onclick="ShowAdd">
        <span class="bi bi-plus-lg"></span> Schedule Window
    </button>
</div>

@if (activeWindows.Count > 0)
{
    <div class="alert alert-warning d-flex align-items-center gap-2 mb-3 py-2">
        <span class="bi bi-tools fs-5"></span>
        <div>
            <strong>Active maintenance:</strong>
            @foreach (MaintenanceWindow w in activeWindows)
            {
                <span class="me-2">@w.Title (until @w.EndsAt.ToLocalTime().ToString("HH:mm"))</span>
            }
            <div class="small text-muted">Alert notifications are suppressed for covered clusters.</div>
        </div>
    </div>
}

@if (windows.Count == 0)
{
    <EmptyState Icon="bi-calendar-x"
                Title="No maintenance windows"
                Message="No windows scheduled." />
}
else
{
    <div class="table-responsive">
        <table class="table table-sm align-middle">
            <thead class="table-light">
                <tr>
                    <th>Title</th>
                    <th>Cluster</th>
                    <th>Starts</th>
                    <th>Ends</th>
                    <th>Created By</th>
                    <th>Status</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (MaintenanceWindow w in windows)
                {
                    DateTime now = DateTime.UtcNow;
                    bool active = w.StartsAt <= now && w.EndsAt >= now;
                    bool past = w.EndsAt < now;
                    <tr class="@(active ? "table-warning" : past ? "text-muted" : "")">
                        <td class="fw-semibold">@w.Title</td>
                        <td class="small">@(w.Cluster?.Name ?? "All clusters")</td>
                        <td class="small">@w.StartsAt.ToLocalTime().ToString("MMM d HH:mm")</td>
                        <td class="small">@w.EndsAt.ToLocalTime().ToString("MMM d HH:mm")</td>
                        <td class="small text-muted">@w.CreatedBy</td>
                        <td>
                            @if (active)
                            {
                                <span class="badge bg-warning text-dark">Active</span>
                            }
                            else if (past)
                            {
                                <span class="badge bg-secondary">Completed</span>
                            }
                            else
                            {
                                <span class="badge bg-info text-dark">Scheduled</span>
                            }
                        </td>
                        <td>
                            @if (!past)
                            {
                                <button class="btn btn-sm btn-outline-danger" @onclick="() => Delete(w.Id)">
                                    <span class="bi bi-trash"></span>
                                </button>
                            }
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}

@if (showAdd)
{
    <div class="card mt-3 border-primary">
        <div class="card-header d-flex justify-content-between align-items-center py-2">
            <h6 class="mb-0">Schedule Maintenance Window</h6>
            <button class="btn-close btn-sm" @onclick="() => showAdd = false"></button>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label small">Title <span class="text-danger">*</span></label>
                    <input class="form-control form-control-sm" @bind="newTitle" placeholder="e.g. Scheduled database maintenance" />
                </div>
                <div class="col-12">
                    <label class="form-label small">Description</label>
                    <textarea class="form-control form-control-sm" rows="2" @bind="newDescription" placeholder="Optional details"></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label small">Cluster</label>
                    <select class="form-select form-select-sm" @bind="newClusterId">
                        <option value="">All clusters</option>
                        @foreach (KubernetesCluster c in clusters)
                        {
                            <option value="@c.Id">@c.Name</option>
                        }
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label small">Start (local)</label>
                    <input class="form-control form-control-sm" type="datetime-local" @bind="newStartsAt" />
                </div>
                <div class="col-md-3">
                    <label class="form-label small">End (local)</label>
                    <input class="form-control form-control-sm" type="datetime-local" @bind="newEndsAt" />
                </div>
            </div>
            @if (!string.IsNullOrEmpty(formError))
            {
                <div class="alert alert-danger py-1 small mt-2 mb-0">@formError</div>
            }
            <div class="mt-3 d-flex gap-2">
                <button class="btn btn-sm btn-primary" @onclick="Save">Save Window</button>
                <button class="btn btn-sm btn-outline-secondary" @onclick="() => showAdd = false">Cancel</button>
            </div>
        </div>
    </div>
}

@code {
    [Parameter] public required Guid TenantId { get; set; }

    private List<MaintenanceWindow> windows = [];
    private List<MaintenanceWindow> activeWindows = [];
    private List<KubernetesCluster> clusters = [];
    private bool showAdd;
    private string newTitle = "";
    private string newDescription = "";
    private string newClusterId = "";
    private DateTime newStartsAt = DateTime.Now.AddMinutes(5);
    private DateTime newEndsAt = DateTime.Now.AddHours(2);
    private string? formError;
    private string? currentUser;

    protected override async Task OnInitializedAsync()
    {
        AuthenticationState auth = await AuthStateProvider.GetAuthenticationStateAsync();
        currentUser = auth.User.Identity?.Name ?? "Unknown";
        await Load();
    }

    private async Task Load()
    {
        windows = await IncidentService.GetMaintenanceWindowsAsync(TenantId);
        DateTime now = DateTime.UtcNow;
        activeWindows = windows.Where(w => w.StartsAt <= now && w.EndsAt >= now).ToList();

        using ApplicationDbContext db = DbFactory.CreateDbContext();
        clusters = await db.KubernetesClusters
            .Where(c => c.TenantId == TenantId)
            .OrderBy(c => c.Name)
            .ToListAsync();
    }

    private void ShowAdd()
    {
        showAdd = true;
        newTitle = "";
        newDescription = "";
        newClusterId = "";
        newStartsAt = DateTime.Now.AddMinutes(5);
        newEndsAt = DateTime.Now.AddHours(2);
        formError = null;
    }

    private async Task Save()
    {
        formError = null;
        if (string.IsNullOrWhiteSpace(newTitle)) { formError = "Title is required."; return; }
        if (newEndsAt <= newStartsAt) { formError = "End time must be after start time."; return; }

        Guid? clusterId = Guid.TryParse(newClusterId, out Guid cid) ? cid : null;

        await IncidentService.CreateMaintenanceWindowAsync(
            TenantId,
            newTitle.Trim(),
            string.IsNullOrWhiteSpace(newDescription) ? null : newDescription.Trim(),
            clusterId,
            newStartsAt.ToUniversalTime(),
            newEndsAt.ToUniversalTime(),
            currentUser!);

        showAdd = false;
        await Load();
    }

    private async Task Delete(Guid id)
    {
        await IncidentService.DeleteMaintenanceWindowAsync(id);
        await Load();
    }
}
