@model AdminFeatureRequestIndexViewModel
@using Microsoft.AspNetCore.Html
@using System.Text.Encodings.Web
@{
    ViewData["Title"] = "Feature Requests";
    ViewData["ShellClass"] = "plotline-shell-wide feature-request-admin-page";
}

<div class="page-heading compact">
    <div>
        <p class="eyebrow">Admin</p>
        <h1>Feature Requests</h1>
    </div>
    <div class="button-row">
        <a class="btn btn-outline-secondary" asp-action="Index">Admin dashboard</a>
    </div>
</div>

<nav class="mb-3" aria-label="Breadcrumb">
    <a asp-action="Index">Admin</a>
    <span class="muted"> / Feature Requests</span>
</nav>

@if (TempData["AdminMessage"] is string adminMessage)
{
    <div class="alert alert-info">@adminMessage</div>
}

<section class="edit-panel">
    <form method="get" class="row g-3 align-items-end">
        <div class="col-md-2">
            <label class="form-label" for="status">Status</label>
            <select class="form-select" id="status" name="status">
                <option value="">All statuses</option>
                @foreach (var status in Model.StatusOptions)
                {
                    <option value="@status" selected="@(string.Equals(Model.Status, status, StringComparison.OrdinalIgnoreCase))">@status</option>
                }
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label" for="appArea">App Area</label>
            <select class="form-select" id="appArea" name="appArea">
                <option value="">All areas</option>
                @foreach (var appArea in Model.AppAreas)
                {
                    <option value="@appArea" selected="@(string.Equals(Model.AppArea, appArea, StringComparison.OrdinalIgnoreCase))">@appArea</option>
                }
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label" for="importance">Importance</label>
            <select class="form-select" id="importance" name="importance">
                <option value="">All importance</option>
                @foreach (var importance in Model.ImportanceOptions)
                {
                    <option value="@importance" selected="@(string.Equals(Model.Importance, importance, StringComparison.OrdinalIgnoreCase))">@importance</option>
                }
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label" for="sort">Sort</label>
            <select class="form-select" id="sort" name="sort">
                @foreach (var sort in Model.SortOptions)
                {
                    <option value="@sort.Value" selected="@(string.Equals(Model.Sort, sort.Value, StringComparison.OrdinalIgnoreCase))">@sort.Label</option>
                }
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label" for="search">Search</label>
            <input class="form-control" id="search" name="search" value="@Model.Search" placeholder="Title, description, user or email" />
        </div>
        <div class="col-md-2 d-flex gap-2">
            <button class="btn btn-outline-primary" type="submit">Apply</button>
            <a class="btn btn-outline-secondary" asp-action="FeatureRequests">Reset</a>
        </div>
    </form>
</section>

@if (!Model.Requests.Any())
{
    <section class="empty-panel">
        <h2>No feature requests found</h2>
        <p class="muted mb-0">New suggestions will appear here once users submit them.</p>
    </section>
}
else
{
    <section class="edit-panel">
        <div class="table-responsive">
            <table class="table table-sm align-middle feature-request-admin-table">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>User</th>
                        <th>Status</th>
                        <th>Area</th>
                        <th>Importance</th>
                        <th>Created</th>
                        <th>Latest Activity</th>
                        <th>Conversation</th>
                        <th>Messages</th>
                        <th class="feature-request-admin-table__preview">Latest message</th>
                        <th class="feature-request-admin-table__action"></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var request in Model.Requests)
                    {
                        <tr>
                            <td>@request.Title</td>
                            <td>@(request.UserDisplayName ?? request.UserEmail)</td>
                            <td>@StatusBadge(request.Status)</td>
                            <td>@(request.AppArea ?? "Not set")</td>
                            <td>@(request.Importance ?? "Not set")</td>
                            <td>@FormatDate(request.CreatedUtc)</td>
                            <td>@FormatNullableDate(request.LatestActivityUtc)</td>
                            <td>@ConversationBadge(request.ConversationState)</td>
                            <td>@request.MessageCount.ToString("N0")</td>
                            <td class="feature-request-admin-table__preview">@Preview(request.LatestMessagePreview)</td>
                            <td class="text-end">
                                <a class="btn btn-outline-primary btn-sm" asp-action="FeatureRequestDetails" asp-route-id="@request.FeatureRequestID">Open</a>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </section>
}

@functions {
    private static string FormatDate(DateTime value) => value.ToLocalTime().ToString("yyyy-MM-dd HH:mm");

    private static string FormatNullableDate(DateTime? value) => value.HasValue ? FormatDate(value.Value) : "None yet";

    private static string Preview(string? value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return "No messages yet";
        }

        var cleaned = value.ReplaceLineEndings(" ").Trim();
        return cleaned.Length <= 90 ? cleaned : $"{cleaned[..90]}...";
    }

    private static IHtmlContent StatusBadge(string status)
    {
        var css = status switch
        {
            FeatureRequestStatuses.New => "text-bg-primary",
            FeatureRequestStatuses.NeedsDetail => "text-bg-warning",
            FeatureRequestStatuses.UnderReview => "text-bg-info",
            FeatureRequestStatuses.Candidate => "text-bg-secondary",
            FeatureRequestStatuses.Planned => "text-bg-success",
            FeatureRequestStatuses.InProgress => "text-bg-success",
            FeatureRequestStatuses.Shipped => "text-bg-dark",
            FeatureRequestStatuses.NotPlanned => "text-bg-light",
            _ => "text-bg-secondary"
        };

        return new HtmlString($"<span class=\"badge {css}\">{HtmlEncoder.Default.Encode(status)}</span>");
    }

    private static IHtmlContent ConversationBadge(string state)
    {
        var css = state switch
        {
            FeatureRequestConversationStates.WaitingForAdminReply => "text-bg-danger",
            FeatureRequestConversationStates.WaitingForUserReply => "text-bg-warning",
            _ => "text-bg-secondary"
        };

        return new HtmlString($"<span class=\"badge {css}\">{HtmlEncoder.Default.Encode(state)}</span>");
    }
}
