@*
    EN: Full Table Map — Drag arrangement, sections (Indoor/Outdoor/VIP), merge/split tables.
        Connected to tables API with add/merge/split functionality.
    VI: So do ban day du — Keo tha sap xep, khu vuc (Trong nha/Ngoai troi/VIP), gop/tach ban.
        Ket noi API ban voi chuc nang them/gop/tach.
*@
@page "/pos/{ShopId:guid}/restaurant/table-map"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ TOOLBAR / THANH CONG CU ═══ *@
    <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 pos-category-tab--active" @onclick="@(() => NavigateTo("restaurant"))">
            <i data-lucide="arrow-left" style="width:14px;"></i> Quay lai
        </button>
        <span style="flex:1;font-size:16px;font-weight:700;">Quan ly so do ban</span>
        <div style="display:flex;gap:8px;">
            <button class="pos-category-tab" @onclick="MergeTables" disabled="@(_selectedIds.Count < 2)">
                <i data-lucide="merge" style="width:14px;"></i> Gop ban
            </button>
            <button class="pos-category-tab" @onclick="SplitTable" disabled="@(_selectedIds.Count != 1)">
                <i data-lucide="split" style="width:14px;"></i> Tach ban
            </button>
            <button class="pos-category-tab" @onclick="ToggleAddForm">
                <i data-lucide="plus" style="width:14px;"></i> Them ban
            </button>
        </div>
    </div>

    @* ═══ ADD TABLE FORM / FORM THEM BAN ═══ *@
    @if (_showAddForm)
    {
        <div style="padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);background:var(--pos-bg-elevated);">
            <div style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap;">
                <div style="display:flex;flex-direction:column;gap:4px;">
                    <label style="font-size:11px;color:var(--pos-text-tertiary);">So ban</label>
                    <input type="text" @bind="_newTableNumber" placeholder="VD: 15"
                           style="padding:8px 12px;border-radius:8px;border:1px solid var(--pos-border-default);background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:13px;width:100px;" />
                </div>
                <div style="display:flex;flex-direction:column;gap:4px;">
                    <label style="font-size:11px;color:var(--pos-text-tertiary);">Suc chua</label>
                    <input type="number" @bind="_newTableCapacity" min="1" max="20"
                           style="padding:8px 12px;border-radius:8px;border:1px solid var(--pos-border-default);background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:13px;width:80px;" />
                </div>
                <div style="display:flex;flex-direction:column;gap:4px;">
                    <label style="font-size:11px;color:var(--pos-text-tertiary);">Khu vuc</label>
                    <select @bind="_newTableZone"
                            style="padding:8px 12px;border-radius:8px;border:1px solid var(--pos-border-default);background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:13px;width:140px;">
                        <option value="Trong nha">Trong nha</option>
                        <option value="Ngoai troi">Ngoai troi</option>
                        <option value="VIP">VIP</option>
                        <option value="San thuong">San thuong</option>
                    </select>
                </div>
                <button style="padding:8px 16px;border-radius:8px;border:none;background:var(--pos-orange-primary);color:#fff;font-size:13px;font-weight:600;cursor:pointer;min-width:90px;"
                        disabled="@_isCreating" @onclick="CreateTable">
                    @(_isCreating ? "Dang tao..." : "Tao ban")
                </button>
                <button style="padding:8px 16px;border-radius:8px;border:1px solid var(--pos-border-default);background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:13px;cursor:pointer;"
                        @onclick="() => _showAddForm = false">Huy</button>
            </div>
            @if (!string.IsNullOrEmpty(_formMessage))
            {
                <div style="margin-top:8px;font-size:12px;color:@(_formIsError ? "var(--pos-danger)" : "var(--pos-success)");">@_formMessage</div>
            }
        </div>
    }

    @* ═══ SECTION TABS / TAB KHU VUC ═══ *@
    @if (_isLoading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Dang tai...
        </div>
    }
    else if (_loadError)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Khong the tai du lieu
        </div>
    }
    else
    {
    <div class="pos-category-tabs">
        @foreach (var s in _sections)
        {
            <button class="pos-category-tab @(s == _activeSection ? "pos-category-tab--active" : "")"
                    @onclick="() => _activeSection = s">@s</button>
        }
    </div>

    @* ═══ TABLE GRID / LUOI BAN ═══ *@
    <div style="flex:1;overflow-y:auto;padding:16px;">
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:14px;">
            @foreach (var t in FilteredTables)
            {
                <div @onclick="() => ToggleSelect(t)"
                     style="background:@StatusBg(t.Status);border-radius:var(--pos-radius);padding:16px;
                            text-align:center;cursor:grab;position:relative;
                            border:2px solid @(_selectedIds.Contains(t.Id) ? "var(--pos-orange-primary)" : "transparent");
                            transition:all .2s ease;">
                    @if (_selectedIds.Contains(t.Id))
                    {
                        <div style="position:absolute;top:6px;right:6px;width:18px;height:18px;border-radius:50%;
                                    background:var(--pos-orange-primary);display:flex;align-items:center;justify-content:center;">
                            <i data-lucide="check" style="width:12px;color:#fff;"></i>
                        </div>
                    }
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">@t.Section</div>
                    <div style="font-size:20px;font-weight:700;">@t.Name</div>
                    <div style="font-size:12px;color:rgba(255,255,255,.7);margin-top:4px;">@t.Seats cho · @t.Shape</div>
                    <div style="font-size:11px;font-weight:600;margin-top:6px;color:@StatusTextColor(t.Status);">
                        @StatusLabel(t.Status)
                    </div>
                </div>
            }
        </div>
    </div>

    }

    @* ═══ MERGE CONFIRMATION / XAC NHAN GOP ═══ *@
    @if (_showMergeConfirm)
    {
        <div style="padding:12px 16px;border-top:1px solid var(--pos-border-subtle);background:rgba(255,92,0,.08);">
            <div style="display:flex;align-items:center;gap:12px;">
                <span style="font-size:13px;font-weight:600;color:var(--pos-orange-primary);">
                    Gop @_selectedIds.Count ban: @string.Join(" + ", _tables.Where(t => _selectedIds.Contains(t.Id)).Select(t => t.Name))
                </span>
                <span style="flex:1;"></span>
                <button style="padding:8px 16px;border-radius:8px;border:none;background:var(--pos-orange-primary);color:#fff;font-size:13px;font-weight:600;cursor:pointer;"
                        @onclick="ConfirmMerge">Xac nhan gop</button>
                <button style="padding:8px 16px;border-radius:8px;border:1px solid var(--pos-border-default);background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:13px;cursor:pointer;"
                        @onclick="CancelMerge">Huy</button>
            </div>
        </div>
    }

    @* ═══ FOOTER STATS / THONG KE ═══ *@
    <div style="padding:10px 16px;border-top:1px solid var(--pos-border-subtle);display:flex;gap:20px;font-size:12px;color:var(--pos-text-secondary);">
        <span>Tong: <b>@_tables.Count</b> ban</span>
        <span style="color:var(--pos-success);">Trong: @_tables.Count(t => t.Status == "available")</span>
        <span style="color:var(--pos-orange-primary);">Dang PV: @_tables.Count(t => t.Status == "occupied")</span>
        <span style="color:var(--pos-info);">Da dat: @_tables.Count(t => t.Status == "reserved")</span>
        @if (_selectedIds.Count > 0)
        {
            <span style="margin-left:auto;color:var(--pos-orange-primary);font-weight:600;">Da chon: @_selectedIds.Count ban</span>
        }
    </div>
</div>

@code {

    // EN: Loading state / VI: Trang thai tai
    private bool _isLoading = true;
    private bool _loadError;

    private string _activeSection = "Tat ca";
    private string[] _sections = { "Tat ca" };
    private readonly HashSet<string> _selectedIds = new();

    // EN: Add table form state / VI: Trang thai form them ban
    private bool _showAddForm;
    private string _newTableNumber = "";
    private int _newTableCapacity = 4;
    private string _newTableZone = "Trong nha";
    private bool _isCreating;
    private string? _formMessage;
    private bool _formIsError;

    // EN: Merge state / VI: Trang thai gop ban
    private bool _showMergeConfirm;

    // EN: Table data from API / VI: Du lieu ban tu API
    private List<MapTable> _tables = new();

    private IEnumerable<MapTable> FilteredTables =>
        _activeSection == "Tat ca" ? _tables : _tables.Where(t => t.Section == _activeSection);

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

    private async Task LoadTablesAsync()
    {
        _isLoading = true;
        _loadError = false;

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

            _tables = apiTables.Select(t => new MapTable(
                t.Id.ToString(),
                $"Ban {t.TableNumber}",
                t.Capacity,
                t.Status ?? "available",
                t.Zone ?? "Trong nha",
                t.Capacity <= 2 ? "Tron" : t.Capacity <= 6 ? "Vuong" : "Chu nhat"
            )).ToList();

            var zones = _tables.Select(t => t.Section).Distinct().ToList();
            _sections = new[] { "Tat ca" }.Concat(zones).ToArray();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void ToggleSelect(MapTable t)
    {
        if (!_selectedIds.Add(t.Id)) _selectedIds.Remove(t.Id);
        // EN: Hide merge confirm if selection changes / VI: An xac nhan gop khi chon thay doi
        _showMergeConfirm = false;
    }

    private void ToggleAddForm()
    {
        _showAddForm = !_showAddForm;
        _formMessage = null;
        _newTableNumber = "";
        _newTableCapacity = 4;
        _newTableZone = "Trong nha";
    }

    private async Task CreateTable()
    {
        if (string.IsNullOrWhiteSpace(_newTableNumber))
        {
            _formMessage = "Vui long nhap so ban";
            _formIsError = true;
            return;
        }

        _isCreating = true;
        _formMessage = null;

        try
        {
            var req = new WebClientTpos.Client.Services.PosDataService.CreateTableRequest(
                ShopId,
                _newTableNumber.Trim(),
                _newTableCapacity,
                _newTableZone
            );

            var success = await DataService.CreateTableAsync(req);
            if (success)
            {
                _formMessage = $"Da tao ban {_newTableNumber} thanh cong!";
                _formIsError = false;
                _newTableNumber = "";
                _newTableCapacity = 4;
                // EN: Reload tables from API / VI: Tai lai ban tu API
                await LoadTablesAsync();
            }
            else
            {
                _formMessage = "Khong the tao ban. Vui long thu lai.";
                _formIsError = true;
            }
        }
        catch
        {
            _formMessage = "Loi khi tao ban. Vui long thu lai.";
            _formIsError = true;
        }
        finally
        {
            _isCreating = false;
        }
    }

    private void MergeTables()
    {
        if (_selectedIds.Count < 2) return;
        _showMergeConfirm = true;
    }

    private void ConfirmMerge()
    {
        // EN: Visual merge — combine selected table names into first table
        // VI: Gop hinh — ghep ten cac ban duoc chon vao ban dau tien
        var selectedTables = _tables.Where(t => _selectedIds.Contains(t.Id)).ToList();
        if (selectedTables.Count < 2) return;

        var mergedName = string.Join("+", selectedTables.Select(t => t.Name.Replace("Ban ", "")));
        var totalSeats = selectedTables.Sum(t => t.Seats);
        var primary = selectedTables.First();

        // EN: Update primary table to show merged name
        // VI: Cap nhat ban chinh de hien ten da gop
        var primaryIdx = _tables.FindIndex(t => t.Id == primary.Id);
        if (primaryIdx >= 0)
        {
            _tables[primaryIdx] = primary with { Name = $"Ban {mergedName}", Seats = totalSeats };
        }

        // EN: Remove other tables from visual list (they remain in DB)
        // VI: Xoa cac ban khac khoi danh sach hien (chung van ton tai trong DB)
        foreach (var t in selectedTables.Skip(1))
        {
            _tables.RemoveAll(x => x.Id == t.Id);
        }

        _selectedIds.Clear();
        _showMergeConfirm = false;
    }

    private void CancelMerge()
    {
        _showMergeConfirm = false;
    }

    private void SplitTable()
    {
        if (_selectedIds.Count != 1) return;
        // EN: Navigate to table-merge-split page / VI: Chuyen den trang gop/tach ban
        NavigateTo("restaurant/table-merge-split");
    }

    private static string StatusBg(string s) => s switch
    {
        "available" => "rgba(34,197,94,.12)", "occupied" => "rgba(255,92,0,.15)",
        "reserved" => "rgba(59,130,246,.15)", _ => "var(--pos-bg-interactive)"
    };

    private static string StatusTextColor(string s) => s switch
    {
        "available" => "var(--pos-success)", "occupied" => "var(--pos-orange-primary)",
        "reserved" => "var(--pos-info)", _ => "var(--pos-text-tertiary)"
    };

    private static string StatusLabel(string s) => s switch
    {
        "available" => "Trong", "occupied" => "Dang phuc vu", "reserved" => "Da dat", _ => s
    };

    private record MapTable(string Id, string Name, int Seats, string Status, string Section, string Shape);
}
