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

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
    <div style="display:flex;align-items:center;gap:12px;">
        <input type="date" @bind="_selectedDate" @bind:event="onchange" @bind:after="LoadReservations"
            style="padding:6px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:13px;" />
        <div style="display:flex;gap:4px;background:var(--admin-bg-elevated);border-radius:8px;padding:3px;">
            @foreach (var st in new[] { ("all", "", "Tất cả"), ("pending", "clock", "Chờ"), ("confirmed", "check-circle", "Xác nhận"), ("seated", "armchair", "Đã ngồi"), ("cancelled", "x-circle", "Đã hủy"), ("no_show", "user-x", "Vắng") })
            {
                var count = st.Item1 == "all" ? _reservations.Count : _reservations.Count(r => r.Status == st.Item1);
                <button @onclick='() => { _statusFilter = st.Item1; }'
                    style="padding:6px 12px;border-radius:6px;border:none;font-size:11px;font-weight:600;cursor:pointer;transition:all 0.2s;display:flex;align-items:center;gap:4px;@(_statusFilter == st.Item1 ? "background:var(--admin-orange-primary);color:white;" : "background:transparent;color:var(--admin-text-secondary);")">
                    @if (!string.IsNullOrEmpty(st.Item2)) { <i data-lucide="@st.Item2" style="width:12px;height:12px;"></i> }@st.Item3 @if (count > 0) { <span style="font-size:10px;opacity:0.8;">(@count)</span> }
                </button>
            }
        </div>
    </div>
    <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick="ToggleForm">
        <i data-lucide="@(_showForm ? "x" : "plus-circle")" style="width:16px;height:16px;"></i>@(_showForm ? "Đóng" : "Tạo đặt bàn")
    </button>
</div>

@if (_showForm)
{
    <div class="admin-panel" style="margin-bottom:16px;border:1px solid rgba(59,130,246,0.3);">
        <div class="admin-panel__header"><h3 class="admin-panel__title"><i data-lucide="calendar-plus" style="width:16px;height:16px;vertical-align:middle;margin-right:4px;"></i>Tạo đặt bàn mới</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 khách *</label><input type="text" @bind="_formGuestName" placeholder="Nhập tên khách" 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;">Số điện thoại</label><input type="tel" @bind="_formPhone" placeholder="0912 345 678" 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;">Số khách *</label><input type="number" @bind="_formPartySize" 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:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-top:12px;">
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Thời gian đặt *</label><input type="datetime-local" @bind="_formReservationTime" 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;">Bàn</label>
                    <select @bind="_formTableId" 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="">— Chưa chọn —</option>
                        @foreach (var t in _tables.Where(t => t.Status == "available"))
                        {
                            <option value="@t.Id">@t.TableNumber (@t.Capacity chỗ) @(t.Zone != null ? $"- {t.Zone}" : "")</option>
                        }
                    </select>
                </div>
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Ghi chú</label><input type="text" @bind="_formNote" placeholder="VD: Sinh nhật, yêu cầu đặc biệt" 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="CreateReservation" disabled="@_saving" style="display:inline-flex;align-items:center;gap:6px;">
                    <i data-lucide="@(_saving ? "loader" : "check")" style="width:14px;height:14px;"></i>@(_saving ? "Đang lưu..." : "Tạo đặt bàn")
                </button>
                <button @onclick='() => _showForm = 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 (_formMessage != null) { <div style="margin-top:8px;font-size:13px;color:@(_formSuccess ? "#22C55E" : "#EF4444");">@_formMessage</div> }
        </div>
    </div>
}

@if (_loading)
{
    <div style="text-align:center;padding:40px;color:var(--admin-text-tertiary);">
        <i data-lucide="loader" style="width:24px;height:24px;animation:spin 1s linear infinite;"></i>
        <p style="margin-top:8px;">Đang tải...</p>
    </div>
}
else if (!FilteredReservations.Any())
{
    <div style="text-align:center;padding:60px 20px;">
        <div style="width:80px;height:80px;border-radius:24px;background:rgba(59,130,246,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
            <i data-lucide="calendar-check" style="width:36px;height:36px;color:#3B82F6;"></i>
        </div>
        <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--admin-text-primary);">Chưa có đặt bàn</h2>
        <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0;">@(_statusFilter == "all" ? "Nhấn 'Tạo đặt bàn' để thêm lịch đặt bàn mới" : "Không có đặt bàn nào ở trạng thái này")</p>
    </div>
}
else
{
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:16px;">
        @foreach (var res in FilteredReservations)
        {
            var (statusColor, statusBg, statusText, statusIcon) = res.Status switch
            {
                "pending" => ("#F59E0B", "rgba(245,158,11,0.08)", "Chờ xác nhận", "clock"),
                "confirmed" => ("#3B82F6", "rgba(59,130,246,0.08)", "Đã xác nhận", "check-circle"),
                "seated" => ("#22C55E", "rgba(34,197,94,0.08)", "Đã ngồi", "armchair"),
                "cancelled" => ("#EF4444", "rgba(239,68,68,0.08)", "Đã hủy", "x-circle"),
                "no_show" => ("#6B6B6F", "rgba(107,107,111,0.08)", "Vắng mặt", "user-x"),
                _ => ("#6B6B6F", "rgba(107,107,111,0.08)", res.Status, "circle")
            };
            var tableName = _tables.FirstOrDefault(t => t.Id == res.TableId)?.TableNumber;
            <div style="background:@statusBg;border:1px solid @($"{statusColor}33");border-radius:14px;padding:20px;position:relative;">
                @* Status badge *@
                <div style="position:absolute;top:12px;right:12px;display:inline-flex;align-items:center;gap:4px;font-size:11px;font-weight:600;color:@statusColor;padding:3px 10px;border-radius:6px;background:@($"{statusColor}15");">
                    <i data-lucide="@statusIcon" style="width:12px;height:12px;"></i>@statusText
                </div>

                @* Guest info *@
                <div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
                    <div style="width:44px;height:44px;border-radius:12px;background:@($"{statusColor}18");display:flex;align-items:center;justify-content:center;">
                        <i data-lucide="user" style="width:20px;height:20px;color:@statusColor;"></i>
                    </div>
                    <div>
                        <div style="font-size:16px;font-weight:700;">@res.GuestName</div>
                        @if (!string.IsNullOrEmpty(res.Phone))
                        {
                            <div style="font-size:12px;color:var(--admin-text-tertiary);display:flex;align-items:center;gap:4px;">
                                <i data-lucide="phone" style="width:10px;height:10px;"></i>@res.Phone
                            </div>
                        }
                    </div>
                </div>

                @* Details *@
                <div style="display:flex;gap:16px;margin-bottom:12px;font-size:13px;color:var(--admin-text-secondary);">
                    <span style="display:flex;align-items:center;gap:4px;"><i data-lucide="clock" style="width:14px;height:14px;"></i>@res.ReservationTime.ToString("HH:mm")</span>
                    <span style="display:flex;align-items:center;gap:4px;"><i data-lucide="users" style="width:14px;height:14px;"></i>@res.PartySize khách</span>
                    @if (tableName != null)
                    {
                        <span style="display:flex;align-items:center;gap:4px;"><i data-lucide="grid-3x3" style="width:14px;height:14px;"></i>Bàn @tableName</span>
                    }
                </div>

                @if (!string.IsNullOrEmpty(res.Note))
                {
                    <div style="font-size:12px;color:var(--admin-text-tertiary);margin-bottom:12px;padding:8px 12px;border-radius:8px;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.06);">
                        <i data-lucide="message-square" style="width:11px;height:11px;vertical-align:middle;margin-right:4px;"></i>@res.Note
                    </div>
                }

                @* Actions *@
                @if (res.Status == "pending" || res.Status == "confirmed")
                {
                    <div style="display:flex;gap:8px;padding-top:12px;border-top:1px solid @($"{statusColor}22");">
                        @if (res.Status == "pending")
                        {
                            <button @onclick='() => UpdateStatus(res.Id, "confirmed")' style="flex:1;padding:7px 0;border-radius:8px;border:none;font-size:12px;font-weight:600;cursor:pointer;background:rgba(59,130,246,0.15);color:#3B82F6;">
                                <i data-lucide="check" style="width:12px;height:12px;vertical-align:middle;margin-right:3px;"></i>Xác nhận
                            </button>
                        }
                        @if (res.Status == "confirmed")
                        {
                            <button @onclick='() => UpdateStatus(res.Id, "seated")' style="flex:1;padding:7px 0;border-radius:8px;border:none;font-size:12px;font-weight:600;cursor:pointer;background:rgba(34,197,94,0.15);color:#22C55E;">
                                <i data-lucide="armchair" style="width:12px;height:12px;vertical-align:middle;margin-right:3px;"></i>Đã ngồi
                            </button>
                            <button @onclick='() => UpdateStatus(res.Id, "no_show")' style="flex:1;padding:7px 0;border-radius:8px;border:none;font-size:12px;font-weight:600;cursor:pointer;background:rgba(107,107,111,0.15);color:#6B6B6F;">
                                <i data-lucide="user-x" style="width:12px;height:12px;vertical-align:middle;margin-right:3px;"></i>Vắng
                            </button>
                        }
                        <button @onclick='() => UpdateStatus(res.Id, "cancelled")' style="padding:7px 14px;border-radius:8px;border:none;font-size:12px;font-weight:600;cursor:pointer;background:rgba(239,68,68,0.15);color:#EF4444;">
                            <i data-lucide="x" style="width:12px;height:12px;vertical-align:middle;"></i>
                        </button>
                    </div>
                }
            </div>
        }
    </div>
}

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

    private List<PosDataService.ReservationInfo> _reservations = new();
    private List<PosDataService.TableInfo> _tables = new();
    private string _statusFilter = "all";
    private DateTime _selectedDate = DateTime.Today;
    private bool _loading = true;
    private bool _showForm;
    private bool _saving;

    // Form fields
    private string _formGuestName = "";
    private string? _formPhone;
    private int _formPartySize = 2;
    private DateTime _formReservationTime = DateTime.Today.AddHours(12);
    private string _formTableId = "";
    private string? _formNote;
    private string? _formMessage;
    private bool _formSuccess;

    private IEnumerable<PosDataService.ReservationInfo> FilteredReservations =>
        _statusFilter == "all" ? _reservations : _reservations.Where(r => r.Status == _statusFilter);

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
        {
            _tables = await DataService.GetTablesAsync(ShopId);
            await LoadReservations();
        }
        _loading = false;
    }

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

    private void ToggleForm()
    {
        _showForm = !_showForm;
        if (_showForm)
        {
            _formGuestName = "";
            _formPhone = null;
            _formPartySize = 2;
            _formReservationTime = _selectedDate.Date.AddHours(DateTime.Now.Hour + 1);
            _formTableId = "";
            _formNote = null;
            _formMessage = null;
        }
    }

    private async Task CreateReservation()
    {
        _formMessage = null;
        if (string.IsNullOrWhiteSpace(_formGuestName))
        {
            _formMessage = "Vui lòng nhập tên khách."; _formSuccess = false; return;
        }
        if (_formPartySize <= 0)
        {
            _formMessage = "Số khách phải lớn hơn 0."; _formSuccess = false; return;
        }

        _saving = true;
        try
        {
            Guid? tableId = Guid.TryParse(_formTableId, out var tid) ? tid : null;
            var req = new PosDataService.CreateReservationRequest2(
                ShopId, _formGuestName.Trim(), _formPartySize, _formReservationTime,
                string.IsNullOrWhiteSpace(_formPhone) ? null : _formPhone.Trim(),
                tableId,
                string.IsNullOrWhiteSpace(_formNote) ? null : _formNote.Trim());
            var ok = await DataService.CreateReservationAsync(req);
            if (ok)
            {
                _formMessage = "Tạo đặt bàn thành công!"; _formSuccess = true;
                _formGuestName = ""; _formPhone = null; _formPartySize = 2; _formTableId = ""; _formNote = null;
                await LoadReservations();
            }
            else
            {
                _formMessage = "Không thể tạo đặt bàn. Vui lòng thử lại."; _formSuccess = false;
            }
        }
        catch (Exception ex) { _formMessage = $"Lỗi: {ex.Message}"; _formSuccess = false; }
        finally { _saving = false; }
    }

    private async Task UpdateStatus(Guid reservationId, string newStatus)
    {
        try
        {
            var ok = await DataService.UpdateReservationStatusAsync(reservationId, newStatus);
            if (ok) await LoadReservations();
        }
        catch (Exception ex) { Console.Error.WriteLine($"Update status failed: {ex.Message}"); }
    }
}
