@page "/collection"
@attribute [Authorize]
@using QuantEngine.Web.Client.Services
@inject ApiClient ApiClient
@inject ILogger<Collection> Logger

<PageTitle>QuantEngine - Collection</PageTitle>

<MudText Typo="Typo.h4" Class="mb-2">Data Collection</MudText>
<MudText Typo="Typo.body2" Class="mb-4">KIS API data collection dashboard. API-first로만 동작합니다.</MudText>

<MudStack Row="true" Spacing="2" Class="mb-4">
    <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@StartCollectionAsync" Disabled="@IsProcessing">
        @(IsProcessing ? "Running..." : "Start Collection")
    </MudButton>
    <MudButton Variant="Variant.Outlined" OnClick="@RefreshAsync" Disabled="@IsProcessing">Refresh</MudButton>
</MudStack>

@if (IsLoading)
{
    <MudProgressLinear Indeterminate="true" Color="Color.Primary" Class="mb-4" />
}
else if (DashboardState != null)
{
    <MudGrid Spacing="2" Class="mb-4">
        <MudItem xs="12" sm="4">
            <MudPaper Class="pa-4" Elevation="2">
                <MudText Typo="Typo.caption">Last Run</MudText>
                <MudText Typo="Typo.h6">@(DashboardState.LastRunStatus ?? "N/A")</MudText>
                <MudText Typo="Typo.body2">@(DashboardState.LastFinishedAt ?? "Not finished")</MudText>
            </MudPaper>
        </MudItem>
        <MudItem xs="12" sm="4">
            <MudPaper Class="pa-4" Elevation="2">
                <MudText Typo="Typo.caption">Total Snapshots</MudText>
                <MudText Typo="Typo.h6">@DashboardState.TotalSnapshots</MudText>
            </MudPaper>
        </MudItem>
        <MudItem xs="12" sm="4">
            <MudPaper Class="pa-4" Elevation="2">
                <MudText Typo="Typo.caption">Total Errors</MudText>
                <MudText Typo="Typo.h6">@DashboardState.TotalErrors</MudText>
            </MudPaper>
        </MudItem>
    </MudGrid>

    @if (DashboardState.RecentErrors.Count > 0)
    {
        <MudPaper Class="pa-4 mb-4" Elevation="2">
            <MudText Typo="Typo.h6" Class="mb-3">Recent Errors</MudText>
            <MudTable Items="@DashboardState.RecentErrors" Dense="true" Hover="true">
                <HeaderContent>
                    <MudTh>Source</MudTh>
                    <MudTh>Kind</MudTh>
                    <MudTh>Ticker</MudTh>
                    <MudTh>Message</MudTh>
                </HeaderContent>
                <RowTemplate>
                    <MudTd DataLabel="Source">@context.SourceName</MudTd>
                    <MudTd DataLabel="Kind">@context.ErrorKind</MudTd>
                    <MudTd DataLabel="Ticker">@context.Ticker</MudTd>
                    <MudTd DataLabel="Message">@context.ErrorMessage</MudTd>
                </RowTemplate>
            </MudTable>
        </MudPaper>
    }

    @if (RecentRuns != null && RecentRuns.Count > 0)
    {
        <MudPaper Class="pa-4" Elevation="2">
            <MudText Typo="Typo.h6" Class="mb-3">Recent Runs</MudText>
            <MudTable Items="@RecentRuns" Dense="true" Hover="true">
                <HeaderContent>
                    <MudTh>Run ID</MudTh>
                    <MudTh>Status</MudTh>
                    <MudTh>Started</MudTh>
                    <MudTh>Finished</MudTh>
                    <MudTh>Snapshots</MudTh>
                    <MudTh>Errors</MudTh>
                </HeaderContent>
                <RowTemplate>
                    <MudTd DataLabel="Run ID" Style="font-family: monospace; font-size: 12px;">@context.RunId</MudTd>
                    <MudTd DataLabel="Status">@context.Status</MudTd>
                    <MudTd DataLabel="Started">@context.StartedAt</MudTd>
                    <MudTd DataLabel="Finished">@context.FinishedAt</MudTd>
                    <MudTd DataLabel="Snapshots">@context.TotalSnapshots</MudTd>
                    <MudTd DataLabel="Errors">@context.TotalErrors</MudTd>
                </RowTemplate>
            </MudTable>
        </MudPaper>
    }
}

@code {
    private CollectionDashboardStateDto? DashboardState;
    private List<CollectionRunDto>? RecentRuns;
    private bool IsLoading = true;
    private bool IsProcessing = false;

    protected override async Task OnInitializedAsync()
    {
        await LoadDashboardStateAsync();
    }

    private async Task LoadDashboardStateAsync()
    {
        IsLoading = true;
        try
        {
            // Parallelize API calls to avoid sequential RTT bottlenecks
            var stateTask = ApiClient.GetCollectionStateAsync();
            var runsTask = ApiClient.GetCollectionRunsAsync(10);
            
            await Task.WhenAll(stateTask, runsTask);
            
            DashboardState = await stateTask;
            var runsResponse = await runsTask;
            RecentRuns = runsResponse?.Runs ?? new();
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "Error loading dashboard");
        }
        finally
        {
            IsLoading = false;
        }
    }

    private async Task StartCollectionAsync()
    {
        IsProcessing = true;
        try
        {
            var result = await ApiClient.StartCollectionRunAsync();
            if (result != null)
            {
                await LoadDashboardStateAsync();
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "Error starting collection");
        }
        finally
        {
            IsProcessing = false;
        }
    }

    private async Task RefreshAsync()
    {
        await LoadDashboardStateAsync();
    }
}
