@*
    EN: Table Merge/Split — Merge multiple tables or split a table with active order.
    VI: Ghép/Tách bàn — Ghép nhiều bàn lại hoặc tách bàn có đơn đang hoạt động.
*@
@page "/pos/{ShopId:guid}/restaurant/table-merge-split"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ HEADER / TIÊU ĐỀ ═══ *@
    <div style="padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);display:flex;align-items:center;gap:12px;">
        <button class="pos-category-tab" @onclick="@(() => NavigateTo("restaurant"))">
            <i data-lucide="arrow-left" style="width:14px;"></i> Quay lại
        </button>
        <span style="font-size:16px;font-weight:700;">
            <i data-lucide="combine" style="width:18px;height:18px;display:inline;"></i> Ghép / Tách bàn
        </span>
    </div>

    @* ═══ MODE TABS / TAB CHẾ ĐỘ ═══ *@
    <div class="pos-category-tabs">
        <button class="pos-category-tab @(_mode == "merge" ? "pos-category-tab--active" : "")"
                @onclick="@(() => SwitchMode("merge"))">
            <i data-lucide="merge" style="width:14px;"></i> Ghép bàn
        </button>
        <button class="pos-category-tab @(_mode == "split" ? "pos-category-tab--active" : "")"
                @onclick="@(() => SwitchMode("split"))">
            <i data-lucide="split" style="width:14px;"></i> Tách bàn
        </button>
    </div>

    <div style="flex:1;overflow-y:auto;padding:16px;">
        @if (_isLoading)
        {
            <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
                Đang tải...
            </div>
        }
        else if (_loadError)
        {
            <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
                Không thể tải dữ liệu
            </div>
        }
        else if (_mode == "merge")
        {
            @* ═══ MERGE MODE / CHẾ ĐỘ GHÉP ═══ *@
            <div style="margin-bottom:20px;">
                <div style="font-size:14px;font-weight:600;margin-bottom:12px;color:var(--pos-text-secondary);">
                    Chọn bàn để ghép (2+ bàn)
                </div>
                <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:10px;">
                    @foreach (var table in _mergeTables)
                    {
                        var isSelected = _mergeSelected.Contains(table.Id);
                        <div style="padding:16px;border-radius:var(--pos-radius);text-align:center;cursor:pointer;
                                    background:@(isSelected ? "rgba(255,92,0,.15)" : "var(--pos-bg-elevated)");
                                    border:2px solid @(isSelected ? "var(--pos-orange-primary)" : "transparent");
                                    transition:all .2s ease;"
                             @onclick="() => ToggleMerge(table.Id)">
                            @if (isSelected)
                            {
                                <div style="width:20px;height:20px;border-radius:50%;background:var(--pos-orange-primary);
                                            display:flex;align-items:center;justify-content:center;margin:0 auto 8px;">
                                    <i data-lucide="check" style="width:12px;height:12px;color:#fff;"></i>
                                </div>
                            }
                            <div style="font-size:18px;font-weight:700;">@table.Name</div>
                            <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:4px;">@table.Seats chỗ</div>
                            <div style="font-size:11px;font-weight:600;margin-top:4px;color:@(table.Status == "available" ? "var(--pos-success)" : "var(--pos-text-tertiary)");">
                                @(table.Status == "available" ? "Trống" : "Đang dùng")
                            </div>
                        </div>
                    }
                </div>
            </div>

            @* EN: Merge preview / VI: Xem trước ghép *@
            @if (_mergeSelected.Count >= 2)
            {
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;
                            border:1px solid var(--pos-orange-primary);">
                    <div style="font-size:14px;font-weight:600;margin-bottom:10px;color:var(--pos-orange-primary);">
                        <i data-lucide="eye" style="width:14px;height:14px;display:inline;"></i> Xem trước
                    </div>
                    <div style="display:flex;align-items:center;gap:12px;">
                        @foreach (var id in _mergeSelected)
                        {
                            var t = _mergeTables.First(x => x.Id == id);
                            <span style="font-size:14px;font-weight:600;">@t.Name</span>
                            @if (id != _mergeSelected.Last())
                            {
                                <span style="color:var(--pos-text-tertiary);">+</span>
                            }
                        }
                        <span style="color:var(--pos-text-tertiary);">→</span>
                        <span style="font-size:16px;font-weight:700;color:var(--pos-orange-primary);">
                            @MergedName (@MergedCapacity chỗ)
                        </span>
                    </div>
                </div>
            }
        }
        else
        {
            @* ═══ SPLIT MODE / CHẾ ĐỘ TÁCH ═══ *@
            <div style="margin-bottom:20px;">
                <div style="font-size:14px;font-weight:600;margin-bottom:12px;color:var(--pos-text-secondary);">
                    Chọn bàn để tách
                </div>
                <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:10px;">
                    @foreach (var table in _splitTables)
                    {
                        var isSelected = _splitSelected == table.Id;
                        <div style="padding:16px;border-radius:var(--pos-radius);text-align:center;cursor:pointer;
                                    background:@(isSelected ? "rgba(59,130,246,.15)" : "var(--pos-bg-elevated)");
                                    border:2px solid @(isSelected ? "var(--pos-info)" : "transparent");"
                             @onclick="() => _splitSelected = table.Id">
                            <div style="font-size:18px;font-weight:700;">@table.Name</div>
                            <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:4px;">@table.Seats chỗ</div>
                            <div style="font-size:11px;color:var(--pos-orange-primary);font-weight:600;margin-top:4px;">
                                @table.OrderCount món
                            </div>
                        </div>
                    }
                </div>
            </div>

            @* EN: Split preview / VI: Xem trước tách *@
            @if (_splitSelected is not null)
            {
                var selected = _splitTables.First(t => t.Id == _splitSelected);
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;
                            border:1px solid var(--pos-info);">
                    <div style="font-size:14px;font-weight:600;margin-bottom:10px;color:var(--pos-info);">
                        <i data-lucide="eye" style="width:14px;height:14px;display:inline;"></i> Xem trước tách
                    </div>
                    <div style="display:flex;align-items:center;gap:12px;">
                        <span style="font-size:14px;font-weight:600;">@selected.Name (@selected.Seats chỗ)</span>
                        <span style="color:var(--pos-text-tertiary);">→</span>
                        <span style="font-size:14px;font-weight:700;color:var(--pos-info);">
                            @(selected.Name)A (@(selected.Seats / 2) chỗ)
                        </span>
                        <span style="color:var(--pos-text-tertiary);">+</span>
                        <span style="font-size:14px;font-weight:700;color:var(--pos-info);">
                            @(selected.Name)B (@(selected.Seats - selected.Seats / 2) chỗ)
                        </span>
                    </div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:8px;">
                        @selected.OrderCount món sẽ được chia giữa 2 bàn
                    </div>
                </div>
            }
        }
    </div>

    @* ═══ FOOTER ACTIONS / NÚT HÀNH ĐỘNG ═══ *@
    <div style="padding:12px 16px;border-top:1px solid var(--pos-border-subtle);display:flex;gap:8px;flex-shrink:0;">
        <button style="flex:1;padding:12px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);
                       border:1px solid var(--pos-border-default);color:var(--pos-text-primary);cursor:pointer;font-size:13px;"
                @onclick="@(() => NavigateTo("restaurant"))">
            Hủy
        </button>
        <button class="pos-btn-checkout" style="flex:1;" @onclick="ConfirmAction"
                disabled="@(!CanConfirm)">
            <i data-lucide="check" style="width:14px;height:14px;display:inline;"></i>
            @(_mode == "merge" ? "Xác nhận ghép" : "Xác nhận tách")
        </button>
    </div>
</div>

@code {

    // EN: Loading state / VI: Trạng thái tải
    private bool _isLoading = true;
    private bool _loadError;

    private string _mode = "merge";
    private readonly HashSet<string> _mergeSelected = new();
    private string? _splitSelected;

    // EN: Tables from API / VI: Bàn từ API
    private List<MergeTable> _mergeTables = new();
    private List<SplitTable> _splitTables = new();

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

        try
        {
            var apiTables = await DataService.GetTablesAsync(ShopId);

            _mergeTables = apiTables
                .Select(t => new MergeTable(
                    t.Id.ToString(),
                    $"Bàn {t.TableNumber}",
                    t.Capacity,
                    t.Status ?? "available"
                )).ToList();

            _splitTables = apiTables
                .Where(t => (t.Status ?? "available") == "occupied")
                .Select(t => new SplitTable(
                    t.Id.ToString(),
                    $"Bàn {t.TableNumber}",
                    t.Capacity,
                    0
                )).ToList();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void SwitchMode(string mode)
    {
        _mode = mode;
        _mergeSelected.Clear();
        _splitSelected = null;
    }

    private void ToggleMerge(string id)
    {
        if (!_mergeSelected.Remove(id))
            _mergeSelected.Add(id);
    }

    private bool CanConfirm => _mode == "merge" ? _mergeSelected.Count >= 2 : _splitSelected is not null;

    private string MergedName => string.Join("-", _mergeSelected.Select(id =>
        _mergeTables.First(t => t.Id == id).Name.Replace("Bàn ", "")));

    private int MergedCapacity => _mergeSelected.Sum(id =>
        _mergeTables.First(t => t.Id == id).Seats);

    private void ConfirmAction() => NavigateTo("restaurant");

    private record MergeTable(string Id, string Name, int Seats, string Status);
    private record SplitTable(string Id, string Name, int Seats, int OrderCount);
}
