@page "/superadmin/merchants/{MerchantId:guid}"
@layout SuperAdminLayout
@inherits SuperAdminBase
@inject SuperAdminApiService Api
@using WebClientTpos.Client.Services

<PageTitle>Chi tiết doanh nghiệp — aPOS Super Admin</PageTitle>

<div class="sa-topbar">
    <div class="sa-topbar__left">
        <div style="display:flex;align-items:center;gap:12px;">
            <a href="/superadmin/merchants" style="color:var(--sa-text-tertiary);text-decoration:none;display:flex;align-items:center;">
                <i data-lucide="arrow-left" style="width:18px;height:18px;"></i>
            </a>
            <div>
                <h1 class="sa-topbar__title">@(_detail?.BusinessName ?? "Đang tải...")</h1>
                <p class="sa-topbar__subtitle">
                    @if (_detail != null)
                    {
                        <span class="sa-badge @GetStatusBadge(_detail.Status)">@GetStatusLabel(_detail.Status)</span>
                        <span> • ID: @MerchantId.ToString()[..8]...</span>
                    }
                </p>
            </div>
        </div>
    </div>
    <div class="sa-topbar__right">
        @if (_detail != null)
        {
            @if (_detail.Status?.Equals("PendingApproval", StringComparison.OrdinalIgnoreCase) == true)
            {
                <button class="sa-btn-primary" @onclick="ApproveAsync">
                    <i data-lucide="check" style="width:14px;height:14px;"></i> Phê duyệt
                </button>
            }
            @if (_detail.Status?.Equals("Active", StringComparison.OrdinalIgnoreCase) == true)
            {
                <button class="sa-btn-outline" style="color:var(--sa-danger);border-color:var(--sa-danger);" @onclick="SuspendAsync">
                    <i data-lucide="ban" style="width:14px;height:14px;"></i> Tạm ngưng
                </button>
            }
            @if (_detail.Status?.Equals("Suspended", StringComparison.OrdinalIgnoreCase) == true)
            {
                <button class="sa-btn-primary" style="background:var(--sa-success);" @onclick="ReactivateAsync">
                    <i data-lucide="check-circle" style="width:14px;height:14px;"></i> Kích hoạt lại
                </button>
            }
        }
    </div>
</div>

<div class="sa-content">
    @if (_detail == null)
    {
        <div class="sa-panel">
            <div class="sa-panel__body" style="text-align:center;padding:48px;">
                <p style="color:var(--sa-text-tertiary);">Đang tải thông tin doanh nghiệp...</p>
            </div>
        </div>
    }
    else
    {
        @* ── TABS ── *@
        <div class="sa-tabs" style="background:var(--sa-bg-elevated);border-radius:12px 12px 0 0;border:1px solid var(--sa-border);border-bottom:none;">
            <button class="sa-tab @(_activeTab == "info" ? "sa-tab--active" : "")" @onclick='() => _activeTab = "info"'>Thông tin</button>
            <button class="sa-tab @(_activeTab == "shops" ? "sa-tab--active" : "")" @onclick='() => _activeTab = "shops"'>Cửa hàng (@(_detail.Shops?.Count ?? 0))</button>
            <button class="sa-tab @(_activeTab == "subscription" ? "sa-tab--active" : "")" @onclick='() => _activeTab = "subscription"'>Gói đăng ký</button>
        </div>

        <div class="sa-panel" style="border-radius:0 0 12px 12px;">
            @if (_activeTab == "info")
            {
                <div class="sa-panel__body">
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">
                        <div>
                            <h4 style="font-size:14px;font-weight:700;color:var(--sa-text-primary);margin:0 0 16px;">Thông tin kinh doanh</h4>
                            @InfoRow("Tên doanh nghiệp", _detail.BusinessName)
                            @InfoRow("Loại hình", _detail.Type)
                            @InfoRow("Mã số thuế", _detail.TaxCode)
                            @InfoRow("Website", _detail.Website)
                        </div>
                        <div>
                            <h4 style="font-size:14px;font-weight:700;color:var(--sa-text-primary);margin:0 0 16px;">Liên hệ</h4>
                            @InfoRow("Email", _detail.Email)
                            @InfoRow("Số điện thoại", _detail.Phone)
                            @InfoRow("Địa chỉ", _detail.Address)
                            @InfoRow("Thành phố", _detail.City)
                            @InfoRow("Quận/Huyện", _detail.District)
                        </div>
                    </div>
                    <div style="margin-top:24px;display:grid;grid-template-columns:1fr 1fr;gap:24px;">
                        <div>
                            <h4 style="font-size:14px;font-weight:700;color:var(--sa-text-primary);margin:0 0 16px;">Trạng thái</h4>
                            @InfoRow("Trạng thái", GetStatusLabel(_detail.Status))
                            @InfoRow("Xác minh", _detail.VerificationStatus)
                            @InfoRow("Ngày xác minh", _detail.VerifiedAt?.ToString("dd/MM/yyyy HH:mm"))
                        </div>
                        <div>
                            <h4 style="font-size:14px;font-weight:700;color:var(--sa-text-primary);margin:0 0 16px;">Thống kê</h4>
                            @InfoRow("Tổng cửa hàng", _detail.ShopsCount.ToString())
                            @InfoRow("Tổng nhân viên", _detail.StaffCount.ToString())
                            @InfoRow("Ngày tạo", _detail.CreatedAt.ToString("dd/MM/yyyy HH:mm"))
                            @InfoRow("Đăng nhập cuối", _detail.LastLoginAt?.ToString("dd/MM/yyyy HH:mm"))
                        </div>
                    </div>
                </div>
            }
            else if (_activeTab == "shops")
            {
                @if (_detail.Shops?.Any() == true)
                {
                    <table class="sa-table">
                        <thead>
                            <tr>
                                <th>Tên cửa hàng</th>
                                <th>Ngành hàng</th>
                                <th>Trạng thái</th>
                                <th>Ngày tạo</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var shop in _detail.Shops)
                            {
                                <tr>
                                    <td>@shop.Name</td>
                                    <td>@(shop.Category ?? "—")</td>
                                    <td><span class="sa-badge @GetShopStatusBadge(shop.Status)">@(shop.Status ?? "—")</span></td>
                                    <td>@shop.CreatedAt.ToString("dd/MM/yyyy")</td>
                                </tr>
                            }
                        </tbody>
                    </table>
                }
                else
                {
                    <div class="sa-empty">
                        <p>Chưa có cửa hàng nào</p>
                    </div>
                }
            }
            else if (_activeTab == "subscription")
            {
                <div class="sa-panel__body">
                    @* Current plan display *@
                    <div style="display:flex;align-items:center;gap:16px;padding:20px;background:var(--sa-bg-interactive);border-radius:10px;">
                        <div style="width:48px;height:48px;border-radius:12px;background:var(--sa-blue-bg);display:flex;align-items:center;justify-content:center;">
                            <i data-lucide="credit-card" style="width:24px;height:24px;color:var(--sa-blue-light);"></i>
                        </div>
                        <div>
                            <div style="font-size:18px;font-weight:700;color:var(--sa-text-primary);">
                                @(_detail.PlanName ?? "Starter")
                            </div>
                            <div style="font-size:13px;color:var(--sa-text-tertiary);">Gói hiện tại</div>
                        </div>
                    </div>

                    @* Plan selector *@
                    <h4 style="font-size:14px;font-weight:700;color:var(--sa-text-primary);margin:24px 0 12px;">Đổi gói đăng ký</h4>
                    <div style="display:grid;grid-template-columns:repeat(4, 1fr);gap:12px;">
                        @foreach (var plan in _planOptions)
                        {
                            var isActive = plan.Id == (_detail.SubscriptionPlanId);
                            <div @onclick="@(() => SelectPlan(plan.Id))"
                                 style="padding:16px;border-radius:10px;cursor:pointer;border:2px solid @(isActive ? "var(--sa-blue-light)" : "var(--sa-border)");background:@(isActive ? "var(--sa-blue-bg)" : "var(--sa-bg-interactive)");transition:all 0.15s ease;">
                                <div style="font-size:15px;font-weight:700;color:var(--sa-text-primary);">@plan.Name</div>
                                <div style="font-size:13px;color:var(--sa-blue-light);font-weight:600;margin-top:4px;">
                                    @(plan.Price > 0 ? $"{plan.Price:N0}đ/tháng" : plan.Name == "Enterprise" ? "Liên hệ" : "Miễn phí")
                                </div>
                                <div style="font-size:11px;color:var(--sa-text-tertiary);margin-top:6px;">
                                    @plan.MaxShops cửa hàng • @plan.MaxStaff nhân viên
                                </div>
                                @if (isActive)
                                {
                                    <span class="sa-badge sa-badge--success" style="margin-top:8px;">Hiện tại</span>
                                }
                            </div>
                        }
                    </div>

                    @if (_selectedPlanId != _detail.SubscriptionPlanId)
                    {
                        <div style="margin-top:16px;display:flex;align-items:center;gap:12px;">
                            <button class="sa-btn-primary" @onclick="SavePlanAsync">
                                <i data-lucide="save" style="width:14px;height:14px;"></i>
                                Lưu thay đổi → @(_planOptions.FirstOrDefault(p => p.Id == _selectedPlanId)?.Name)
                            </button>
                            <button class="sa-btn-outline" @onclick="@(() => _selectedPlanId = _detail.SubscriptionPlanId)">
                                Hủy
                            </button>
                            @if (!string.IsNullOrEmpty(_planMessage))
                            {
                                <span style="font-size:13px;color:@(_planSuccess ? "var(--sa-success)" : "var(--sa-danger)");">@_planMessage</span>
                            }
                        </div>
                    }
                </div>
            }
        </div>
    }
</div>

@code {
    [Parameter] public Guid MerchantId { get; set; }

    private SuperAdminApiService.MerchantDetailDto? _detail;
    private string _activeTab = "info";
    private int _selectedPlanId;
    private string? _planMessage;
    private bool _planSuccess;

    private record PlanOption(int Id, string Name, decimal Price, int MaxShops, int MaxStaff);
    private static readonly PlanOption[] _planOptions =
    [
        new(0, "Starter", 0, 1, 5),
        new(1, "Growth", 299000, 3, 15),
        new(2, "Pro", 799000, 10, 50),
        new(3, "Enterprise", 0, 999, 999),
    ];

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        _detail = await Api.GetMerchantDetailAsync(MerchantId);
        if (_detail != null)
            _selectedPlanId = _detail.SubscriptionPlanId;
    }

    private void SelectPlan(int planId) => _selectedPlanId = planId;

    private async Task SavePlanAsync()
    {
        _planMessage = null;
        var (ok, err) = await Api.UpdateMerchantPlanAsync(MerchantId, _selectedPlanId);
        if (ok)
        {
            _planSuccess = true;
            _planMessage = "Đã cập nhật gói đăng ký thành công!";
            _detail = await Api.GetMerchantDetailAsync(MerchantId);
        }
        else
        {
            _planSuccess = false;
            _planMessage = err ?? "Cập nhật thất bại";
        }
    }

    private async Task ApproveAsync()
    {
        await Api.ApproveMerchantAsync(MerchantId);
        _detail = await Api.GetMerchantDetailAsync(MerchantId);
    }

    private async Task SuspendAsync()
    {
        await Api.SuspendMerchantAsync(MerchantId, "Tạm ngưng bởi Super Admin");
        _detail = await Api.GetMerchantDetailAsync(MerchantId);
    }

    private async Task ReactivateAsync()
    {
        await Api.ReactivateMerchantAsync(MerchantId);
        _detail = await Api.GetMerchantDetailAsync(MerchantId);
    }

    private static RenderFragment InfoRow(string label, string? value) => builder =>
    {
        builder.OpenElement(0, "div");
        builder.AddAttribute(1, "style", "display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--sa-border-subtle);");
        builder.OpenElement(2, "span");
        builder.AddAttribute(3, "style", "font-size:13px;color:var(--sa-text-tertiary);");
        builder.AddContent(4, label);
        builder.CloseElement();
        builder.OpenElement(5, "span");
        builder.AddAttribute(6, "style", "font-size:13px;color:var(--sa-text-primary);font-weight:500;");
        builder.AddContent(7, value ?? "—");
        builder.CloseElement();
        builder.CloseElement();
    };

    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", _ => s ?? "—"
    };

    private static string GetShopStatusBadge(string? s) => s?.ToLowerInvariant() switch
    {
        "active" => "sa-badge--success", "setup" => "sa-badge--warning",
        "paused" or "closed" => "sa-badge--danger", _ => "sa-badge--neutral"
    };
}
