@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@inject PosDataService DataService

<div style="padding:8px 14px;border-radius:8px;background:rgba(59,130,246,.08);border:1px solid rgba(59,130,246,.15);margin-bottom:12px;display:flex;align-items:center;gap:8px;font-size:12px;color:var(--admin-text-secondary);">
    <i data-lucide="info" style="width:14px;height:14px;color:#3B82F6;flex-shrink:0;"></i>
    Chiến dịch khuyến mãi chung cho tất cả cửa hàng trong thương hiệu
</div>
@* ─── Sub-tabs: Campaigns | Vouchers ─── *@
<div style="display:flex;gap:8px;margin-bottom:16px;">
    @{ var promoTabs = new[] { ("campaigns", "Chiến dịch", "tag"), ("vouchers", "Mã voucher", "ticket") }; }
    @foreach (var (tab, label, icon) in promoTabs)
    {
        var t = tab;
        var isActive = _promoSubTab == t;
        <button @onclick="@(() => SwitchPromoTab(t))"
            class="@(isActive ? "admin-btn-primary" : "")"
            style="padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);font-size:13px;display:inline-flex;align-items:center;gap:6px;cursor:pointer;@(isActive ? "background:var(--admin-orange-primary);color:#FFF;font-weight:700;border-color:var(--admin-orange-primary);" : "background:var(--admin-bg-elevated);color:var(--admin-text-secondary);font-weight:500;")">
            <i data-lucide="@icon" style="width:14px;height:14px;"></i>@label
        </button>
    }
</div>
@if (_promoSubTab == "campaigns")
{
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
    <h3 style="margin:0;font-size:16px;font-weight:700;">@_campaigns.Count chiến dịch</h3>
    <button class="admin-btn-primary" style="font-size:12px;padding:6px 14px;" @onclick='() => { _showCampaignForm = !_showCampaignForm; _editingCampaignId = null; _newCampaignName = ""; _newCampaignDesc = ""; _newCampaignValue = 0; _newCampaignVouchers = 0; _newCampaignDiscountType = "fixed"; _newCampaignStart = DateTime.Today; _newCampaignEnd = DateTime.Today.AddMonths(1); _campaignFormMessage = null; }'>
        <i data-lucide="plus" style="width:14px;height:14px;margin-right:4px;"></i>Thêm chiến dịch
    </button>
</div>
@if (_showCampaignForm)
{
    <div class="admin-panel" style="margin-bottom:16px;">
        <div class="admin-panel__header"><h3 class="admin-panel__title">@(_editingCampaignId.HasValue ? "Sửa chiến dịch" : "Thêm chiến dịch")</h3></div>
        <div class="admin-panel__body">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Tên chiến dịch *</label><input type="text" @bind="_newCampaignName" placeholder="Tên chiến dịch..." style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Mô tả</label><input type="text" @bind="_newCampaignDesc" placeholder="Mô tả..." style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Loại giảm giá *</label>
                    <select @bind="_newCampaignDiscountType" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);">
                        <option value="fixed">Theo giá tiền (₫)</option>
                        <option value="percentage">Theo phần trăm (%)</option>
                    </select>
                </div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Giá trị @(_newCampaignDiscountType == "percentage" ? "(%)" : "(₫)") *</label><input type="number" @bind="_newCampaignValue" min="0" max="@(_newCampaignDiscountType == "percentage" ? 100 : 999999999)" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Số lượng voucher *</label><input type="number" @bind="_newCampaignVouchers" min="1" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Ngày bắt đầu *</label><input type="date" @bind="_newCampaignStart" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Ngày kết thúc *</label><input type="date" @bind="_newCampaignEnd" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
            </div>
            @if (_campaignFormMessage != null)
            {
                <div style="margin-top:12px;padding:8px 12px;border-radius:8px;background:@(_campaignFormSuccess ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)");color:@(_campaignFormSuccess ? "#22C55E" : "#EF4444");font-size:13px;">@_campaignFormMessage</div>
            }
            <div style="display:flex;gap:8px;margin-top:12px;">
                <button class="admin-btn-primary" style="font-size:12px;padding:6px 16px;" @onclick="SaveCampaign">Lưu</button>
                <button style="padding:6px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;cursor:pointer;" @onclick='() => { _showCampaignForm = false; _campaignFormMessage = null; }'>Hủy</button>
            </div>
        </div>
    </div>
}
@if (!_campaigns.Any())
{
    <div style="text-align:center;padding:60px 20px;">
        <div style="width:80px;height:80px;border-radius:24px;background:rgba(34,197,94,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
            <i data-lucide="tag" style="width:36px;height:36px;color:#22C55E;"></i>
        </div>
        <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">Chưa có chiến dịch</h2>
        <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">Tạo chiến dịch voucher, khuyến mãi cho khách hàng</p>
        <a href="/admin/shop/@ShopId/menu" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;">
            <i data-lucide="plus-circle" style="width:16px;height:16px;"></i>
            Thêm chiến dịch
        </a>
    </div>
}
else
{
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;">
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(34,197,94,0.1);"><i data-lucide="tag" style="color:#22C55E;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_campaigns.Count</span><span class="admin-stat-card__label">Tổng chiến dịch</span></div></div>
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(59,130,246,0.1);"><i data-lucide="zap" style="color:#3B82F6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_campaigns.Count(c => c.Status == "Active")</span><span class="admin-stat-card__label">Đang hoạt động</span></div></div>
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(236,72,153,0.1);"><i data-lucide="ticket" style="color:#EC4899;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_campaigns.Sum(c => c.TotalVouchers)</span><span class="admin-stat-card__label">Tổng voucher</span></div></div>
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(255,92,0,0.1);"><i data-lucide="check-circle" style="color:#FF5C00;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_campaigns.Sum(c => c.IssuedVouchers)</span><span class="admin-stat-card__label">Đã phát</span></div></div>
    </div>
    <div class="admin-panel" style="margin-top:16px;">
        <div class="admin-panel__header"><h3 class="admin-panel__title">Danh sách chiến dịch</h3></div>
        <div class="admin-panel__body" style="padding:0;">
            <table class="admin-table" style="width:100%;"><thead><tr>
                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Tên</th>
                <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Loại</th>
                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Giá trị</th>
                <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Đã phát/Tổng</th>
                <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Bắt đầu</th>
                <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Kết thúc</th>
                <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);"></th>
            </tr></thead><tbody>
                @foreach (var c in _campaigns)
                {
                    <tr style="border-top:1px solid var(--admin-border-subtle);">
                        <td style="padding:12px 16px;font-weight:600;">@c.Name</td>
                        <td style="padding:12px 16px;text-align:center;"><span style="font-size:11px;padding:2px 8px;border-radius:4px;background:@(c.Description?.Contains("%") == true ? "rgba(139,92,246,0.15)" : "rgba(255,92,0,0.15)");color:@(c.Description?.Contains("%") == true ? "#8B5CF6" : "#FF5C00");font-weight:600;">@(c.Description?.Contains("%") == true ? "%" : "₫")</span></td>
                        <td style="padding:12px 16px;text-align:right;font-weight:600;color:var(--admin-orange-primary);">@(c.Description?.Contains("%") == true ? $"{c.FaceValue}%" : ShopHelpers.FormatVND(c.FaceValue))</td>
                        <td style="padding:12px 16px;text-align:center;font-size:13px;">@c.IssuedVouchers / @c.TotalVouchers</td>
                        <td style="padding:12px 16px;text-align:center;font-size:12px;color:var(--admin-text-tertiary);">@(c.StartDate?.ToString("dd/MM/yy") ?? "—")</td>
                        <td style="padding:12px 16px;text-align:center;font-size:12px;color:var(--admin-text-tertiary);">@(c.EndDate?.ToString("dd/MM/yy") ?? "—")</td>
                        <td style="padding:12px 16px;text-align:center;">
                            <div style="display:flex;gap:4px;justify-content:center;">
                                <button @onclick="@(() => EditCampaign(c))" style="background:rgba(59,130,246,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Sửa"><i data-lucide="pencil" style="color:#3B82F6;width:14px;height:14px;"></i></button>
                                <button @onclick="@(() => DeleteCampaignItem(c.Id))" style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Xóa"><i data-lucide="trash-2" style="color:#EF4444;width:14px;height:14px;"></i></button>
                            </div>
                        </td>
                    </tr>
                }
            </tbody></table>
        </div>
    </div>
} @* end else *@
} @* end campaigns sub-tab *@
@if (_promoSubTab == "vouchers")
{
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
        <h3 style="margin:0;font-size:16px;font-weight:700;">@_vouchers.Count mã voucher</h3>
        <button class="admin-btn-primary" style="font-size:12px;padding:6px 14px;" @onclick="LoadVouchers">
            <i data-lucide="refresh-cw" style="width:14px;height:14px;margin-right:4px;"></i>Làm mới
        </button>
    </div>
    @if (!_vouchers.Any())
    {
        <div style="text-align:center;padding:60px 20px;">
            <div style="width:80px;height:80px;border-radius:24px;background:rgba(236,72,153,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i data-lucide="ticket" style="width:36px;height:36px;color:#EC4899;"></i>
            </div>
            <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">Chưa có voucher</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">Tạo chiến dịch để tự động sinh mã voucher</p>
            <a href="/admin/shop/@ShopId/menu" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;">
                <i data-lucide="tag" style="width:16px;height:16px;"></i>
                Tạo chiến dịch
            </a>
        </div>
    }
    else
    {
        <div class="admin-panel">
            <div class="admin-panel__header"><h3 class="admin-panel__title">Danh sách mã voucher</h3></div>
            <div class="admin-panel__body" style="padding:0;">
                <table class="admin-table" style="width:100%;"><thead><tr>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Mã</th>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Chiến dịch</th>
                    <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Mệnh giá</th>
                    <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Còn lại</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Trạng thái</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Ngày tạo</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);"></th>
                </tr></thead><tbody>
                    @foreach (var v in _vouchers)
                    {
                        <tr style="border-top:1px solid var(--admin-border-subtle);">
                            <td style="padding:12px 16px;font-weight:700;font-family:monospace;letter-spacing:1px;color:var(--admin-orange-primary);">@v.Code</td>
                            <td style="padding:12px 16px;font-size:13px;">@(v.CampaignName ?? "—")</td>
                            <td style="padding:12px 16px;text-align:right;font-weight:600;">@ShopHelpers.FormatVND(v.FaceValue)</td>
                            <td style="padding:12px 16px;text-align:right;font-weight:600;color:@(v.RemainingValue < v.FaceValue ? "#F59E0B" : "var(--admin-text-primary)");">@ShopHelpers.FormatVND(v.RemainingValue)</td>
                            <td style="padding:12px 16px;text-align:center;"><span style="font-size:11px;padding:2px 8px;border-radius:4px;background:@(GetVoucherStatusColor(v.Status));font-weight:600;">@GetVoucherStatusLabel(v.Status)</span></td>
                            <td style="padding:12px 16px;text-align:center;font-size:12px;color:var(--admin-text-tertiary);">@(v.CreatedAt?.ToLocalTime().ToString("dd/MM/yy") ?? "—")</td>
                            <td style="padding:12px 16px;text-align:center;">
                                @if (v.Status?.ToLower() == "available")
                                {
                                    <button @onclick="@(() => RevokeVoucher(v.Id))" style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;padding:4px 10px;font-size:11px;color:#EF4444;font-weight:600;cursor:pointer;" title="Thu hồi">Thu hồi</button>
                                }
                            </td>
                        </tr>
                    }
                </tbody></table>
            </div>
        </div>
    }
}

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

    private List<PosDataService.CampaignInfo> _campaigns = new();
    private bool _showCampaignForm;
    private Guid? _editingCampaignId;
    private string _newCampaignName = "";
    private string _newCampaignDesc = "";
    private decimal _newCampaignValue;
    private int _newCampaignVouchers;
    private DateTime _newCampaignStart = DateTime.Today;
    private DateTime _newCampaignEnd = DateTime.Today.AddMonths(1);
    private string _newCampaignDiscountType = "fixed";
    private string? _campaignFormMessage;
    private bool _campaignFormSuccess;
    private string _promoSubTab = "campaigns";
    private List<PosDataService.AdminVoucherInfo> _vouchers = new();
    private Guid? _voucherCampaignFilter;

    protected override async Task OnInitializedAsync()
    {
        _campaigns = await DataService.GetCampaignsAsync();
    }

    private async Task SwitchPromoTab(string tab)
    {
        _promoSubTab = tab;
        if (tab == "vouchers" && !_vouchers.Any())
        {
            _vouchers = await DataService.GetAdminVouchersAsync(_voucherCampaignFilter);
            StateHasChanged();
        }
    }

    private async Task LoadVouchers()
    {
        _vouchers = await DataService.GetAdminVouchersAsync(_voucherCampaignFilter);
        StateHasChanged();
    }

    private async Task RevokeVoucher(Guid voucherId)
    {
        var ok = await DataService.RevokeVoucherAsync(voucherId);
        if (ok) _vouchers = await DataService.GetAdminVouchersAsync(_voucherCampaignFilter);
    }

    private static string GetVoucherStatusLabel(string? status) => (status ?? "").ToLower() switch
    {
        "available" => "Chưa nhận", "claimed" => "Đã nhận", "redeemed" => "Đã dùng",
        "revoked" => "Thu hồi", "expired" => "Hết hạn", _ => status ?? "—"
    };

    private static string GetVoucherStatusColor(string? status) => (status ?? "").ToLower() switch
    {
        "available" => "#F59E0B", "claimed" => "#3B82F6", "redeemed" => "#22C55E",
        "revoked" => "#EF4444", "expired" => "#888", _ => "#888"
    };

    private async Task SaveCampaign()
    {
        _campaignFormMessage = null;
        if (string.IsNullOrWhiteSpace(_newCampaignName) || _newCampaignValue <= 0 || _newCampaignVouchers <= 0)
        {
            _campaignFormMessage = "Vui lòng nhập đầy đủ tên, giá trị và số lượng voucher."; _campaignFormSuccess = false; return;
        }
        var desc = string.IsNullOrWhiteSpace(_newCampaignDesc) ? _newCampaignDiscountType : $"{_newCampaignDesc} [{_newCampaignDiscountType}]";
        if (_newCampaignDiscountType == "percentage") desc = $"Giảm {_newCampaignValue}% [{_newCampaignDiscountType}]";
        var req = new PosDataService.CreateCampaignRequest(_newCampaignName, desc, _newCampaignValue, _newCampaignVouchers, _newCampaignStart, _newCampaignEnd);
        bool ok;
        if (_editingCampaignId.HasValue)
            ok = await DataService.UpdateCampaignAsync(_editingCampaignId.Value, req);
        else
            ok = await DataService.CreateCampaignAsync(req);
        _campaignFormMessage = ok ? (_editingCampaignId.HasValue ? "Đã cập nhật chiến dịch!" : "Đã thêm chiến dịch!") : "Lỗi khi lưu chiến dịch.";
        _campaignFormSuccess = ok;
        if (ok) { _showCampaignForm = false; _editingCampaignId = null; _campaigns = await DataService.GetCampaignsAsync(); }
    }

    private void EditCampaign(PosDataService.CampaignInfo c)
    {
        _editingCampaignId = c.Id; _newCampaignName = c.Name; _newCampaignDesc = c.Description ?? "";
        _newCampaignValue = c.FaceValue; _newCampaignVouchers = c.TotalVouchers;
        _newCampaignStart = c.StartDate?.ToLocalTime().Date ?? DateTime.Today;
        _newCampaignEnd = c.EndDate?.ToLocalTime().Date ?? DateTime.Today.AddMonths(1);
        _showCampaignForm = true; _campaignFormMessage = null;
    }

    private async Task DeleteCampaignItem(Guid campaignId)
    {
        await DataService.DeleteCampaignAsync(campaignId);
        _campaigns = await DataService.GetCampaignsAsync();
    }
}
