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

<div style="display:flex;justify-content:flex-end;margin-bottom:12px;">
    <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick='() => { _showApptForm = !_showApptForm; _apptFormMessage = null; _newApptStart = DateTime.Today.AddHours(9); _newApptEnd = DateTime.Today.AddHours(10); }'>
        <i data-lucide="plus-circle" style="width:16px;height:16px;"></i>Thêm lịch hẹn
    </button>
</div>
@if (_showApptForm)
{
    <div class="admin-panel" style="margin-bottom:16px;border:1px solid rgba(236,72,153,0.3);">
        <div class="admin-panel__header"><h3 class="admin-panel__title">Thêm lịch hẹn mới</h3></div>
        <div class="admin-panel__body">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Thời gian bắt đầu *</label><input type="datetime-local" @bind="_newApptStart" 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;">Thời gian kết thúc *</label><input type="datetime-local" @bind="_newApptEnd" 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="AddAppointment" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>Lưu</button>
                <button @onclick='() => _showApptForm = 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 (_apptFormMessage != null) { <div style="margin-top:8px;font-size:13px;color:@(_apptFormSuccess ? "#22C55E" : "#EF4444");">@_apptFormMessage</div> }
        </div>
    </div>
}
@{
    var calWeekStart = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + 1 + _calendarWeekOffset * 7);
    var calWeekEnd = calWeekStart.AddDays(7);
    var weekAppts = _appointments.Where(a => a.StartTime >= calWeekStart && a.StartTime < calWeekEnd).ToList();
}
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;">
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(236,72,153,0.1);"><i data-lucide="calendar" style="color:#EC4899;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_appointments.Count</span><span class="admin-stat-card__label">Tổng lịch hẹn</span></div></div>
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(34,197,94,0.1);"><i data-lucide="check-circle" style="color:#22C55E;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_appointments.Count(a => a.Status == "Confirmed")</span><span class="admin-stat-card__label">Đã xác nhận</span></div></div>
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(245,158,11,0.1);"><i data-lucide="clock" style="color:#F59E0B;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_appointments.Count(a => a.Status == "Pending")</span><span class="admin-stat-card__label">Chờ xác nhận</span></div></div>
        <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(59,130,246,0.1);"><i data-lucide="calendar-range" style="color:#3B82F6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@weekAppts.Count</span><span class="admin-stat-card__label">Tuần này</span></div></div>
    </div>
</div>
<div class="admin-panel">
    <div class="admin-panel__header" style="display:flex;justify-content:space-between;align-items:center;">
        <h3 style="margin:0;font-size:14px;font-weight:700;">Lịch hẹn tuần @calWeekStart.ToString("dd/MM") — @calWeekEnd.AddDays(-1).ToString("dd/MM")</h3>
        <div style="display:flex;gap:4px;">
            <button @onclick='() => { _calendarWeekOffset--; StateHasChanged(); }' 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:12px;cursor:pointer;">← Trước</button>
            <button @onclick='() => { _calendarWeekOffset = 0; StateHasChanged(); }' style="padding:6px 12px;border-radius:8px;border:1px solid var(--admin-orange-primary);background:rgba(255,92,0,0.1);color:var(--admin-orange-primary);font-size:12px;font-weight:600;cursor:pointer;">Hôm nay</button>
            <button @onclick='() => { _calendarWeekOffset++; StateHasChanged(); }' 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:12px;cursor:pointer;">Sau →</button>
        </div>
    </div>
    <div class="admin-panel__body" style="padding:0;">
        <div style="display:grid;grid-template-columns:repeat(7,1fr);min-height:300px;">
            @for (int d = 0; d < 7; d++)
            {
                var day = calWeekStart.AddDays(d);
                var dayAppts = weekAppts.Where(a => a.StartTime.Date == day.Date).OrderBy(a => a.StartTime).ToList();
                var isToday = day.Date == DateTime.Today;
                <div style="border-right:1px solid var(--admin-border-subtle);padding:8px;@(d == 6 ? "border-right:none;" : "")">
                    <div style="text-align:center;padding:6px 0;margin-bottom:8px;border-radius:8px;@(isToday ? "background:rgba(255,92,0,0.15);" : "")">
                        <div style="font-size:11px;font-weight:600;color:var(--admin-text-tertiary);">@DayLabel((int)day.DayOfWeek)</div>
                        <div style="font-size:16px;font-weight:700;@(isToday ? "color:var(--admin-orange-primary);" : "")">@day.Day</div>
                    </div>
                    @foreach (var appt in dayAppts)
                    {
                        var apptColor = appt.Status switch { "Confirmed" => "#22C55E", "Pending" => "#F59E0B", "Completed" => "#3B82F6", _ => "#6B6B6F" };
                        <div style="background:@($"{apptColor}15");border-left:3px solid @apptColor;border-radius:6px;padding:6px 8px;margin-bottom:4px;font-size:11px;">
                            <div style="font-weight:600;">@appt.StartTime.ToString("HH:mm")-@appt.EndTime.ToString("HH:mm")</div>
                            <div style="color:var(--admin-text-tertiary);margin-top:2px;">@(appt.ResourceName ?? "—")</div>
                            @if (appt.Status != "Cancelled" && appt.Status != "Completed")
                            {
                                <button @onclick='() => CancelAppt(appt.Id)' style="margin-top:4px;padding:2px 6px;border-radius:4px;border:none;background:rgba(239,68,68,0.15);color:#EF4444;font-size:10px;cursor:pointer;">Hủy</button>
                            }
                        </div>
                    }
                    @if (!dayAppts.Any())
                    {
                        <div style="text-align:center;padding:20px 0;font-size:11px;color:var(--admin-text-quaternary, #555);">—</div>
                    }
                </div>
            }
        </div>
    </div>
</div>

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

    // Appointments state
    private List<PosDataService.AppointmentInfo> _appointments = new();
    // Appointments form state
    private bool _showApptForm;
    private DateTime _newApptStart = DateTime.Today.AddHours(9);
    private DateTime _newApptEnd = DateTime.Today.AddHours(10);
    private string? _apptFormMessage;
    private bool _apptFormSuccess;
    private int _calendarWeekOffset;
    private string? _errorMessage;

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
            _appointments = await DataService.GetAppointmentsAsync(ShopId);
    }

    private async Task AddAppointment()
    {
        _apptFormMessage = null;
        if (ShopId == Guid.Empty)
        {
            _apptFormMessage = "Thiếu thông tin cửa hàng."; _apptFormSuccess = false; return;
        }
        try
        {
            await DataService.CreateAppointmentAsync(new PosDataService.CreateAppointmentRequest(
                ShopId, null, null, null, null, _newApptStart, _newApptEnd));
            _apptFormMessage = "Đã thêm lịch hẹn thành công!"; _apptFormSuccess = true;
            _showApptForm = false;
            _appointments = await DataService.GetAppointmentsAsync(ShopId);
        }
        catch (Exception ex) { _apptFormMessage = $"Lỗi: {ex.Message}"; _apptFormSuccess = false; }
    }

    private async Task CancelAppt(Guid apptId)
    {
        try
        {
            await DataService.CancelAppointmentAsync(apptId);
            if (ShopId != Guid.Empty) _appointments = await DataService.GetAppointmentsAsync(ShopId);
        }
        catch (Exception ex) { _errorMessage = $"Không thể hủy lịch hẹn: {ex.Message}"; }
    }

    private static string DayLabel(int dow) => dow switch
    {
        0 => "CN", 1 => "T2", 2 => "T3", 3 => "T4",
        4 => "T5", 5 => "T6", 6 => "T7", _ => $"#{dow}"
    };
}
