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

<PageTitle>대시보드</PageTitle>

<section class="admin-page-hero">
    <div>
        <MudText Typo="Typo.caption" Class="admin-eyebrow">Overview</MudText>
        <MudText Typo="Typo.h4" Class="admin-page-title">대시보드</MudText>
        <MudText Typo="Typo.body2" Class="admin-page-subtitle">문의 흐름과 콘텐츠 상태를 한 화면에서 확인합니다.</MudText>
    </div>
    <MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" Href="/taxbaik/admin/blog/create">
        새 포스트 작성
    </MudButton>
</section>

@if (!string.IsNullOrEmpty(errorMessage))
{
    <MudAlert Severity="Severity.Error" Class="mb-4">@errorMessage</MudAlert>
}

<AdminDataPanel Loading="@isLoading" SkeletonContent="@DashboardSkeleton">
    <div class="admin-metric-grid">
        <AdminMetricCard Label="이번달 문의" Value="@summary.ThisMonthInquiries" Caption="월간 상담 유입 (클릭 시 이동)" Accent="accent-blue" Icon="💬" ValueColor="var(--primary-dark)" IconColor="var(--primary-color)" OnClick="@GoInquiries" />
        <AdminMetricCard Label="신규 문의" Value="@summary.NewInquiries" Caption="처리 대기 (클릭 시 이동)" Accent="accent-amber" Icon="⚠️" ValueColor="var(--tertiary-dark)" IconColor="var(--tertiary-color)" OnClick="@GoNewInquiries" />
        <AdminMetricCard Label="전체 포스트" Value="@summary.TotalPosts" Caption="콘텐츠 자산 (클릭 시 이동)" Accent="accent-slate" Icon="📄" ValueColor="#455a64" IconColor="#607d8b" OnClick="@GoBlog" />
        <AdminMetricCard Label="발행된 포스트" Value="@summary.PublishedPosts" Caption="검색 노출 대상 (클릭 시 이동)" Accent="accent-green" Icon="🌐" ValueColor="var(--secondary-dark)" IconColor="var(--secondary-color)" OnClick="@GoBlog" />
    </div>

    @if (upcomingFilings.Count > 0)
    {
        <MudPaper Class="admin-surface mt-4" Elevation="0">
            <div class="admin-section-header">
                <div>
                    <MudText Typo="Typo.h6">이번 달 마감 임박 신고</MudText>
                    <MudText Typo="Typo.body2">30일 이내 신고 예정 건 (고객명 클릭 시 상세 카드로 연결)</MudText>
                </div>
                <MudButton Variant="Variant.Outlined" Color="Color.Primary" Href="/taxbaik/admin/tax-filings">전체 일정 보기</MudButton>
            </div>
            <MudSimpleTable Striped="true" Dense="true" Class="admin-table">
                <thead>
                    <tr>
                        <th>고객</th>
                        <th>신고 유형</th>
                        <th>기한</th>
                        <th>D-day</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var f in upcomingFilings)
                    {
                        var dday = BusinessDayCalculator.GetDday(DateOnly.FromDateTime(f.DueDate));
                        var effectiveDueDate = BusinessDayCalculator.GetEffectiveDueDate(DateOnly.FromDateTime(f.DueDate));
                        <tr>
                            <td>
                                <MudLink Href="@($"/taxbaik/admin/clients/{f.ClientId}")" Underline="Underline.Hover" Color="Color.Primary" Class="font-weight-bold">
                                    @f.ClientName
                                </MudLink>
                            </td>
                            <td>@f.FilingType</td>
                            <td>@effectiveDueDate.ToDateTime(TimeOnly.MinValue).ToString("yyyy-MM-dd")</td>
                            <td>
                                @if (dday < 0)
                                {
                                    <MudChip T="string" Size="Size.Small" Color="Color.Dark">기한 초과 (@(-dday)일)</MudChip>
                                }
                                else if (dday <= 7)
                                {
                                    <MudChip T="string" Size="Size.Small" Color="Color.Error">D-@dday</MudChip>
                                }
                                else
                                {
                                    <span>D-@dday</span>
                                }
                            </td>
                        </tr>
                    }
                </tbody>
            </MudSimpleTable>
        </MudPaper>
    }

    <MudPaper Class="admin-surface mt-4" Elevation="0">
        <div class="admin-section-header">
            <div>
                <MudText Typo="Typo.h6">최근 문의</MudText>
                <MudText Typo="Typo.body2">최근 유입된 상담 요청을 빠르게 확인합니다. (이름 클릭 시 상세 관리 화면으로 연계)</MudText>
            </div>
            <MudButton Variant="Variant.Outlined" Color="Color.Primary" Href="/taxbaik/admin/inquiries">문의 전체 보기</MudButton>
        </div>
        <MudSimpleTable Striped="true" Dense="true" Class="admin-table">
            <thead>
                <tr>
                    <th>이름</th>
                    <th>전화</th>
                    <th>분야</th>
                    <th>상태</th>
                    <th>날짜</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var inquiry in summary.RecentInquiries)
                {
                    <tr>
                        <td>
                            <MudLink Href="@($"/taxbaik/admin/inquiries?id={inquiry.Id}")" Underline="Underline.Hover" Color="Color.Primary" Class="font-weight-bold">
                                @inquiry.Name
                            </MudLink>
                        </td>
                        <td>@inquiry.Phone</td>
                        <td>@inquiry.ServiceType</td>
                        <td>
                            <MudChip T="string" Size="Size.Small" Color="@StatusColor(inquiry.Status)">
                                @GetStatusLabel(inquiry.Status)
                            </MudChip>
                        </td>
                        <td>@inquiry.CreatedAt.ToString("yyyy-MM-dd")</td>
                    </tr>
                }
            </tbody>
        </MudSimpleTable>
    </MudPaper>
</AdminDataPanel>

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

    private AdminDashboardSummary summary = new(0, 0, 0, 0, []);
    private List<Domain.Entities.TaxFiling> upcomingFilings = [];
    private string? errorMessage;
    private bool isLoading = true;

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

    private void GoInquiries()
    {
        Nav.NavigateTo("/taxbaik/admin/inquiries");
    }

    private void GoNewInquiries()
    {
        Nav.NavigateTo("/taxbaik/admin/inquiries?status=new");
    }

    private void GoBlog()
    {
        Nav.NavigateTo("/taxbaik/admin/blog");
    }

    protected override async Task OnInitializedAsync()
    {
        if (AuthStateTask != null)
        {
            var authState = await AuthStateTask;
            if (authState.User.Identity?.IsAuthenticated == true)
            {
                try
                {
                    var summaryTask = DashboardClient.GetSummaryAsync();
                    var filingsTask = DashboardClient.GetUpcomingFilingsAsync(30);

                    await Task.WhenAll(summaryTask, filingsTask);
                    summary = await summaryTask;
                    upcomingFilings = (await filingsTask).ToList();
                }
                catch (Exception ex)
                {
                    errorMessage = "대시보드 데이터를 불러올 수 없습니다.";
                    Console.Error.WriteLine($"Dashboard error: {ex.Message}");
                }
                finally
                {
                    isLoading = false;
                }
            }
            else
            {
                // AuthorizeRouteView already gates this page, so this branch is
                // only a transient auth-state resolution timing gap - but without
                // resetting isLoading here, AdminDataPanel would spin forever.
                isLoading = false;
            }
        }
        else
        {
            isLoading = false;
        }
    }

    private static string GetStatusLabel(string status) => InquiryStatusMapper.Labels.GetValueOrDefault(status, status);

    private static Color StatusColor(string status) => status switch
    {
        "new" => Color.Warning,
        "consulting" => Color.Info,
        "contracted" => Color.Success,
        "rejected" => Color.Error,
        "closed" => Color.Dark,
        _ => Color.Default
    };
}
