@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject ISnackbar Snackbar
@inject IHttpClientFactory HttpClientFactory

<MudCard Class="w-100 me-2 position-relative mt-2" Elevation="0" Outlined Style="height: 350px">
    <MudCardHeader>
        <MudText Typo="Typo.h5">Dashboard Mission Names</MudText>
    </MudCardHeader>
    <MudCardContent>
        <div class="d-flex flex-column">
            <div class="d-flex flex-row">
                <MudTextField Label="Mission Name" Variant="Variant.Outlined" @bind-Value="MissionName" ShrinkLabel />
                <MudButton Class="mt-2 mb-1 ms-2" Variant="Variant.Filled" Color="Color.Info" OnClick="Add">Add</MudButton>
            </div>
            <div class="d-flex flex-wrap overflow-x-hidden overflow-y-auto mt-2" style="border: 1px solid silver; height: 115px; border-radius: 5px">
                @foreach(var missionName in MissionNames)
                {
                    <div class="m-1" style="height: fit-content">
                        <MudButton Variant="Variant.Filled" Color="Color.Tertiary" Style="text-transform:none" OnClick="@(() => MissionNames.Remove(missionName))">
                            @missionName
                        </MudButton>
                    </div>
                }
            </div>
            <div class="d-flex flex-row-reverse mt-4">
                <div>
                    <MudButton Class="d-flex flex-grow-1 mt-2 mb-1 ms-2" Variant="Variant.Filled" Color="Color.Info" OnClick="Update">Update</MudButton>
                </div>
            </div>
        </div>
    </MudCardContent>

    <MudOverlay Visible="OverlayIsVisible" DarkBackground="true" Absolute="true">
        <MudProgressCircular Color="Color.Secondary" Indeterminate="true" />
    </MudOverlay>
</MudCard>

@code {
    private List<string> MissionNames = [];
    private bool OverlayIsVisible;

    private string MissionName = "";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (!firstRender) return;

        await LoadMisison();
    }

    private async Task LoadMisison()
    {
        try
        {
            OverlayIsVisible = true;
            StateHasChanged();

            using var client = HttpClientFactory.CreateClient("ScriptManagerAPI");
            var mission = await client.GetFromJsonAsync<MessageResult<string[]>>("api/DashboardConfig");
            if (mission is null || mission.Data is null || !mission.IsSuccess) MissionNames = [];
            else MissionNames = [.. mission.Data];

            OverlayIsVisible = false;
            StateHasChanged();
        }
        catch (AccessTokenNotAvailableException ex)
        {
            ex.Redirect();
        }
    }

    private async Task Update()
    {
        try
        {
            OverlayIsVisible = true;
            StateHasChanged();

            using var Http = HttpClientFactory.CreateClient("ScriptManagerAPI");

            var result = await (await Http.PostAsJsonAsync($"api/DashboardConfig", MissionNames)).Content.ReadFromJsonAsync<MessageResult>();
            if (result is null) { Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Warning); return; }
            else if (!result.IsSuccess) { Snackbar.Add(result.Message ?? "Cập nhật không thành công", Severity.Warning); return; }

            OverlayIsVisible = false;
            Snackbar.Add("Cập nhật thành công", Severity.Success);
            StateHasChanged();
        }
        catch (AccessTokenNotAvailableException ex)
        {
            ex.Redirect();
        }
    }

    private void Add()
    {
        if (string.IsNullOrEmpty(MissionName))
        {
            Snackbar.Add("Vui lòng nhập mission name", Severity.Warning);
            return;
        }
        if (MissionNames.Contains(MissionName))
        {
            Snackbar.Add("Mission name đã tồn tại", Severity.Warning);
            return;
        }
        MissionNames.Add(MissionName);
        StateHasChanged();
    }
}
