@page "/admin/consulting-activities"
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@using TaxBaik.WasmClient.Components.Admin.Shared
@inject IConsultingActivityBrowserClient ActivityClient
@inject IClientBrowserClient ClientClient
@inject ISnackbar Snackbar
@attribute [Authorize]

<PageTitle>상담 활동 관리</PageTitle>

<AdminPageHeader Title="상담 활동 관리" Eyebrow="CRM & 세무관리" Subtitle="초기 렌더 진단용 최소 화면입니다." />

<AdminDataPanel Loading="@(activities is null)" SkeletonContent="@ActivitySkeleton">
    @if (activities is null)
    {
    }
    else if (activities.Count == 0)
    {
        <MudAlert Severity="Severity.Info" Class="mt-4">상담 활동이 없습니다.</MudAlert>
    }
    else
    {
        <MudDataGrid T="ConsultingActivity" Items="@activities" 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.ActivityType" Title="활동 유형" Sortable="true" />
                <PropertyColumn Property="x => x.ActivityDate" Title="활동일시" Sortable="true" Format="yyyy-MM-dd HH:mm" />
                <PropertyColumn Property="x => x.Description" Title="설명" Sortable="false" CellStyleFunc="@(_ => "max-width: 420px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;")" />
            </Columns>
        </MudDataGrid>
    }
</AdminDataPanel>

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

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

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

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

    private async Task LoadData()
    {
        try
        {
            activities = await ActivityClient.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;
}
