@*
    EN: Reservation Management — Date picker, time slots, guest info, table assignment, status.
    VI: Quản lý đặt bàn — Chọn ngày, khung giờ, thông tin khách, gán bàn, trạng thái.
*@
@using WebClientTpos.Client.Services
@page "/pos/{ShopId:guid}/restaurant/reservation"
@layout PosLayout
@inherits PosBase
@inject 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;">Đặt bàn trước</span>
        <span style="flex:1;"></span>
        <button class="pos-category-tab pos-category-tab--active" @onclick="() => OpenNewForm()">
            <i data-lucide="plus" style="width:14px;"></i> Đặt bàn mới
        </button>
    </div>

    @* ═══ DATE & FILTERS / NGÀY & BỘ LỌC ═══ *@
    <div style="padding:10px 16px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--pos-border-subtle);">
        <div style="display:flex;align-items:center;gap:8px;">
            <i data-lucide="calendar" style="width:16px;color:var(--pos-text-tertiary);"></i>
            <input type="date" value="@_selectedDate.ToString("yyyy-MM-dd")" @onchange="OnDateChanged"
                   style="background:var(--pos-bg-interactive);border:1px solid var(--pos-border-default);border-radius:8px;
                          padding:6px 10px;color:var(--pos-text-primary);font-family:var(--pos-font);font-size:13px;" />
        </div>
        <div class="pos-category-tabs" style="padding:0;flex:1;">
            @foreach (var s in _statusFilters)
            {
                <button class="pos-category-tab @(s == _activeFilter ? "pos-category-tab--active" : "")"
                        style="font-size:12px;padding:6px 12px;" @onclick="() => _activeFilter = s">@s</button>
            }
        </div>
    </div>

    @if (_loading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else if (!_reservations.Any())
    {
        <div style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;color:var(--pos-text-tertiary);">
            <i data-lucide="calendar-off" style="width:40px;height:40px;opacity:.4;"></i>
            <span style="font-size:14px;">Chưa có đặt bàn nào cho ngày này</span>
        </div>
    }
    else
    {
        @* ═══ RESERVATION LIST / DANH SÁCH ĐẶT BÀN ═══ *@
        <div style="flex:1;overflow-y:auto;padding:12px 16px;display:flex;flex-direction:column;gap:8px;">
            @foreach (var r in FilteredReservations)
            {
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:14px 16px;
                            display:flex;align-items:center;gap:14px;border-left:4px solid @StatusColor(r.Status);">
                    @* EN: Time / VI: Giờ *@
                    <div style="text-align:center;min-width:50px;">
                        <div style="font-size:16px;font-weight:700;">@r.ReservationTime.ToString("HH:mm")</div>
                    </div>
                    @* EN: Guest info / VI: Thông tin khách *@
                    <div style="flex:1;">
                        <div style="font-size:14px;font-weight:600;">@r.GuestName</div>
                        <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:2px;">
                            @r.PartySize người @if(!string.IsNullOrEmpty(r.Phone)){<text> · @r.Phone</text>}
                        </div>
                        @if (!string.IsNullOrEmpty(r.Note))
                        {
                            <div style="font-size:11px;color:var(--pos-warning);margin-top:2px;font-style:italic;">@r.Note</div>
                        }
                    </div>
                    @* EN: Table assignment / VI: Bàn đã gán *@
                    <div style="text-align:center;padding:6px 12px;border-radius:8px;background:var(--pos-bg-interactive);font-size:13px;font-weight:600;">
                        @(r.TableId.HasValue ? TableName(r.TableId.Value) : "—")
                    </div>
                    @* EN: Status actions / VI: Hành động trạng thái *@
                    <div style="display:flex;align-items:center;gap:6px;">
                        <span style="font-size:11px;padding:4px 10px;border-radius:6px;font-weight:600;
                                    background:@StatusBg(r.Status);color:@StatusColor(r.Status);">
                            @StatusLabel(r.Status)
                        </span>
                        @if (r.Status == "pending")
                        {
                            <button class="pos-category-tab" style="font-size:11px;padding:4px 8px;"
                                    @onclick='() => UpdateStatus(r.Id, "confirmed")'>
                                <i data-lucide="check" style="width:12px;"></i> XN
                            </button>
                            <button class="pos-category-tab" style="font-size:11px;padding:4px 8px;color:var(--pos-danger);"
                                    @onclick='() => UpdateStatus(r.Id, "cancelled")'>
                                <i data-lucide="x" style="width:12px;"></i>
                            </button>
                        }
                        else if (r.Status == "confirmed")
                        {
                            <button class="pos-category-tab" style="font-size:11px;padding:4px 8px;"
                                    @onclick='() => UpdateStatus(r.Id, "seated")'>
                                <i data-lucide="armchair" style="width:12px;"></i> Đã đến
                            </button>
                        }
                    </div>
                </div>
            }
        </div>
    }

    @* ═══ SUMMARY / TÓM TẮT ═══ *@
    <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>Tổng: <b>@_reservations.Count</b> đặt bàn</span>
        <span style="color:var(--pos-info);">Chờ xác nhận: @_reservations.Count(r => r.Status == "pending")</span>
        <span style="color:var(--pos-success);">Đã xác nhận: @_reservations.Count(r => r.Status == "confirmed")</span>
        <span style="color:var(--pos-orange-primary);">Đã đến: @_reservations.Count(r => r.Status == "seated")</span>
    </div>
</div>

@* ═══ NEW RESERVATION FORM / FORM ĐẶT BÀN MỚI ═══ *@
@if (_showForm)
{
    <div style="position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:999;display:flex;align-items:center;justify-content:center;"
         @onclick="() => _showForm = false">
        <div style="background:var(--pos-bg-elevated);border-radius:12px;padding:24px;width:420px;max-height:90vh;overflow-y:auto;"
             @onclick:stopPropagation="true">
            <div style="font-size:16px;font-weight:700;margin-bottom:16px;">Đặt bàn mới</div>

            @if (!string.IsNullOrEmpty(_formMessage))
            {
                <div style="padding:8px 12px;border-radius:8px;margin-bottom:12px;font-size:13px;
                            background:@(_formSuccess ? "rgba(34,197,94,.15)" : "rgba(239,68,68,.15)");
                            color:@(_formSuccess ? "var(--pos-success)" : "var(--pos-danger)");">@_formMessage</div>
            }

            <div style="display:flex;flex-direction:column;gap:12px;">
                <div>
                    <label style="font-size:12px;color:var(--pos-text-secondary);margin-bottom:4px;display:block;">Tên khách *</label>
                    <input @bind="_fGuestName" placeholder="Nguyễn Văn A"
                           style="width:100%;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;" />
                </div>
                <div style="display:flex;gap:12px;">
                    <div style="flex:1;">
                        <label style="font-size:12px;color:var(--pos-text-secondary);margin-bottom:4px;display:block;">Số khách *</label>
                        <input type="number" @bind="_fPartySize" min="1"
                               style="width:100%;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;" />
                    </div>
                    <div style="flex:1;">
                        <label style="font-size:12px;color:var(--pos-text-secondary);margin-bottom:4px;display:block;">SĐT</label>
                        <input @bind="_fPhone" placeholder="0912345678"
                               style="width:100%;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;" />
                    </div>
                </div>
                <div style="display:flex;gap:12px;">
                    <div style="flex:1;">
                        <label style="font-size:12px;color:var(--pos-text-secondary);margin-bottom:4px;display:block;">Ngày *</label>
                        <input type="date" @bind="_fDate"
                               style="width:100%;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;" />
                    </div>
                    <div style="flex:1;">
                        <label style="font-size:12px;color:var(--pos-text-secondary);margin-bottom:4px;display:block;">Giờ *</label>
                        <input type="time" value="@_fTime" @onchange="OnTimeChanged"
                               style="width:100%;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;" />
                    </div>
                </div>
                <div>
                    <label style="font-size:12px;color:var(--pos-text-secondary);margin-bottom:4px;display:block;">Bàn</label>
                    <select @bind="_fTableId"
                            style="width:100%;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;">
                        <option value="">— Chưa chọn —</option>
                        @foreach (var t in _tables)
                        {
                            <option value="@t.Id">@t.TableNumber (sức chứa @t.Capacity)</option>
                        }
                    </select>
                </div>
                <div>
                    <label style="font-size:12px;color:var(--pos-text-secondary);margin-bottom:4px;display:block;">Ghi chú</label>
                    <textarea @bind="_fNote" rows="2" placeholder="Yêu cầu đặc biệt..."
                              style="width:100%;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;resize:vertical;"></textarea>
                </div>
            </div>

            <div style="display:flex;gap:8px;margin-top:16px;justify-content:flex-end;">
                <button class="pos-category-tab" @onclick="() => _showForm = false">Hủy</button>
                <button class="pos-category-tab pos-category-tab--active" @onclick="SubmitReservation" disabled="@_submitting">
                    @(_submitting ? "Đang lưu..." : "Xác nhận đặt bàn")
                </button>
            </div>
        </div>
    </div>
}

@code {
    private DateTime _selectedDate = DateTime.Today;
    private string _activeFilter = "Tất cả";
    private bool _showForm;
    private bool _loading = true;
    private bool _submitting;
    private string? _formMessage;
    private bool _formSuccess;
    private readonly string[] _statusFilters = { "Tất cả", "Chờ xác nhận", "Đã xác nhận", "Đã đến", "Hủy" };

    private List<PosDataService.ReservationInfo> _reservations = new();
    private List<PosDataService.TableInfo> _tables = new();

    // Form fields
    private string _fGuestName = "";
    private int _fPartySize = 2;
    private string _fPhone = "";
    private DateTime _fDate = DateTime.Today;
    private string _fTime = "18:00";
    private string _fTableId = "";
    private string _fNote = "";

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await Task.WhenAll(LoadReservations(), LoadTables());
        _loading = false;
    }

    private async Task LoadReservations()
    {
        _reservations = await DataService.GetReservationsAsync(ShopId, _selectedDate.ToString("yyyy-MM-dd"));
    }

    private async Task LoadTables()
    {
        _tables = await DataService.GetTablesAsync(ShopId);
    }

    private void OnTimeChanged(ChangeEventArgs e)
    {
        _fTime = e.Value?.ToString() ?? "18:00";
    }

    private async Task OnDateChanged(ChangeEventArgs e)
    {
        if (DateTime.TryParse(e.Value?.ToString(), out var d))
        {
            _selectedDate = d;
            _loading = true;
            await LoadReservations();
            _loading = false;
        }
    }

    private IEnumerable<PosDataService.ReservationInfo> FilteredReservations => _activeFilter switch
    {
        "Chờ xác nhận" => _reservations.Where(r => r.Status == "pending"),
        "Đã xác nhận" => _reservations.Where(r => r.Status == "confirmed"),
        "Đã đến" => _reservations.Where(r => r.Status == "seated"),
        "Hủy" => _reservations.Where(r => r.Status is "cancelled" or "no_show"),
        _ => _reservations
    };

    private void OpenNewForm()
    {
        _fGuestName = "";
        _fPartySize = 2;
        _fPhone = "";
        _fDate = _selectedDate;
        _fTime = "18:00";
        _fTableId = "";
        _fNote = "";
        _formMessage = null;
        _showForm = true;
    }

    private async Task SubmitReservation()
    {
        if (string.IsNullOrWhiteSpace(_fGuestName)) { _formMessage = "Vui lòng nhập tên khách"; _formSuccess = false; return; }
        if (_fPartySize < 1) { _formMessage = "Số khách phải >= 1"; _formSuccess = false; return; }

        _submitting = true;
        _formMessage = null;

        var timeParts = _fTime.Split(':');
        var reservationTime = _fDate.Date.AddHours(int.Parse(timeParts[0])).AddMinutes(int.Parse(timeParts.Length > 1 ? timeParts[1] : "0"));
        Guid? tableId = Guid.TryParse(_fTableId, out var tid) ? tid : null;

        var ok = await DataService.CreateReservationAsync(new PosDataService.CreateReservationRequest2(
            ShopId, _fGuestName, _fPartySize, reservationTime, _fPhone, tableId, _fNote));

        if (ok)
        {
            _formMessage = "Đặt bàn thành công!";
            _formSuccess = true;
            await LoadReservations();
            _ = Task.Delay(800).ContinueWith(_ => InvokeAsync(() => { _showForm = false; StateHasChanged(); }));
        }
        else
        {
            _formMessage = "Không thể đặt bàn. Vui lòng thử lại.";
            _formSuccess = false;
        }
        _submitting = false;
    }

    private async Task UpdateStatus(Guid id, string status)
    {
        var ok = await DataService.UpdateReservationStatusAsync(id, status);
        if (ok) await LoadReservations();
    }

    private string TableName(Guid tableId)
    {
        var t = _tables.FirstOrDefault(x => x.Id == tableId);
        return t != null ? $"Bàn {t.TableNumber}" : "Bàn ?";
    }

    private static string StatusColor(string s) => s switch
    {
        "pending" => "var(--pos-info)", "confirmed" => "var(--pos-success)",
        "seated" => "var(--pos-orange-primary)", "cancelled" or "no_show" => "var(--pos-danger)", _ => "var(--pos-text-tertiary)"
    };

    private static string StatusBg(string s) => s switch
    {
        "pending" => "rgba(59,130,246,.15)", "confirmed" => "rgba(34,197,94,.15)",
        "seated" => "rgba(255,92,0,.15)", "cancelled" or "no_show" => "rgba(239,68,68,.15)", _ => "var(--pos-bg-interactive)"
    };

    private static string StatusLabel(string s) => s switch
    {
        "pending" => "Chờ XN", "confirmed" => "Đã XN", "seated" => "Đã đến",
        "cancelled" => "Đã hủy", "no_show" => "Vắng mặt", _ => s
    };
}
