@page "/dashboard"
@page "/admin/dashboard"
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@attribute [Authorize]
@inject TaxBaik.Web.Client.Components.Admin.Services.IAdminSessionBootstrap SessionBootstrap
@inject TaxBaik.Web.Client.Components.Admin.Services.IAdminDashboardClient DashboardClient
@inject NavigationManager Navigation

<PageTitle>대시보드</PageTitle>

<AdminPageHeader Title="대시보드" Eyebrow="Home" Subtitle="로그인 후 가장 먼저 보는 운영 요약과 최근 상태를 한 화면에 모았습니다.">
    <ChildContent>
        <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1" Class="admin-header-actions">
            <MudButton Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Refresh" OnClick="@ReloadAsync">
                새로고침
            </MudButton>
            <MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" Href="./inquiries/create">
                새 문의
            </MudButton>
        </MudStack>
    </ChildContent>
</AdminPageHeader>

<MudPaper Class="admin-surface admin-dashboard-status mb-4" Elevation="0" Outlined="true">
    <MudStack Row="true" Wrap="Wrap.Wrap" Spacing="2" AlignItems="AlignItems.Stretch">
        <MudPaper Class="admin-status-chip" Elevation="0" Outlined="true">
            <MudText Typo="Typo.overline">현재 화면</MudText>
            <MudText Typo="Typo.body2">대시보드</MudText>
        </MudPaper>
        <MudPaper Class="admin-status-chip" Elevation="0" Outlined="true">
            <MudText Typo="Typo.overline">핵심 동작</MudText>
            <MudText Typo="Typo.body2">문의 확인, 신규 등록, 콘텐츠 이동</MudText>
        </MudPaper>
        <MudPaper Class="admin-status-chip" Elevation="0" Outlined="true">
            <MudText Typo="Typo.overline">선택 기준</MudText>
            <MudText Typo="Typo.body2">활성 메뉴는 현재 경로와 일치</MudText>
        </MudPaper>
    </MudStack>
</MudPaper>

<MudGrid Spacing="3" Class="mt-4">
    <MudItem xs="12" md="3">
        <AdminMetricCard Label="이번 달 문의" Value="@GetMetricValue(summary?.ThisMonthInquiries)" Caption="월간 유입 추이" Accent="accent-blue" Icon="@Icons.Material.Filled.Campaign" ValueColor="var(--primary-color)" IconColor="var(--primary-light)" OnClick="@(() => Navigation.NavigateTo("./inquiries"))" />
    </MudItem>
    <MudItem xs="12" md="3">
        <AdminMetricCard Label="신규 문의" Value="@GetMetricValue(summary?.NewInquiries)" Caption="즉시 대응 필요" Accent="accent-green" Icon="@Icons.Material.Filled.MarkUnreadChatAlt" ValueColor="var(--success-dark)" IconColor="var(--success-light)" OnClick="@(() => Navigation.NavigateTo("./inquiries?status=new"))" />
    </MudItem>
    <MudItem xs="12" md="3">
        <AdminMetricCard Label="전체 포스트" Value="@GetMetricValue(summary?.TotalPosts)" Caption="콘텐츠 자산" Accent="accent-slate" Icon="@Icons.Material.Filled.Article" ValueColor="var(--text-primary)" IconColor="var(--bg-tertiary)" OnClick="@(() => Navigation.NavigateTo("./blog"))" />
    </MudItem>
    <MudItem xs="12" md="3">
        <AdminMetricCard Label="발행 포스트" Value="@GetMetricValue(summary?.PublishedPosts)" Caption="공개 노출 중" Accent="accent-warm" Icon="@Icons.Material.Filled.Public" ValueColor="var(--tertiary-dark)" IconColor="var(--tertiary-light)" OnClick="@(() => Navigation.NavigateTo("./blog"))" />
    </MudItem>

    <MudItem xs="12" md="7">
        <AdminDataPanel Loading="@isLoading" SkeletonContent="@SummarySkeleton">
            <MudStack Spacing="2">
                <MudStack Row="true" AlignItems="AlignItems.Center" Justify="Justify.SpaceBetween">
                    <div>
                        <MudText Typo="Typo.h6" Class="font-weight-bold">최근 문의</MudText>
                        <MudText Typo="Typo.body2" Class="text-muted">실제 운영자가 가장 자주 보는 처리 대상입니다.</MudText>
                    </div>
                    <MudButton Variant="Variant.Text" Href="./inquiries">전체 보기</MudButton>
                </MudStack>

                @if (summary?.RecentInquiries is null || summary.RecentInquiries.Count == 0)
                {
                    <AdminEmptyState Icon="@Icons.Material.Filled.Inbox" Message="최근 문의가 없습니다." />
                }
                else
                {
                    <MudTable Items="summary.RecentInquiries" Dense="true" Hover="true" Bordered="false" Elevation="0" Class="admin-table">
                        <HeaderContent>
                            <MudTh>고객</MudTh>
                            <MudTh>제목</MudTh>
                            <MudTh>상태</MudTh>
                            <MudTh>등록일</MudTh>
                        </HeaderContent>
                        <RowTemplate>
                            <MudTd DataLabel="고객">@context.Name</MudTd>
                            <MudTd DataLabel="요약">@GetMessageSnippet(context.Message)</MudTd>
                            <MudTd DataLabel="상태">@context.Status</MudTd>
                            <MudTd DataLabel="등록일">@context.CreatedAt.ToString("yyyy-MM-dd")</MudTd>
                        </RowTemplate>
                    </MudTable>
                }
            </MudStack>
        </AdminDataPanel>
    </MudItem>

    <MudItem xs="12" md="5">
        <MudCard Class="admin-surface" Elevation="0" Outlined="true">
            <MudCardContent>
                <MudText Typo="Typo.h6" Class="font-weight-bold">빠른 작업</MudText>
                <MudText Typo="Typo.body2" Class="text-muted mb-3">운영자가 가장 많이 쓰는 이동 경로를 바로 배치했습니다.</MudText>
                <MudStack Spacing="2">
                    <MudButton Variant="Variant.Outlined" FullWidth="true" Href="./clients" StartIcon="@Icons.Material.Filled.Groups">고객 관리</MudButton>
                    <MudButton Variant="Variant.Outlined" FullWidth="true" Href="./tax-profiles" StartIcon="@Icons.Material.Filled.Badge">세무 프로필</MudButton>
                    <MudButton Variant="Variant.Outlined" FullWidth="true" Href="./tax-filing-schedules" StartIcon="@Icons.Material.Filled.EventNote">신고 일정</MudButton>
                    <MudButton Variant="Variant.Outlined" FullWidth="true" Href="./settings" StartIcon="@Icons.Material.Filled.Settings">설정</MudButton>
                </MudStack>

                <MudDivider Class="my-4" />

                <MudText Typo="Typo.subtitle2" Class="font-weight-bold mb-2">운영 기준</MudText>
                <MudStack Spacing="1">
                    <MudPaper Class="admin-status-chip" Elevation="0" Outlined="true">
                        <MudText Typo="Typo.overline">기준 1</MudText>
                        <MudText Typo="Typo.body2">활성 메뉴만 역할별로 표시</MudText>
                    </MudPaper>
                    <MudPaper Class="admin-status-chip" Elevation="0" Outlined="true">
                        <MudText Typo="Typo.overline">기준 2</MudText>
                        <MudText Typo="Typo.body2">로딩 시 스켈레톤 우선 노출</MudText>
                    </MudPaper>
                    <MudPaper Class="admin-status-chip" Elevation="0" Outlined="true">
                        <MudText Typo="Typo.overline">기준 3</MudText>
                        <MudText Typo="Typo.body2">모바일에서는 우선 순위 높은 메뉴만 유지</MudText>
                    </MudPaper>
                    <MudPaper Class="admin-status-chip" Elevation="0" Outlined="true">
                        <MudText Typo="Typo.overline">기준 4</MudText>
                        <MudText Typo="Typo.body2">상단 상태로 현재 위치를 즉시 확인</MudText>
                    </MudPaper>
                </MudStack>
            </MudCardContent>
        </MudCard>
    </MudItem>
</MudGrid>

@code {
    private AdminDashboardSummary? summary;
    private bool isLoading = true;

    protected override async Task OnInitializedAsync()
    {
        await SessionBootstrap.EnsureInitializedAsync();
        await ReloadAsync();
    }

    private async Task ReloadAsync()
    {
        isLoading = true;
        try
        {
            summary = await DashboardClient.GetSummaryAsync();
        }
        catch
        {
            summary = null;
        }
        finally
        {
            isLoading = false;
        }
    }

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

    private static string GetMetricValue(int? value) => value?.ToString() ?? "0";

    private static string GetMessageSnippet(string message)
        => string.IsNullOrWhiteSpace(message)
            ? "내용 없음"
            : message.Length <= 48 ? message : message[..48] + "...";
}
