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

<PageTitle>고객 관리</PageTitle>

<AdminPageHeader Title="고객 관리" Eyebrow="CRM" Subtitle="고객 카드를 등록하고 상담 이력을 관리합니다.">
    <ChildContent>
        <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
            <MudButton Variant="Variant.Outlined" Color="Color.Primary"
                       StartIcon="@Icons.Material.Filled.Refresh"
                       OnClick="@SearchAsync">
                새로고침
            </MudButton>
            <MudButton Variant="Variant.Filled" Color="Color.Primary"
                       StartIcon="@Icons.Material.Filled.PersonAdd"
                       Href="./clients/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="CLIENT_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="@(clients is null)" SkeletonContent="@ClientListSkeleton">
    @if (clients is null)
    {
    }
    else if (!clients.Any())
    {
        <AdminEmptyState Icon="@Icons.Material.Filled.PeopleAlt" Message="등록된 고객이 없습니다." />
    }
    else
    {
        <MudStack Row="true" AlignItems="AlignItems.Center" Justify="Justify.SpaceBetween" Class="mb-3 px-4">
            <MudText Typo="Typo.subtitle1">@($"검색 결과 {clients.Count}명 / 전체 {totalCount}명")</MudText>
            <MudText Typo="Typo.body2">페이지 @currentPage / @totalPages</MudText>
        </MudStack>

        <MudDataGrid T="Client"
            Items="@clients"
            Dense="true"
            Hover="true"
            Striped="true"
            Virtualize="true"
            RowsPerPage="30"
            Class="admin-grid mt-4">

            <Columns>
                <PropertyColumn Property="x => x.Id" Title="ID" Sortable="true"
                    Style="width: 80px;" />

                <PropertyColumn Property="x => x.Name" Title="이름" Sortable="true"
                    Filterable="true" />

                <PropertyColumn Property="x => x.CompanyName" Title="회사명" Sortable="true"
                    Filterable="true" />

                <PropertyColumn Property="x => x.Phone" Title="연락처" Sortable="false" />

                <TemplateColumn Title="서비스">
                    <CellTemplate>
                        @if (!string.IsNullOrEmpty(context.Item.ServiceType))
                        {
                            <MudChip T="string" Size="Size.Small" Color="Color.Primary" Variant="Variant.Filled">
                                @context.Item.ServiceType
                            </MudChip>
                        }
                        else
                        {
                            <span class="text-muted">—</span>
                        }
                    </CellTemplate>
                </TemplateColumn>

                <PropertyColumn Property="x => x.TaxType" Title="세금 유형" Sortable="true" />

                <TemplateColumn Title="상태" Sortable="true">
                    <CellTemplate>
                        @{
                            var isActive = context.Item.Status == "active";
                        }
                        <MudChip T="string"
                            Size="Size.Small"
                            Color="@(isActive ? Color.Success : Color.Default)"
                            Variant="Variant.Filled">
                            @(isActive ? "활성" : "비활성")
                        </MudChip>
                    </CellTemplate>
                </TemplateColumn>

                <PropertyColumn Property="x => x.Source" Title="유입 경로" Sortable="true" />

                <PropertyColumn Property="x => x.CreatedAt" Title="등록일" Sortable="true"
                    Format="yyyy-MM-dd" />

                <TemplateColumn Title="작업" CellStyleFunc="@(_ => "text-align: center;")">
                    <CellTemplate>
                        <MudButtonGroup Size="Size.Small" Variant="Variant.Outlined">
                            <MudButton Color="Color.Primary"
                                Href="@($"./clients/{context.Item.Id}/edit")">
                                @Icons.Material.Filled.Edit
                            </MudButton>
                            <MudButton Color="Color.Error"
                                @onclick="@(() => DeleteAsync(context.Item))">
                                @Icons.Material.Filled.Delete
                            </MudButton>
                        </MudButtonGroup>
                    </CellTemplate>
                </TemplateColumn>
            </Columns>
        </MudDataGrid>

        @* 페이징 *@
        @if (totalPages > 1)
        {
            <div class="d-flex justify-center pa-3">
                <MudPagination BoundaryCount="1" MiddleCount="3"
                               Count="@totalPages" Selected="@currentPage"
                               SelectedChanged="@OnPageChanged" />
            </div>
        }
    }
</AdminDataPanel>

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

    private List<Client>? clients;
    private string searchText = "";
    private string statusFilter = "";
    private int currentPage = 1;
    private int totalCount;
    private int totalPages;
    private const int PageSize = 20;

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

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

    private async Task LoadAsync()
    {
        try
        {
            var (items, total) = await ClientClient.GetPagedAsync(
                currentPage, PageSize,
                string.IsNullOrEmpty(statusFilter) ? null : statusFilter,
                string.IsNullOrEmpty(searchText) ? null : searchText);

            clients = items.ToList();
            totalCount = total;
            totalPages = (int)Math.Ceiling((double)total / PageSize);

            if (clients.Count > 0)
            {
                Snackbar.Add($"고객 {clients.Count}명을 불러왔습니다.", Severity.Info);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"오류: {ex.Message}", Severity.Error);
            clients = [];
            totalCount = 0;
            totalPages = 0;
        }
    }

    private async Task SearchAsync()
    {
        currentPage = 1;
        await LoadAsync();
    }

    private async Task ResetAsync()
    {
        searchText = "";
        statusFilter = "";
        currentPage = 1;
        await LoadAsync();
    }

    private async Task OnPageChanged(int page)
    {
        currentPage = page;
        await LoadAsync();
    }

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

    private async Task DeleteAsync(Client client)
    {
        var confirmed = await DialogService.ShowMessageBox(
            "고객 삭제",
            $"'{client.Name}' 고객을 삭제하시겠습니까? 관련 데이터도 함께 삭제됩니다.",
            yesText: "삭제", cancelText: "취소");

        if (confirmed != true) return;

        try
        {
            var success = await ClientClient.DeleteAsync(client.Id);
            if (success)
            {
                Snackbar.Add($"{client.Name} 고객이 삭제되었습니다.", Severity.Success);
                await LoadAsync();
            }
            else
            {
                Snackbar.Add("삭제에 실패했습니다.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"오류: {ex.Message}", Severity.Error);
        }
    }
}
