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

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
    <div style="display:flex;gap:8px;">
        <div class="admin-stat-card" style="margin:0;"><div class="admin-stat-card__icon" style="background:rgba(236,72,153,0.1);"><i data-lucide="door-open" style="color:#EC4899;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_resources.Count</span><span class="admin-stat-card__label">Tổng</span></div></div>
        <div class="admin-stat-card" style="margin:0;"><div class="admin-stat-card__icon" style="background:rgba(34,197,94,0.1);"><i data-lucide="check-circle" style="color:#22C55E;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_resources.Count(r => r.IsActive)</span><span class="admin-stat-card__label">Hoạt động</span></div></div>
    </div>
    <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick='() => { _editingResourceId = null; _newResourceName = ""; _newResourceType = "Room"; _newResourceCapacity = 1; _resourceFormMessage = null; _showResourceForm = !_showResourceForm; }'>
        <i data-lucide="plus-circle" style="width:16px;height:16px;"></i>Thêm tài nguyên
    </button>
</div>
@if (_showResourceForm)
{
    <div class="admin-panel" style="margin-bottom:16px;border:1px solid rgba(236,72,153,0.3);">
        <div class="admin-panel__header"><h3 class="admin-panel__title">@(_editingResourceId.HasValue ? "Chỉnh sửa" : "Thêm tài nguyên")</h3></div>
        <div class="admin-panel__body">
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;">
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Tên *</label><input type="text" @bind="_newResourceName" placeholder="VD: Phòng 01" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Loại</label>
                    <select @bind="_newResourceType" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                        <option value="Room">Phòng</option>
                        <option value="Bed">Giường</option>
                        <option value="Chair">Ghế</option>
                        <option value="Equipment">Thiết bị</option>
                    </select>
                </div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Sức chứa</label><input type="number" @bind="_newResourceCapacity" min="1" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
            </div>
            <div style="display:flex;gap:8px;margin-top:12px;">
                <button class="admin-btn-primary" @onclick="@(_editingResourceId.HasValue ? SaveResource : AddResource)" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>@(_editingResourceId.HasValue ? "Cập nhật" : "Lưu")</button>
                <button @onclick='() => _showResourceForm = false' style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;"><i data-lucide="x" style="width:14px;height:14px;"></i>Hủy</button>
            </div>
            @if (_resourceFormMessage != null) { <div style="margin-top:8px;font-size:13px;color:@(_resourceFormSuccess ? "#22C55E" : "#EF4444");">@_resourceFormMessage</div> }
        </div>
    </div>
}
@if (!_resources.Any())
{
    @RenderEmpty("door-open", "#EC4899", "Chưa có tài nguyên", "Thêm phòng, giường, thiết bị cho cửa hàng")
}
else
{
    <div class="admin-panel">
        <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);">Sức chứa</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;width:80px;"></th>
            </tr></thead><tbody>
                @foreach (var r in _resources)
                {
                    <tr style="border-top:1px solid var(--admin-border-subtle);">
                        <td style="padding:12px 16px;font-weight:600;">@r.Name</td>
                        <td style="padding:12px 16px;text-align:center;font-size:12px;color:var(--admin-text-tertiary);">@(r.ResourceType ?? "—")</td>
                        <td style="padding:12px 16px;text-align:right;font-weight:600;color:var(--admin-orange-primary);">@r.Capacity</td>
                        <td style="padding:12px 16px;text-align:center;"><span class="admin-status-badge @(r.IsActive ? "admin-status-badge--online" : "admin-status-badge--offline")" style="font-size:11px;padding:2px 10px;"><span class="admin-status-badge__dot" style="width:5px;height:5px;"></span>@(r.IsActive ? "Active" : "Inactive")</span></td>
                        <td style="padding:12px 16px;text-align:center;">
                            <div style="display:flex;gap:4px;justify-content:center;">
                                <button @onclick='() => EditResource(r)' 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;"><i data-lucide="pencil" style="color:#3B82F6;width:14px;height:14px;"></i></button>
                                <button @onclick='() => DeleteResourceItem(r.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;"><i data-lucide="trash-2" style="color:#EF4444;width:14px;height:14px;"></i></button>
                            </div>
                        </td>
                    </tr>
                }
            </tbody></table>
        </div>
    </div>
}

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

    // Resources CRUD state
    private List<PosDataService.ResourceInfo> _resources = new();
    private bool _showResourceForm;
    private Guid? _editingResourceId;
    private string _newResourceName = "";
    private string _newResourceType = "Room";
    private int _newResourceCapacity = 1;
    private string? _resourceFormMessage;
    private bool _resourceFormSuccess;
    private string? _errorMessage;

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
            _resources = await DataService.GetResourcesAsync(ShopId);
    }

    // ═══ RESOURCE CRUD ═══
    private void EditResource(PosDataService.ResourceInfo r)
    {
        _editingResourceId = r.Id;
        _newResourceName = r.Name;
        _newResourceType = r.ResourceType ?? "Room";
        _newResourceCapacity = r.Capacity;
        _resourceFormMessage = null;
        _showResourceForm = true;
    }

    private async Task AddResource()
    {
        _resourceFormMessage = null;
        if (string.IsNullOrWhiteSpace(_newResourceName) || ShopId == Guid.Empty)
        {
            _resourceFormMessage = "Vui lòng nhập tên tài nguyên."; _resourceFormSuccess = false; return;
        }
        try
        {
            await DataService.CreateResourceAsync(new PosDataService.CreateResourceRequest(ShopId, _newResourceName, _newResourceType, _newResourceCapacity));
            _resourceFormMessage = $"Đã thêm '{_newResourceName}' thành công!"; _resourceFormSuccess = true;
            _newResourceName = ""; _newResourceType = "Room"; _newResourceCapacity = 1;
            _resources = await DataService.GetResourcesAsync(ShopId);
        }
        catch (Exception ex) { _resourceFormMessage = $"Lỗi: {ex.Message}"; _resourceFormSuccess = false; }
    }

    private async Task SaveResource()
    {
        _resourceFormMessage = null;
        if (string.IsNullOrWhiteSpace(_newResourceName) || ShopId == Guid.Empty || !_editingResourceId.HasValue)
        {
            _resourceFormMessage = "Vui lòng nhập tên tài nguyên."; _resourceFormSuccess = false; return;
        }
        try
        {
            await DataService.UpdateResourceAsync(_editingResourceId.Value, new PosDataService.CreateResourceRequest(ShopId, _newResourceName, _newResourceType, _newResourceCapacity));
            _resourceFormMessage = $"Đã cập nhật '{_newResourceName}' thành công!"; _resourceFormSuccess = true;
            _editingResourceId = null;
            _resources = await DataService.GetResourcesAsync(ShopId);
        }
        catch (Exception ex) { _resourceFormMessage = $"Lỗi: {ex.Message}"; _resourceFormSuccess = false; }
    }

    private async Task DeleteResourceItem(Guid id)
    {
        try
        {
            await DataService.DeleteResourceAsync(id);
            if (ShopId != Guid.Empty) _resources = await DataService.GetResourcesAsync(ShopId);
        }
        catch (Exception ex) { _errorMessage = $"Không thể xóa tài nguyên: {ex.Message}"; }
    }

    private RenderFragment RenderEmpty(string icon, string color, string title, string desc, string? ctaIcon = null, string? ctaLabel = null, string? ctaHref = null) => __builder =>
    {
        <div style="text-align:center;padding:60px 20px;">
            <div style="width:80px;height:80px;border-radius:24px;background:@($"rgba({HexToRgb(color)},0.1)");display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i data-lucide="@icon" style="width:36px;height:36px;color:@color;"></i>
            </div>
            <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">@title</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">@desc</p>
            @if (ctaIcon != null && ctaLabel != null)
            {
                <a href="@(ctaHref ?? $"/admin/shop/{ShopId}/menu")" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;">
                    <i data-lucide="@ctaIcon" style="width:16px;height:16px;"></i>
                    @ctaLabel
                </a>
            }
        </div>
    };

    private static string HexToRgb(string hex)
    {
        hex = hex.TrimStart('#');
        if (hex.Length != 6) return "0,0,0";
        return $"{Convert.ToInt32(hex[..2], 16)},{Convert.ToInt32(hex[2..4], 16)},{Convert.ToInt32(hex[4..], 16)}";
    }
}
