@page "/admin/revenue-trackings"
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@using TaxBaik.WasmClient.Components.Admin.Shared
@inject IRevenueTrackingBrowserClient RevenueClient
@inject IClientBrowserClient ClientClient
@inject ISnackbar Snackbar
@attribute [Authorize]

<PageTitle>수익 추적 관리</PageTitle>

<AdminPageHeader Title="수익 추적 관리" Eyebrow="CRM & 세무관리" Subtitle="청구 기록과 수익 흐름을 확인합니다." />

<AdminDataPanel Loading="@(revenues is null)" SkeletonContent="@RevenueSkeleton">
    @if (revenues is null)
    {
    }
    else if (revenues.Count == 0)
    {
        <MudAlert Severity="Severity.Info" Class="mt-4">청구 기록이 없습니다.</MudAlert>
    }
    else
    {
        <MudDataGrid T="RevenueTracking" Items="@revenues" Dense="true" Hover="true" Striped="true" Class="admin-grid mt-4">
            <Columns>
                <PropertyColumn Property="x => x.Id" Title="ID" Sortable="true" Class="admin-table-id-column" />
                <TemplateColumn Title="고객" Sortable="true">
                    <CellTemplate>
                        @clientMap.GetValueOrDefault(context.Item.ClientId)
                    </CellTemplate>
                </TemplateColumn>
                <PropertyColumn Property="x => x.InvoiceNumber" Title="청구번호" Sortable="true" />
                <PropertyColumn Property="x => x.InvoiceDate" Title="청구일" Sortable="true" Format="yyyy-MM-dd" />
                <PropertyColumn Property="x => x.Amount" Title="청구액" Sortable="true" Format="C" />
            </Columns>
        </MudDataGrid>
    }
</AdminDataPanel>

@code {
    [CascadingParameter]
    private Task<AuthenticationState>? AuthStateTask { get; set; }

    private List<RevenueTracking>? revenues;
    private List<Client> clients = [];
    private Dictionary<int, string> clientMap = new();

    private RenderFragment RevenueSkeleton => builder =>
    {
        builder.OpenComponent<AdminSkeletonRows>(0);
        builder.AddAttribute(1, "Rows", 5);
        builder.AddAttribute(2, "Columns", 5);
        builder.CloseComponent();
    };

    protected override async Task OnInitializedAsync()
    {
        if (AuthStateTask != null)
        {
            var authState = await AuthStateTask;
            if (authState.User.Identity?.IsAuthenticated == true)
            {
                await LoadData();
            }
            else
            {
                revenues = [];
            }
        }
        else
        {
            revenues = [];
        }
    }

    private async Task LoadData()
    {
        try
        {
            revenues = await RevenueClient.GetAllAsync();
            var (clientItems, _) = await ClientClient.GetPagedAsync(pageSize: 1000);
            clients = clientItems.ToList();
            clientMap = clients.ToDictionary(c => c.Id, GetClientDisplayName);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"데이터 로드 실패: {ex.Message}", Severity.Error);
        }
    }

    private static string GetClientDisplayName(Client client)
        => !string.IsNullOrWhiteSpace(client.CompanyName) ? $"{client.Name} ({client.CompanyName})" : client.Name;
}
