@page "/admin/stores"
@layout AdminLayout
@inherits AdminBase
@inject PosDataService DataService
@using WebClientTpos.Client.Services

@*
    EN: Store list — all stores with tabs, search, filter (real data from API).
    VI: Danh sách cửa hàng — tất cả cửa hàng với tabs, tìm kiếm, lọc (dữ liệu thực từ API).
*@

<PageTitle>Quản lý cửa hàng — aPOS Admin</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">Quản lý cửa hàng</h1>
        <p class="admin-topbar__subtitle">Tạo và quản lý tất cả cửa hàng trong hệ thống</p>
    </div>
    <div class="admin-topbar__right">
        <div class="admin-search" style="width:260px;">
            <i data-lucide="search"></i>
            <input type="text" placeholder="Tìm cửa hàng..." @bind="SearchQuery" @bind:event="oninput" />
        </div>
        <button class="admin-btn-primary" @onclick="@(() => NavigateTo("stores/create"))">
            <i data-lucide="plus"></i>
            <span>Tạo cửa hàng</span>
        </button>
    </div>
</div>

@* ═══ TABS ═══ *@
<div class="admin-tabs">
    <button class="admin-tab @(_activeTab == "all" ? "admin-tab--active" : "")" @onclick="@(() => _activeTab = "all")">
        Tất cả
        <span class="admin-tab__badge admin-tab__badge--active">@_shops.Count</span>
    </button>
    <button class="admin-tab @(_activeTab == "active" ? "admin-tab--active" : "")" @onclick="@(() => _activeTab = "active")">
        Hoạt động
        <span class="admin-tab__badge">@_shops.Count(s => ShopVerticalHelper.IsActive(s.Status))</span>
    </button>
    <button class="admin-tab @(_activeTab == "setup" ? "admin-tab--active" : "")" @onclick="@(() => _activeTab = "setup")">
        Thiết lập
        <span class="admin-tab__badge">@_shops.Count(s => ShopVerticalHelper.IsSetup(s.Status))</span>
    </button>
    <button class="admin-tab @(_activeTab == "paused" ? "admin-tab--active" : "")" @onclick="@(() => _activeTab = "paused")">
        Tạm dừng
        <span class="admin-tab__badge">@_shops.Count(s => ShopVerticalHelper.IsPaused(s.Status))</span>
    </button>
</div>

@* ═══ STORE LIST ═══ *@
<div class="admin-content" style="display:flex;flex-direction:column;gap:16px;padding:28px 32px;">

    @if (!string.IsNullOrEmpty(_errorMessage))
    {
        <div class="admin-panel" style="border:1px solid rgba(239,68,68,0.3);">
            <div class="admin-panel__body" style="text-align:center;padding:40px 20px;">
                <div style="width:64px;height:64px;border-radius:20px;background:rgba(239,68,68,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
                    <i data-lucide="alert-circle" style="width:28px;height:28px;color:#EF4444;"></i>
                </div>
                <h3 style="font-size:16px;font-weight:700;margin:0 0 8px;color:#EF4444;">Lỗi tải dữ liệu</h3>
                <p style="font-size:13px;color:var(--admin-text-tertiary);margin:0 0 16px;">@_errorMessage</p>
                <button class="admin-btn-primary" @onclick="LoadData" style="display:inline-flex;align-items:center;gap:8px;">
                    <i data-lucide="refresh-cw" style="width:14px;height:14px;"></i>
                    Thử lại
                </button>
            </div>
        </div>
    }
    else if (IsLoading)
    {
        <div style="text-align:center;padding:48px 20px;">
            <div class="spinner-small" style="width:32px;height:32px;margin:0 auto 16px;"></div>
            <p style="color:var(--admin-text-tertiary);font-size:14px;">Đang tải danh sách cửa hàng...</p>
        </div>
    }
    else if (!FilteredShops.Any())
    {
        <div style="text-align:center;padding:48px 20px;">
            <i data-lucide="store" style="width:48px;height:48px;color:var(--admin-orange-primary);margin-bottom:16px;"></i>
            <h3 style="font-size:18px;font-weight:700;color:var(--pos-text-primary, #FFFFFF);margin:0 0 8px;">
                @if (_shops.Count == 0)
                {
                    @:Chưa có cửa hàng nào
                }
                else
                {
                    @:Không tìm thấy cửa hàng
                }
            </h3>
            <p style="font-size:14px;color:var(--pos-text-tertiary, #ADADB0);margin:0 0 20px;">
                @if (_shops.Count == 0)
                {
                    @:Bắt đầu bằng việc tạo cửa hàng đầu tiên.
                }
                else
                {
                    @:Thử thay đổi bộ lọc hoặc từ khóa tìm kiếm.
                }
            </p>
            @if (_shops.Count == 0)
            {
                <a href="/admin/stores/create" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;">
                    <i data-lucide="plus" style="width:16px;height:16px;"></i>
                    Tạo cửa hàng ngay
                </a>
            }
        </div>
    }
    else
    {
        @foreach (var shop in FilteredShops)
        {
            var isPaused = ShopVerticalHelper.IsPaused(shop.Status);
            var stats = GetStatsForShop(shop.Id);
            <div class="admin-store-list-card @(isPaused ? "admin-store-list-card--paused" : "")" @onclick="@(() => NavigateTo($"shop/{shop.Id}/overview"))">
                <div class="admin-store-list-card__left">
                    <div class="admin-store-card__avatar" style="width:52px;height:52px;background-color:@(ShopVerticalHelper.GetBgColor(shop.Category));border-radius:14px;">
                        <i data-lucide="@ShopVerticalHelper.GetIcon(shop.Category)" style="color:@(ShopVerticalHelper.GetColor(shop.Category));width:24px;height:24px;"></i>
                    </div>
                    <div class="admin-store-list-card__info">
                        <div style="display:flex;align-items:center;gap:10px;">
                            <span style="font-size:16px;font-weight:600;">@shop.Name</span>
                            <div class="admin-status-badge admin-status-badge--@ShopVerticalHelper.GetStatusBadgeClass(shop.Status)">
                                <span class="admin-status-badge__dot"></span>
                                @ShopVerticalHelper.GetStatusLabel(shop.Status)
                            </div>
                        </div>
                        <span style="font-size:12px;color:var(--admin-text-tertiary);">@ShopVerticalHelper.GetLabel(shop.Category) • @(shop.Slug)</span>
                    </div>
                </div>
                <div class="admin-store-list-card__stats">
                    <div class="admin-store-stat">
                        <div class="admin-store-stat__value" style="@(isPaused ? "opacity:0.5;" : "")">@FormatRevenue(stats.Revenue)</div>
                        <div class="admin-store-stat__label">Doanh thu</div>
                    </div>
                    <div class="admin-store-stat">
                        <div class="admin-store-stat__value" style="@(isPaused ? "opacity:0.5;" : "")">@stats.OrderCount</div>
                        <div class="admin-store-stat__label">Đơn hàng</div>
                    </div>
                    <div class="admin-store-stat">
                        <div class="admin-store-stat__value" style="@(isPaused ? "opacity:0.5;" : "")">@stats.StaffCount</div>
                        <div class="admin-store-stat__label">Nhân viên</div>
                    </div>
                    <div class="admin-store-stat">
                        <div class="admin-store-stat__value" style="@(isPaused ? "opacity:0.5;" : "")">@stats.ProductCount</div>
                        <div class="admin-store-stat__label">Sản phẩm</div>
                    </div>
                </div>
                <div class="admin-store-list-card__actions">
                    @if (ShopVerticalHelper.IsSetup(shop.Status))
                    {
                        <button class="admin-btn-primary" style="font-size:12px;padding:6px 12px;" @onclick:stopPropagation @onclick="@(() => NavigateTo($"shop/{shop.Id}/overview"))">
                            <i data-lucide="settings" style="width:14px;height:14px;"></i>
                            Hoàn tất thiết lập
                        </button>
                    }
                    else if (isPaused)
                    {
                        <button class="admin-btn-secondary" style="font-size:12px;padding:6px 12px;" @onclick:stopPropagation>
                            <i data-lucide="play" style="width:14px;height:14px;"></i>
                            Kích hoạt lại
                        </button>
                    }
                    else
                    {
                        <button class="admin-icon-btn" title="Cài đặt" @onclick:stopPropagation @onclick="@(() => NavigateTo($"stores/{shop.Id}/settings"))">
                            <i data-lucide="settings"></i>
                        </button>
                        <button class="admin-icon-btn" title="Xem chi tiết">
                            <i data-lucide="chevron-right"></i>
                        </button>
                    }
                </div>
            </div>
        }
    }
</div>

@code {
    private List<PosDataService.ShopInfo> _shops = new();
    private List<PosDataService.ShopStatsInfo> _shopStats = new();
    private string _activeTab = "all";
    private string? _errorMessage;

    private IEnumerable<PosDataService.ShopInfo> FilteredShops => _shops
        .Where(s => _activeTab == "all" 
            || (_activeTab == "active" && ShopVerticalHelper.IsActive(s.Status))
            || (_activeTab == "setup" && ShopVerticalHelper.IsSetup(s.Status))
            || (_activeTab == "paused" && ShopVerticalHelper.IsPaused(s.Status)))
        .Where(s => string.IsNullOrWhiteSpace(SearchQuery)
            || (s.Name?.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase) ?? false)
            || (s.Slug?.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase) ?? false)
            || (s.Category?.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase) ?? false));

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

    private async Task LoadData()
    {
        IsLoading = true;
        _errorMessage = null;
        try
        {
            // EN: Load shops and stats in parallel / VI: Tải shops và stats song song
            var shopsTask = DataService.GetShopsAsync();
            var statsTask = DataService.GetShopStatsAsync();
            _shops = await shopsTask;
            _shopStats = await statsTask;
        }
        catch (Exception ex)
        {
            _errorMessage = $"Không thể tải danh sách cửa hàng: {ex.Message}";
            Console.Error.WriteLine($"[StoreList] Error: {ex}");
        }
        finally
        {
            IsLoading = false;
        }
    }

    // EN: Get stats for a specific shop / VI: Lấy stats cho shop cụ thể
    private PosDataService.ShopStatsInfo GetStatsForShop(Guid shopId) =>
        _shopStats.FirstOrDefault(s => s.ShopId == shopId)
        ?? new PosDataService.ShopStatsInfo(shopId, 0, 0, 0, 0);

    private static string FormatRevenue(decimal val)
    {
        if (val >= 1_000_000) return $"{val / 1_000_000:0.#}M";
        if (val >= 1_000) return $"{val / 1_000:0.#}K";
        return val == 0 ? "0₫" : $"{val:N0}₫";
    }
}
