@page "/collection"
@using QuantEngine.Web.Services
@inject ApiClient ApiClient
@inject ILogger<Collection> Logger

<PageTitle>QuantEngine - Collection</PageTitle>

<h1 style="margin: 0 0 8px 0; font-size: 28px; font-weight: 600;">Data Collection</h1>
<p style="margin: 0 0 16px 0; color: var(--neutral-foreground-2); font-size: 14px;">
    KIS API data collection dashboard. Monitor runs, snapshots, and error trends.
</p>

<!-- Controls -->
<FluentStack Orientation="Orientation.Horizontal" HorizontalGap="8" Style="margin-bottom: 16px;">
    <FluentButton Appearance="ButtonAppearance.Primary" OnClick="@StartCollectionAsync" Disabled="@IsProcessing">
        @if (IsProcessing) { <span>Running...</span> } else { <span>Start Collection</span> }
    </FluentButton>
    <FluentButton Appearance="ButtonAppearance.Default" OnClick="@RefreshAsync" Disabled="@IsProcessing">
        Refresh
    </FluentButton>
</FluentStack>

<!-- Loading skeleton -->
@if (IsLoading)
{
    <FluentStack Orientation="Orientation.Vertical" VerticalGap="16">
        <FluentSkeleton Width="100%" Height="60px" />
        <FluentSkeleton Width="100%" Height="200px" />
    </FluentStack>
}
else if (DashboardState != null)
{
    <!-- Summary Cards -->
    <FluentStack Orientation="Orientation.Horizontal" HorizontalGap="16" Wrap="true" Style="margin-bottom: 16px;">
        <FluentCard Style="flex: 1; min-width: 150px;">
            <div style="padding: 16px;">
                <p style="margin: 0 0 8px 0; color: var(--neutral-foreground-2); font-size: 12px; font-weight: 500;">Last Run</p>
                <h3 style="margin: 0; font-size: 18px; font-weight: 600;">@(DashboardState.LastRunStatus ?? "N/A")</h3>
                <p style="margin: 8px 0 0 0; color: var(--neutral-foreground-3); font-size: 12px;">@(DashboardState.LastFinishedAt ?? "Not finished")</p>
            </div>
        </FluentCard>
        <FluentCard Style="flex: 1; min-width: 150px;">
            <div style="padding: 16px;">
                <p style="margin: 0 0 8px 0; color: var(--neutral-foreground-2); font-size: 12px; font-weight: 500;">Total Snapshots</p>
                <h3 style="margin: 0; font-size: 18px; font-weight: 600;">@DashboardState.TotalSnapshots</h3>
            </div>
        </FluentCard>
        <FluentCard Style="flex: 1; min-width: 150px;">
            <div style="padding: 16px;">
                <p style="margin: 0 0 8px 0; color: var(--neutral-foreground-2); font-size: 12px; font-weight: 500;">Total Errors</p>
                <h3 style="margin: 0; font-size: 18px; font-weight: 600;">@DashboardState.TotalErrors</h3>
            </div>
        </FluentCard>
    </FluentStack>

    <!-- Recent Errors -->
    @if (DashboardState.RecentErrors.Count > 0)
    {
        <FluentCard Style="margin-bottom: 16px;">
            <div style="padding: 16px;">
                <h3 style="margin: 0 0 12px 0; font-size: 16px; font-weight: 600;">Recent Errors</h3>
                <table style="width: 100%; border-collapse: collapse;">
                    <thead style="background: var(--neutral-subtle);">
                        <tr>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Source</th>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Kind</th>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Ticker</th>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Message</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var error in DashboardState.RecentErrors)
                        {
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest);">@error.SourceName</td>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest);">@error.ErrorKind</td>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest);">@error.Ticker</td>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest);">@error.ErrorMessage</td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </FluentCard>
    }

    <!-- Recent Runs -->
    @if (RecentRuns != null && RecentRuns.Count > 0)
    {
        <FluentCard>
            <div style="padding: 16px;">
                <h3 style="margin: 0 0 12px 0; font-size: 16px; font-weight: 600;">Recent Runs</h3>
                <table style="width: 100%; border-collapse: collapse;">
                    <thead style="background: var(--neutral-subtle);">
                        <tr>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Run ID</th>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Status</th>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Started</th>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Finished</th>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Snapshots</th>
                            <th style="padding: 8px; text-align: left; border-bottom: 1px solid var(--neutral-divider-rest);">Errors</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var run in RecentRuns)
                        {
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest); font-family: monospace; font-size: 12px;">@run.RunId</td>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest);">@run.Status</td>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest); font-size: 12px;">@run.StartedAt</td>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest); font-size: 12px;">@run.FinishedAt</td>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest);">@run.TotalSnapshots</td>
                                <td style="padding: 8px; border-bottom: 1px solid var(--neutral-stroke-divider-rest);">@run.TotalErrors</td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </FluentCard>
    }
}

@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
        {
            DashboardState = await ApiClient.GetCollectionStateAsync();

            var runsResponse = await ApiClient.GetCollectionRunsAsync(10);
            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();
    }
}
