@*
    EN: Spa Appointment Book — Date picker, time slots grid (9:00-20:00), staff selection, service, confirm.
    VI: Đặt lịch hẹn Spa — Chọn ngày, lưới khung giờ (9:00-20:00), chọn nhân viên, dịch vụ, xác nhận.
*@
@page "/pos/{ShopId:guid}/spa/appointment-book"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;overflow:hidden;">
    @* ═══ SCHEDULE PANEL (LEFT) / PANEL LỊCH (TRÁI) ═══ *@
    <div class="pos-product-panel" style="padding:16px;overflow-y:auto;">
        @* EN: Header / VI: Tiêu đề *@
        <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
            <button style="background:var(--pos-bg-interactive);border:none;color:var(--pos-text-primary);
                           padding:8px 12px;border-radius:8px;cursor:pointer;font-size:13px;"
                    @onclick="@(() => NavigateTo("spa"))">
                <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
            </button>
            <span style="font-size:16px;font-weight:700;">Đặt lịch hẹn</span>
        </div>

        @if (_isLoading)
        {
            <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
                Đang tải...
            </div>
        }
        else if (_loadError)
        {
            <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
                Không thể tải dữ liệu
            </div>
        }
        else
        {
        @* ═══ DATE PICKER / CHỌN NGÀY ═══ *@
        <div style="margin-bottom:16px;">
            <div style="font-size:13px;font-weight:600;margin-bottom:8px;">Chọn ngày</div>
            <div style="display:flex;gap:8px;">
                @foreach (var day in _dateOptions)
                {
                    <button style="flex:1;padding:12px;border-radius:var(--pos-radius);cursor:pointer;text-align:center;
                                   background:@(day.Value == _selectedDate ? "var(--pos-orange-primary)" : "var(--pos-bg-elevated)");
                                   color:@(day.Value == _selectedDate ? "#FFF" : "var(--pos-text-primary)");
                                   border:1px solid @(day.Value == _selectedDate ? "var(--pos-orange-primary)" : "var(--pos-border-subtle)");"
                            @onclick="() => { _selectedDate = day.Value; _selectedDateValue = day.Date; }">
                        <div style="font-size:11px;opacity:.7;">@day.Label</div>
                        <div style="font-size:16px;font-weight:700;margin-top:2px;">@day.Day</div>
                    </button>
                }
            </div>
        </div>

        @* ═══ STAFF SELECTION / CHỌN NHÂN VIÊN ═══ *@
        <div style="margin-bottom:16px;">
            <div style="font-size:13px;font-weight:600;margin-bottom:8px;">Chọn nhân viên</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                @foreach (var staff in _staffList)
                {
                    var s = staff;
                    <button style="padding:8px 16px;border-radius:20px;cursor:pointer;font-size:13px;
                                   background:@(s.Name == _selectedStaffName ? "var(--pos-orange-primary)" : "var(--pos-bg-elevated)");
                                   color:@(s.Name == _selectedStaffName ? "#FFF" : "var(--pos-text-primary)");
                                   border:1px solid @(s.Name == _selectedStaffName ? "var(--pos-orange-primary)" : "var(--pos-border-subtle)");"
                            @onclick="() => { _selectedStaffName = s.Name; _selectedStaffId = s.Id; }">
                        @s.Name
                    </button>
                }
            </div>
        </div>

        @* ═══ TIME SLOTS GRID / LƯỚI KHUNG GIỜ ═══ *@
        <div style="font-size:13px;font-weight:600;margin-bottom:8px;">Chọn giờ</div>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(90px,1fr));gap:8px;">
            @foreach (var slot in _timeSlots)
            {
                var bgColor = slot.Status == "booked" ? "rgba(239,68,68,.1)"
                    : slot.Time == _selectedTime ? "var(--pos-orange-primary)"
                    : "var(--pos-bg-elevated)";
                var fgColor = slot.Status == "booked" ? "var(--pos-danger)"
                    : slot.Time == _selectedTime ? "#FFF"
                    : "var(--pos-text-primary)";
                var borderColor = slot.Status == "booked" ? "rgba(239,68,68,.3)"
                    : slot.Time == _selectedTime ? "var(--pos-orange-primary)"
                    : "var(--pos-border-subtle)";

                <button style="padding:10px;border-radius:var(--pos-radius);text-align:center;cursor:@(slot.Status == "booked" ? "not-allowed" : "pointer");
                               background:@bgColor;color:@fgColor;border:1px solid @borderColor;font-size:13px;font-weight:500;"
                        disabled="@(slot.Status == "booked")"
                        @onclick="() => _selectedTime = slot.Time">
                    @slot.Time
                    @if (slot.Status == "booked")
                    {
                        <div style="font-size:10px;opacity:.7;">Đã đặt</div>
                    }
                </button>
            }
        </div>
        }
    </div>

    @* ═══ BOOKING SUMMARY (RIGHT) / TÓM TẮT ĐẶT LỊCH (PHẢI) ═══ *@
    <div class="pos-cart-panel">
        <div class="pos-cart-header">
            <span class="pos-cart-header__title">Xác nhận đặt lịch</span>
        </div>

        <div class="pos-cart-items" style="padding:16px;">
            @* EN: Booking details / VI: Chi tiết đặt lịch *@
            <div style="display:flex;flex-direction:column;gap:12px;">
                <div style="display:flex;justify-content:space-between;font-size:13px;">
                    <span style="color:var(--pos-text-secondary);">Khách hàng</span>
                    <span style="font-weight:600;">Khách vãng lai</span>
                </div>
                <div style="display:flex;justify-content:space-between;font-size:13px;">
                    <span style="color:var(--pos-text-secondary);">Ngày</span>
                    <span style="font-weight:600;">@_selectedDate</span>
                </div>
                <div style="display:flex;justify-content:space-between;font-size:13px;">
                    <span style="color:var(--pos-text-secondary);">Giờ</span>
                    <span style="font-weight:600;color:var(--pos-orange-primary);">@(_selectedTime ?? "Chưa chọn")</span>
                </div>
                <div style="display:flex;justify-content:space-between;font-size:13px;">
                    <span style="color:var(--pos-text-secondary);">Nhân viên</span>
                    <span style="font-weight:600;">@_selectedStaffName</span>
                </div>
            </div>

            @* EN: Selected services / VI: Dịch vụ đã chọn *@
            <div style="margin-top:20px;padding-top:16px;border-top:1px solid var(--pos-border-subtle);">
                <div style="font-size:13px;font-weight:600;margin-bottom:10px;">Dịch vụ</div>
                @foreach (var svc in _selectedServices)
                {
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;font-size:13px;">
                        <div>
                            <div style="font-weight:500;">@svc.Name</div>
                            <div style="font-size:11px;color:var(--pos-text-tertiary);">@svc.Duration phút</div>
                        </div>
                        <span style="font-weight:600;">@FormatPrice(svc.Price)</span>
                    </div>
                }
            </div>
        </div>

        <div class="pos-cart-footer">
            <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px;">
                <span style="color:var(--pos-text-secondary);">Tổng thời gian</span>
                <span>@_selectedServices.Sum(s => s.Duration) phút</span>
            </div>
            <div class="pos-cart-total">
                <span class="pos-cart-total__label">Tổng cộng</span>
                <span class="pos-cart-total__value">@FormatPrice(_selectedServices.Sum(s => s.Price))</span>
            </div>
            @if (_bookingError is not null)
            {
                <div style="padding:8px 12px;margin-bottom:8px;border-radius:var(--pos-radius);background:rgba(239,68,68,.1);color:var(--pos-danger);font-size:12px;">
                    @_bookingError
                </div>
            }
            @if (_bookingSuccess)
            {
                <div style="padding:8px 12px;margin-bottom:8px;border-radius:var(--pos-radius);background:rgba(34,197,94,.1);color:var(--pos-success);font-size:12px;">
                    Đặt lịch thành công!
                </div>
            }
            <button class="pos-btn-checkout" @onclick="ConfirmBooking" disabled="@(_isBooking || _selectedTime is null)">
                <i data-lucide="calendar-check" style="width:18px;height:18px;"></i> @(_isBooking ? "Đang đặt lịch..." : "Xác nhận đặt lịch")
            </button>
        </div>
    </div>
</div>

@code {

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

    private string _selectedDate = "Hôm nay";
    private DateTime _selectedDateValue = DateTime.Today;
    private string? _selectedTime = "10:00";
    private string _selectedStaffName = "Bất kỳ";
    private Guid? _selectedStaffId;

    // EN: Date options (dynamic) / VI: Tùy chọn ngày (động)
    private List<DateOption> _dateOptions = new();

    // EN: Staff list from API / VI: Danh sách nhân viên từ API
    private List<StaffOption> _staffList = new();
    private bool _isBooking;
    private string? _bookingError;
    private bool _bookingSuccess;

    // EN: Time slots from API / VI: Khung giờ từ API
    private List<TimeSlot> _timeSlots = new();

    // EN: Selected services from API / VI: Dịch vụ đã chọn từ API
    private List<ServiceInfo> _selectedServices = new();

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

        try
        {
            // EN: Build dynamic date options / VI: Tạo tùy chọn ngày động
            var today = DateTime.Today;
            var dayNames = new[] { "CN", "T2", "T3", "T4", "T5", "T6", "T7" };
            _dateOptions = Enumerable.Range(0, 4).Select(i =>
            {
                var d = today.AddDays(i);
                var label = i == 0 ? "Hôm nay" : i == 1 ? "Ngày mai" : d.ToString("dd/MM");
                return new DateOption(label, dayNames[(int)d.DayOfWeek], label, d);
            }).ToList();
            _selectedDate = _dateOptions[0].Value;
            _selectedDateValue = _dateOptions[0].Date;

            // EN: Load staff from API / VI: Tải nhân viên từ API
            var staffData = await DataService.GetStaffForShopAsync(ShopId);
            _staffList = staffData.Select(s => new StaffOption(
                s.Id,
                $"{s.FirstName ?? ""} {s.LastName ?? ""}".Trim() is { Length: > 0 } name ? name : (s.EmployeeCode ?? s.Id.ToString()[..8])
            )).ToList();
            _staffList.Add(new StaffOption(null, "Bất kỳ"));
            _selectedStaffName = "Bất kỳ";

            // EN: Load appointments to mark booked slots / VI: Tải lịch hẹn để đánh dấu khung giờ đã đặt
            var appointments = await DataService.GetAppointmentsAsync(ShopId);

            var bookedTimes = appointments
                .Where(a => a.StartTime.Date == _selectedDateValue.Date)
                .Select(a => a.StartTime.ToString("HH:mm"))
                .ToHashSet();

            var slots = new List<TimeSlot>();
            for (var hour = 9; hour <= 20; hour++)
            {
                foreach (var min in new[] { 0, 30 })
                {
                    if (hour == 20 && min == 30) break;
                    var time = $"{hour:D2}:{min:D2}";
                    var status = bookedTimes.Contains(time) ? "booked" : "available";
                    slots.Add(new TimeSlot(time, status));
                }
            }
            _timeSlots = slots;

            // EN: Load services/products / VI: Tải dịch vụ/sản phẩm
            var products = await DataService.GetProductsAsync(ShopId);
            _selectedServices = products.Take(2).Select(p => new ServiceInfo(
                p.Id,
                p.Name,
                p.Price,
                p.DurationMinutes ?? 60
            )).ToList();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    // EN: Confirm booking via API / VI: Xác nhận đặt lịch qua API
    private async Task ConfirmBooking()
    {
        if (_selectedTime is null || !_selectedServices.Any()) return;

        _isBooking = true;
        _bookingError = null;
        _bookingSuccess = false;

        try
        {
            var timeParts = _selectedTime.Split(':');
            var startTime = _selectedDateValue.Date
                .AddHours(int.Parse(timeParts[0]))
                .AddMinutes(int.Parse(timeParts[1]));
            var totalDuration = _selectedServices.Sum(s => s.Duration);
            var endTime = startTime.AddMinutes(totalDuration);

            // EN: Create appointment for the first service (primary) / VI: Tạo lịch hẹn cho dịch vụ chính
            var request = new WebClientTpos.Client.Services.PosDataService.CreateAppointmentRequest(
                ShopId,
                null, // CustomerId
                _selectedStaffId,
                null, // ResourceId
                _selectedServices.First().Id,
                startTime,
                endTime
            );

            var success = await DataService.CreateAppointmentAsync(request);
            if (success)
            {
                _bookingSuccess = true;
                await Task.Delay(1000);
                NavigateTo("spa");
            }
            else
            {
                _bookingError = "Không thể đặt lịch. Vui lòng thử lại.";
            }
        }
        catch
        {
            _bookingError = "Lỗi kết nối. Vui lòng thử lại.";
        }
        finally
        {
            _isBooking = false;
        }
    }

    private record DateOption(string Label, string Day, string Value, DateTime Date);
    private record TimeSlot(string Time, string Status);
    private record ServiceInfo(Guid Id, string Name, decimal Price, int Duration);
    private record StaffOption(Guid? Id, string Name);
}
