@page "/admin/announcements"
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@attribute [Authorize]
@using TaxBaik.Domain.Entities
@inject IAnnouncementBrowserClient AnnouncementClient
@inject NavigationManager Navigation
@inject IDialogService DialogService
@inject ISnackbar Snackbar

<PageTitle>공지사항 관리</PageTitle>

<AdminPageHeader Title="공지사항 관리" Eyebrow="Homepage" Subtitle="홈페이지 상단에 노출되는 공지사항을 등록하고 관리합니다.">
    <MudButton Variant="Variant.Filled" Color="Color.Primary"
               StartIcon="@Icons.Material.Filled.Add"
               Href="./announcements/create">
        공지 등록
    </MudButton>
</AdminPageHeader>

<AdminSearchBar>
    <SearchContent>
        <MudTextField @bind-Value="searchQuery" Placeholder="공지사항 제목 검색..." Adornment="Adornment.Start" 
                      AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="flex-grow-1" Immediate="true" Clearable="true" />
    </SearchContent>
</AdminSearchBar>

<AdminDataPanel Loading="@(announcements is null)" SkeletonContent="@AnnouncementSkeleton">
    @if (announcements is null)
    {
    }
    else if (!FilteredAnnouncements.Any())
    {
        <div class="pa-6 text-center">
            <MudIcon Icon="@Icons.Material.Filled.Campaign" Class="admin-empty-state-icon" />
            <MudText Class="mt-2 text-muted">검색 조건에 맞는 공지사항이 없습니다.</MudText>
        </div>
    }
    else
    {
        <MudSimpleTable Striped="true" Dense="true" Class="admin-table">
            <thead>
                <tr>
                    <th>제목</th>
                    <th>유형</th>
                    <th>상태</th>
                    <th>게시 기간</th>
                    <th>순서</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in FilteredAnnouncements)
                {
                    <tr>
                        <td>@item.Title</td>
                        <td>
                            <MudChip T="string" Size="Size.Small" Color="@GetTypeColor(item.DisplayType)">
                                @GetTypeLabel(item.DisplayType)
                            </MudChip>
                        </td>
                        <td>
                            @if (IsCurrentlyActive(item))
                            {
                                <MudChip T="string" Size="Size.Small" Color="Color.Success">노출 중</MudChip>
                            }
                            else if (!item.IsActive)
                            {
                                <MudChip T="string" Size="Size.Small" Color="Color.Default">비활성</MudChip>
                            }
                            else
                            {
                                <MudChip T="string" Size="Size.Small" Color="Color.Warning">기간 외</MudChip>
                            }
                        </td>
                        <td class="small">
                            @FormatPeriod(item)
                        </td>
                        <td>@item.SortOrder</td>
                        <td>
                            <MudButtonGroup Size="Size.Small" Variant="Variant.Outlined">
                                <MudButton @onclick="@(() => Navigation.NavigateTo($"./announcements/{item.Id}/edit"))">
                                    수정
                                </MudButton>
                                <MudButton Color="Color.Error" @onclick="@(() => DeleteAsync(item))">
                                    삭제
                                </MudButton>
                            </MudButtonGroup>
                        </td>
                    </tr>
                }
            </tbody>
        </MudSimpleTable>
        <MudText Typo="Typo.caption" Class="pa-2 text-muted">
            검색 결과 @(FilteredAnnouncements.Count())개 · 총 @(announcements.Count)개
        </MudText>
    }
</AdminDataPanel>

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

    private List<Announcement>? announcements;
    private string searchQuery = "";

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

    private IEnumerable<Announcement> FilteredAnnouncements => announcements?
        .Where(a => string.IsNullOrEmpty(searchQuery) || 
                    a.Title.Contains(searchQuery, StringComparison.OrdinalIgnoreCase))
        .OrderBy(a => a.SortOrder) ?? Enumerable.Empty<Announcement>();

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

    private async Task LoadAsync()
    {
        try
        {
            announcements = (await AnnouncementClient.GetAllAsync()).ToList();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"오류: {ex.Message}", Severity.Error);
            announcements = [];
        }
    }

    private async Task DeleteAsync(Announcement item)
    {
        var confirmed = await DialogService.ShowMessageBox(
            "공지 삭제",
            $"'{item.Title}' 공지를 삭제하시겠습니까?",
            yesText: "삭제", cancelText: "취소");

        if (confirmed != true) return;

        try
        {
            var success = await AnnouncementClient.DeleteAsync(item.Id);
            if (success)
            {
                Snackbar.Add("공지사항이 삭제되었습니다.", Severity.Success);
                await LoadAsync();
            }
            else
            {
                Snackbar.Add("삭제 실패", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"오류: {ex.Message}", Severity.Error);
        }
    }

    private static bool IsCurrentlyActive(Announcement a)
    {
        if (!a.IsActive) return false;
        var now = DateTime.UtcNow;
        if (a.StartsAt.HasValue && a.StartsAt > now) return false;
        if (a.EndsAt.HasValue   && a.EndsAt   < now) return false;
        return true;
    }

    private static string FormatPeriod(Announcement a)
    {
        var start = a.StartsAt?.ToLocalTime().ToString("MM/dd") ?? "즉시";
        var end   = a.EndsAt?.ToLocalTime().ToString("MM/dd")   ?? "무기한";
        return $"{start} ~ {end}";
    }

    private static Color GetTypeColor(string type) => type switch
    {
        "urgent" => Color.Error,
        "banner" => Color.Warning,
        _        => Color.Info
    };

    private static string GetTypeLabel(string type) => type switch
    {
        "urgent" => "긴급",
        "banner" => "배너",
        _        => "일반"
    };
}
