@page "/superadmin/merchants"
@layout SuperAdminLayout
@inherits SuperAdminBase
@inject SuperAdminApiService Api
@using WebClientTpos.Client.Services

<PageTitle>Doanh nghiệp — aPOS Super Admin</PageTitle>

<div class="sa-topbar">
    <div class="sa-topbar__left">
        <h1 class="sa-topbar__title">Quản lý doanh nghiệp</h1>
        <p class="sa-topbar__subtitle">Danh sách tất cả doanh nghiệp trên nền tảng</p>
    </div>
    <div class="sa-topbar__right">
        <div class="sa-search">
            <i data-lucide="search"></i>
            <input type="text" placeholder="Tìm theo tên, email..." @bind="SearchQuery" @bind:event="oninput" @bind:after="OnSearchChanged" />
        </div>
    </div>
</div>

<div class="sa-content">
    @* ── FILTER TABS ── *@
    <div class="sa-tabs">
        <button class="sa-tab @(_statusFilter == null ? "sa-tab--active" : "")" @onclick="() => FilterByStatus(null)">
            Tất cả (@_totalCount)
        </button>
        <button class="sa-tab @(_statusFilter == "Active" ? "sa-tab--active" : "")" @onclick='() => FilterByStatus("Active")'>
            Hoạt động
        </button>
        <button class="sa-tab @(_statusFilter == "PendingApproval" ? "sa-tab--active" : "")" @onclick='() => FilterByStatus("PendingApproval")'>
            Chờ duyệt
        </button>
        <button class="sa-tab @(_statusFilter == "Suspended" ? "sa-tab--active" : "")" @onclick='() => FilterByStatus("Suspended")'>
            Tạm ngưng
        </button>
    </div>

    @* ── TABLE ── *@
    <div class="sa-panel">
        @if (IsLoading)
        {
            <div class="sa-panel__body" style="text-align:center;padding:48px;">
                <p style="color:var(--sa-text-tertiary);">Đang tải dữ liệu...</p>
            </div>
        }
        else if (_merchants.Any())
        {
            <table class="sa-table">
                <thead>
                    <tr>
                        <th>Tên doanh nghiệp</th>
                        <th>Loại hình</th>
                        <th>Trạng thái</th>
                        <th>Xác minh</th>
                        <th>Cửa hàng</th>
                        <th>Nhân viên</th>
                        <th>Gói</th>
                        <th>Ngày tạo</th>
                        <th>Hành động</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var m in _merchants)
                    {
                        <tr>
                            <td>
                                <a href="/superadmin/merchants/@m.Id" style="color:var(--sa-blue-light);text-decoration:none;">
                                    @m.BusinessName
                                </a>
                                @if (!string.IsNullOrEmpty(m.Email))
                                {
                                    <div style="font-size:11px;color:var(--sa-text-tertiary);">@m.Email</div>
                                }
                            </td>
                            <td>@(m.Type ?? "—")</td>
                            <td><span class="sa-badge @GetStatusBadge(m.Status)">@GetStatusLabel(m.Status)</span></td>
                            <td><span class="sa-badge @GetVerifBadge(m.VerificationStatus)">@GetVerifLabel(m.VerificationStatus)</span></td>
                            <td>@m.ShopsCount</td>
                            <td>@m.StaffCount</td>
                            <td>@(m.PlanName ?? "Starter")</td>
                            <td>@m.CreatedAt.ToString("dd/MM/yyyy")</td>
                            <td style="white-space:nowrap;">
                                @if (m.Status?.Equals("PendingApproval", StringComparison.OrdinalIgnoreCase) == true)
                                {
                                    <button class="sa-btn-primary" style="font-size:11px;padding:4px 10px;" @onclick="() => ApproveAsync(m.Id)">
                                        Duyệt
                                    </button>
                                }
                                @if (m.Status?.Equals("Active", StringComparison.OrdinalIgnoreCase) == true)
                                {
                                    <button class="sa-btn-outline" style="font-size:11px;padding:4px 10px;color:var(--sa-danger);border-color:var(--sa-danger);"
                                            @onclick="() => SuspendAsync(m.Id, m.BusinessName)">
                                        Tạm ngưng
                                    </button>
                                }
                                @if (m.Status?.Equals("Suspended", StringComparison.OrdinalIgnoreCase) == true)
                                {
                                    <button class="sa-btn-outline" style="font-size:11px;padding:4px 10px;color:var(--sa-success);border-color:var(--sa-success);"
                                            @onclick="() => ReactivateAsync(m.Id)">
                                        Kích hoạt lại
                                    </button>
                                }
                            </td>
                        </tr>
                    }
                </tbody>
            </table>

            @* Pagination *@
            @if (_totalPages > 1)
            {
                <div style="display:flex;align-items:center;justify-content:center;gap:8px;padding:16px;">
                    <button class="sa-btn-outline" disabled="@(_currentPage <= 1)" @onclick="PrevPage">← Trước</button>
                    <span style="font-size:13px;color:var(--sa-text-secondary);">Trang @_currentPage / @_totalPages</span>
                    <button class="sa-btn-outline" disabled="@(_currentPage >= _totalPages)" @onclick="NextPage">Sau →</button>
                </div>
            }
        }
        else
        {
            <div class="sa-empty">
                <div class="sa-empty__icon">
                    <i data-lucide="building-2" style="width:24px;height:24px;color:var(--sa-text-tertiary);"></i>
                </div>
                <p>Không tìm thấy doanh nghiệp nào</p>
            </div>
        }
    </div>
</div>

@code {
    private List<SuperAdminApiService.MerchantAdminDto> _merchants = new();
    private int _totalCount = 0;
    private int _currentPage = 1;
    private int _pageSize = 20;
    private int _totalPages => Math.Max(1, (int)Math.Ceiling((double)_totalCount / _pageSize));
    private string? _statusFilter;
    private string? _lastSearch;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await LoadAsync();
    }

    private async Task LoadAsync()
    {
        IsLoading = true;
        StateHasChanged();
        var (items, total) = await Api.GetMerchantsAsync(_currentPage, _pageSize, _statusFilter, SearchQuery);
        _merchants = items;
        _totalCount = total;
        IsLoading = false;
        StateHasChanged();
    }

    private async Task FilterByStatus(string? status)
    {
        _statusFilter = status;
        _currentPage = 1;
        await LoadAsync();
    }

    private async Task OnSearchChanged()
    {
        if (SearchQuery != _lastSearch)
        {
            _lastSearch = SearchQuery;
            _currentPage = 1;
            await LoadAsync();
        }
    }

    private async Task PrevPage() { _currentPage--; await LoadAsync(); }
    private async Task NextPage() { _currentPage++; await LoadAsync(); }

    private async Task ApproveAsync(Guid id)
    {
        var (ok, err) = await Api.ApproveMerchantAsync(id);
        await LoadAsync();
    }

    private async Task SuspendAsync(Guid id, string name)
    {
        var (ok, err) = await Api.SuspendMerchantAsync(id, $"Tạm ngưng bởi Super Admin");
        await LoadAsync();
    }

    private async Task ReactivateAsync(Guid id)
    {
        var (ok, err) = await Api.ReactivateMerchantAsync(id);
        await LoadAsync();
    }

    private static string GetStatusBadge(string? s) => s?.ToLowerInvariant() switch
    {
        "active" => "sa-badge--success",
        "pendingapproval" or "pending" => "sa-badge--warning",
        "suspended" => "sa-badge--danger",
        _ => "sa-badge--neutral"
    };

    private static string GetStatusLabel(string? s) => s?.ToLowerInvariant() switch
    {
        "active" => "Hoạt động",
        "pendingapproval" or "pending" => "Chờ duyệt",
        "suspended" => "Tạm ngưng",
        "inactive" => "Không hoạt động",
        _ => s ?? "—"
    };

    private static string GetVerifBadge(string? v) => v?.ToLowerInvariant() switch
    {
        "verified" => "sa-badge--success",
        "pending" or "pendingverification" => "sa-badge--warning",
        "rejected" => "sa-badge--danger",
        _ => "sa-badge--neutral"
    };

    private static string GetVerifLabel(string? v) => v?.ToLowerInvariant() switch
    {
        "verified" => "Đã xác minh",
        "pending" or "pendingverification" => "Chờ xác minh",
        "rejected" => "Từ chối",
        _ => v ?? "Chưa xác minh"
    };
}
