@page "/admin/inquiries"
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@attribute [Authorize]
@using TaxBaik.Application.Services
@inject IInquiryBrowserClient InquiryClient
@inject ISnackbar Snackbar

<PageTitle>문의 관리</PageTitle>

<AdminPageHeader Title="문의 관리" Eyebrow="Customer Requests" Subtitle="상담 요청을 상태별로 확인하고 후속 조치를 기록합니다.">
    <ChildContent>
        <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
            <MudButton Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Refresh" OnClick="@LoadData">새로고침</MudButton>
            <MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add"
                       Href="./inquiries/create">새 문의 등록</MudButton>
        </MudStack>
    </ChildContent>
</AdminPageHeader>

<AdminSearchBar>
    <SearchContent>
        <MudGrid>
            <MudItem xs="12" md="5">
                <MudTextField @bind-Value="searchText" Label="검색 (이름·전화·이메일·메모)"
                              Adornment="Adornment.End" AdornmentIcon="@Icons.Material.Filled.Search"
                              Immediate="false" OnKeyUp="@OnSearchKeyUp" />
            </MudItem>
            <MudItem xs="12" md="3">
                <CommonCodeSelect @bind-Value="statusFilter" Group="INQUIRY_STATUS" Label="상태" Placeholder="전체" Clearable="true" />
            </MudItem>
        </MudGrid>
    </SearchContent>
    <Actions>
        <MudButton Variant="Variant.Outlined" OnClick="@SearchAsync">검색</MudButton>
        <MudButton Variant="Variant.Text" OnClick="@ResetAsync">초기화</MudButton>
    </Actions>
</AdminSearchBar>

<AdminDataPanel Loading="@isLoading">
    <MudStack Row="true" AlignItems="AlignItems.Center" Justify="Justify.SpaceBetween" Class="mb-3 px-1">
        <MudText Typo="Typo.subtitle1">@($"검색 결과 {filteredInquiries.Count}건 / 전체 {allInquiries.Count}건")</MudText>
        <MudText Typo="Typo.body2">상태 필터: @(string.IsNullOrWhiteSpace(statusFilter) ? "전체" : statusFilter)</MudText>
    </MudStack>

    <MudTabs Rounded="true" Elevation="0" Class="admin-tabs">
        <MudTabPanel Text="전체">
            <InquiryTable Inquiries="filteredInquiries" Status="" />
        </MudTabPanel>
        <MudTabPanel Text="신규">
            <InquiryTable Inquiries="filteredInquiries" Status="@InquiryStatusMapper.StatusNew" />
        </MudTabPanel>
        <MudTabPanel Text="상담중">
            <InquiryTable Inquiries="filteredInquiries" Status="@InquiryStatusMapper.StatusConsulting" />
        </MudTabPanel>
        <MudTabPanel Text="계약완료">
            <InquiryTable Inquiries="filteredInquiries" Status="@InquiryStatusMapper.StatusContracted" />
        </MudTabPanel>
        <MudTabPanel Text="거절">
            <InquiryTable Inquiries="filteredInquiries" Status="@InquiryStatusMapper.StatusRejected" />
        </MudTabPanel>
        <MudTabPanel Text="종결">
            <InquiryTable Inquiries="filteredInquiries" Status="@InquiryStatusMapper.StatusClosed" />
        </MudTabPanel>
    </MudTabs>
</AdminDataPanel>

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

    private bool isLoading = true;
    private IReadOnlyList<Domain.Entities.Inquiry> allInquiries = [];
    private IReadOnlyList<Domain.Entities.Inquiry> filteredInquiries = [];
    private string searchText = "";
    private string statusFilter = "";

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

    private async Task LoadData()
    {
        isLoading = true;
        try
        {
            var (items, _) = await InquiryClient.GetPagedAsync(1, 200);
            allInquiries = items.ToList();
            ApplyFilters();

            if (allInquiries.Count > 0)
            {
                Snackbar.Add($"문의 {allInquiries.Count}건을 불러왔습니다.", Severity.Info);
            }
        }
        catch (Exception ex)
        {
            allInquiries = [];
            Snackbar.Add($"데이터 로드 실패: {ex.Message}", Severity.Error);
        }
        finally
        {
            isLoading = false;
        }
    }

    private void ApplyFilters()
    {
        IEnumerable<Domain.Entities.Inquiry> query = allInquiries;

        if (!string.IsNullOrWhiteSpace(statusFilter))
            query = query.Where(x => string.Equals(x.Status, statusFilter, StringComparison.OrdinalIgnoreCase));

        if (!string.IsNullOrWhiteSpace(searchText))
        {
            var term = searchText.Trim();
            query = query.Where(x =>
                x.Name.Contains(term, StringComparison.OrdinalIgnoreCase) ||
                x.Phone.Contains(term, StringComparison.OrdinalIgnoreCase) ||
                (x.Email?.Contains(term, StringComparison.OrdinalIgnoreCase) ?? false) ||
                (x.AdminMemo?.Contains(term, StringComparison.OrdinalIgnoreCase) ?? false) ||
                x.Message.Contains(term, StringComparison.OrdinalIgnoreCase));
        }

        filteredInquiries = query.OrderByDescending(x => x.CreatedAt).ToList();
    }

    private async Task SearchAsync()
    {
        ApplyFilters();
        await InvokeAsync(StateHasChanged);
    }

    private async Task ResetAsync()
    {
        searchText = "";
        statusFilter = "";
        ApplyFilters();
        await InvokeAsync(StateHasChanged);
    }

    private async Task OnSearchKeyUp(KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
            await SearchAsync();
    }
}
