@page "/portal"
@using EntKube.Web.Data
@using EntKube.Web.Services
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@attribute [Authorize]
@rendermode InteractiveServer
@inject CustomerAccessService CustomerAccessService
@inject DeploymentService DeploymentService
@inject KubernetesOperationsService K8sOps
@inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager Navigation

<PageTitle>Customer Portal</PageTitle>

@* ═══════════════════════════════════════════════════════════════════
   Customer Portal — a scoped view where a user sees only the customers
   they've been granted access to. From here they can drill into apps,
   deployments, view pod logs, restart deployments, and delete pods.

   Navigation flow: My Customers → Apps → Deployments → Operations
   ═══════════════════════════════════════════════════════════════════ *@

@if (loading)
{
    <div class="text-center py-5">
        <div class="spinner-border text-primary" role="status"></div>
        <p class="text-muted mt-2">Loading portal...</p>
    </div>
}
else if (customers is null || customers.Count == 0)
{
    <div class="text-center py-5">
        <i class="bi bi-shield-lock text-muted" style="font-size: 3rem;"></i>
        <h4 class="mt-3">No access granted</h4>
        <p class="text-muted">You don't have access to any customers yet. Ask a tenant administrator to grant you access.</p>
    </div>
}
else
{
    @* ── Level 0: Breadcrumb navigation ── *@
    <nav aria-label="breadcrumb" class="mb-3">
        <ol class="breadcrumb small">
            <li class="breadcrumb-item">
                @if (selectedDeployment is not null)
                {
                    <a href="javascript:void(0)" class="text-decoration-none" @onclick="BackToApps">
                        <i class="bi bi-grid me-1"></i>Portal
                    </a>
                }
                else if (selectedCustomer is not null)
                {
                    <a href="javascript:void(0)" class="text-decoration-none" @onclick="BackToCustomers">
                        <i class="bi bi-grid me-1"></i>Portal
                    </a>
                }
                else
                {
                    <span class="text-muted"><i class="bi bi-grid me-1"></i>Portal</span>
                }
            </li>

            @if (selectedCustomer is not null)
            {
                <li class="breadcrumb-item">
                    @if (selectedDeployment is not null)
                    {
                        <a href="javascript:void(0)" class="text-decoration-none" @onclick="BackToApps">@selectedCustomer.Name</a>
                    }
                    else
                    {
                        <span class="text-muted">@selectedCustomer.Name</span>
                    }
                </li>
            }

            @if (selectedDeployment is not null)
            {
                <li class="breadcrumb-item active">@selectedDeployment.Name</li>
            }
        </ol>
    </nav>

    @* ════════════════════════════════════════════════════════════════
       Level 1: Customer list
       ════════════════════════════════════════════════════════════════ *@
    @if (selectedCustomer is null)
    {
        <div class="d-flex align-items-center mb-4">
            <i class="bi bi-grid fs-3 me-2 text-primary"></i>
            <h2 class="mb-0">My Customers</h2>
        </div>

        <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-3">
            @foreach (Customer customer in customers)
            {
                <div class="col">
                    <div class="card shadow-sm h-100" role="button" style="cursor: pointer;"
                         @onclick="() => SelectCustomer(customer)">
                        <div class="card-body">
                            <div class="d-flex align-items-center mb-2">
                                <i class="bi bi-people fs-4 me-2 text-primary"></i>
                                <h5 class="mb-0">@customer.Name</h5>
                            </div>
                            <div class="text-muted small">
                                <i class="bi bi-app-indicator me-1"></i>
                                @customer.Apps.Count app@(customer.Apps.Count != 1 ? "s" : "")
                            </div>
                        </div>
                    </div>
                </div>
            }
        </div>
    }

    @* ════════════════════════════════════════════════════════════════
       Level 2: Apps and deployments for a selected customer
       ════════════════════════════════════════════════════════════════ *@
    else if (selectedDeployment is null)
    {
        <div class="d-flex align-items-center mb-4">
            <i class="bi bi-people fs-3 me-2 text-primary"></i>
            <div>
                <h2 class="mb-0">@selectedCustomer.Name</h2>
                <small class="text-muted">@selectedCustomer.Apps.Count app@(selectedCustomer.Apps.Count != 1 ? "s" : "")</small>
            </div>
        </div>

        @if (selectedCustomer.Apps.Count == 0)
        {
            <div class="text-center py-4">
                <i class="bi bi-app-indicator text-muted" style="font-size: 2rem;"></i>
                <p class="text-muted mt-2">No apps configured for this customer yet.</p>
            </div>
        }
        else
        {
            @foreach (Data.App app in selectedCustomer.Apps.OrderBy(a => a.Name))
            {
                <div class="card shadow-sm mb-3">
                    <div class="card-header bg-white py-2">
                        <div class="d-flex align-items-center">
                            <i class="bi bi-app-indicator me-2 text-primary"></i>
                            <strong>@app.Name</strong>
                        </div>
                    </div>
                    <div class="card-body">
                        @if (appDeployments.TryGetValue(app.Id, out List<AppDeployment>? deploys) && deploys.Count > 0)
                        {
                            <div class="row row-cols-1 row-cols-lg-2 g-2">
                                @foreach (AppDeployment deploy in deploys)
                                {
                                    <div class="col">
                                        <div class="card border-light" role="button" style="cursor: pointer;"
                                             @onclick="() => SelectDeployment(deploy)">
                                            <div class="card-body py-2">
                                                <div class="d-flex align-items-center justify-content-between mb-1">
                                                    <span class="fw-medium">
                                                        <i class="bi bi-rocket-takeoff me-1 text-primary"></i>@deploy.Name
                                                    </span>
                                                    <div class="d-flex gap-1">
                                                        @SyncBadge(deploy.SyncStatus)
                                                        @HealthBadge(deploy.HealthStatus)
                                                    </div>
                                                </div>
                                                <div class="d-flex flex-wrap gap-2 text-muted small">
                                                    @TypeBadge(deploy.Type)
                                                    <span><i class="bi bi-layers me-1"></i>@deploy.Environment?.Name</span>
                                                    <span><i class="bi bi-hdd-network me-1"></i>@deploy.Cluster?.Name</span>
                                                    <span><i class="bi bi-box me-1"></i>@deploy.Namespace</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                }
                            </div>
                        }
                        else
                        {
                            <p class="text-muted small mb-0">No deployments configured.</p>
                        }
                    </div>
                </div>
            }
        }
    }

    @* ════════════════════════════════════════════════════════════════
       Level 3: Deployment detail with operations
       ════════════════════════════════════════════════════════════════ *@
    else
    {
        <PortalDeploymentDetail
            Deployment="selectedDeployment"
            AccessRole="currentAccessRole"
            K8sOps="K8sOps"
            DeploymentService="DeploymentService"
            OnBack="BackToApps" />
    }
}

@code {
    private bool loading = true;
    private string? currentUserId;
    private CustomerAccessRole currentAccessRole;

    private List<Customer>? customers;
    private Customer? selectedCustomer;
    private AppDeployment? selectedDeployment;

    // Deployments indexed by app ID for the selected customer.
    private Dictionary<Guid, List<AppDeployment>> appDeployments = new();

    protected override async Task OnInitializedAsync()
    {
        // Determine who the logged-in user is.
        AuthenticationState authState = await AuthStateProvider.GetAuthenticationStateAsync();
        currentUserId = authState.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;

        if (string.IsNullOrEmpty(currentUserId))
        {
            loading = false;
            return;
        }

        // Load only the customers this user has access to.
        customers = await CustomerAccessService.GetAccessibleCustomersAsync(currentUserId);
        loading = false;
    }

    private async Task SelectCustomer(Customer customer)
    {
        selectedCustomer = customer;

        // Look up the user's role for this customer.
        CustomerAccess? access = await CustomerAccessService.GetAccessAsync(currentUserId!, customer.Id);
        currentAccessRole = access?.Role ?? CustomerAccessRole.Viewer;

        // Load deployments for all of the customer's apps.
        appDeployments.Clear();

        foreach (Data.App app in customer.Apps)
        {
            List<AppDeployment> deploys = await DeploymentService.GetDeploymentsAsync(app.Id);
            appDeployments[app.Id] = deploys;
        }
    }

    private void SelectDeployment(AppDeployment deploy)
    {
        selectedDeployment = deploy;
    }

    private void BackToCustomers()
    {
        selectedCustomer = null;
        selectedDeployment = null;
    }

    private void BackToApps()
    {
        selectedDeployment = null;
    }

    // ──────── Badge helpers ────────

    private RenderFragment TypeBadge(DeploymentType type) => type switch
    {
        DeploymentType.Manual => @<span class="badge bg-info">Manual</span>,
        DeploymentType.Yaml => @<span class="badge bg-warning text-dark">YAML</span>,
        DeploymentType.HelmChart => @<span class="badge bg-purple text-white" style="background-color: #6f42c1 !important;">Helm</span>,
        _ => @<span class="badge bg-secondary">Unknown</span>
    };

    private RenderFragment SyncBadge(SyncStatus status) => status switch
    {
        SyncStatus.Synced => @<span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Synced</span>,
        SyncStatus.OutOfSync => @<span class="badge bg-warning text-dark"><i class="bi bi-exclamation-circle me-1"></i>OutOfSync</span>,
        SyncStatus.Syncing => @<span class="badge bg-info"><i class="bi bi-arrow-repeat me-1"></i>Syncing</span>,
        SyncStatus.Failed => @<span class="badge bg-danger"><i class="bi bi-x-circle me-1"></i>Failed</span>,
        _ => @<span class="badge bg-secondary">Unknown</span>
    };

    private RenderFragment HealthBadge(HealthStatus status) => status switch
    {
        HealthStatus.Healthy => @<span class="badge bg-success"><i class="bi bi-heart-fill me-1"></i>Healthy</span>,
        HealthStatus.Progressing => @<span class="badge bg-info"><i class="bi bi-hourglass-split me-1"></i>Progressing</span>,
        HealthStatus.Degraded => @<span class="badge bg-warning text-dark"><i class="bi bi-exclamation-triangle me-1"></i>Degraded</span>,
        HealthStatus.Missing => @<span class="badge bg-danger"><i class="bi bi-question-circle me-1"></i>Missing</span>,
        HealthStatus.Suspended => @<span class="badge bg-secondary"><i class="bi bi-pause-circle me-1"></i>Suspended</span>,
        _ => @<span class="badge bg-secondary">Unknown</span>
    };
}
