@*
    EN: Spa Treatment Timer — Large circular countdown, service info, customer/therapist, extend time, complete, notes.
    VI: Đồng hồ trị liệu Spa — Đếm ngược tròn lớn, thông tin dịch vụ, khách/KTV, gia hạn, hoàn thành, ghi chú.
*@
@page "/pos/{ShopId:guid}/spa/treatment-timer"
@page "/pos/{ShopId:guid}/spa/treatment-timer/{AppointmentId:guid}"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService
@implements IDisposable

<div style="flex:1;display:flex;overflow:hidden;">
    @* ═══ TIMER PANEL (LEFT) / PANEL ĐỒNG HỒ (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/therapist-schedule"))">
                <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
            </button>
            <span style="font-size:16px;font-weight:700;">Đang thực hiện dịch vụ</span>
        </div>

        @* ═══ CIRCULAR TIMER / ĐỒNG HỒ TRÒN ═══ *@
        <div style="display:flex;justify-content:center;margin-bottom:24px;">
            <div style="position:relative;width:240px;height:240px;">
                @* EN: Background circle / VI: Vòng tròn nền *@
                <svg viewBox="0 0 240 240" style="width:100%;height:100%;transform:rotate(-90deg);">
                    <circle cx="120" cy="120" r="108" fill="none" stroke="var(--pos-bg-interactive)" stroke-width="8" />
                    <circle cx="120" cy="120" r="108" fill="none" stroke="var(--pos-orange-primary)" stroke-width="8"
                            stroke-dasharray="@(2 * Math.PI * 108)" stroke-dashoffset="@(2 * Math.PI * 108 * (1 - _progress))"
                            stroke-linecap="round" />
                </svg>
                @* EN: Timer text / VI: Chữ đồng hồ *@
                <div style="position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;">
                    <div style="font-size:11px;color:var(--pos-text-tertiary);font-weight:600;text-transform:uppercase;">CÒN LẠI</div>
                    <div style="font-size:44px;font-weight:700;color:var(--pos-orange-primary);font-variant-numeric:tabular-nums;margin:4px 0;">
                        @_remainingTime
                    </div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);">/ @_totalDuration phút</div>
                </div>
            </div>
        </div>

        @* EN: Progress bar / VI: Thanh tiến trình *@
        <div style="margin-bottom:20px;">
            <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--pos-text-tertiary);margin-bottom:6px;">
                <span>Bắt đầu: @_startTime.ToString("HH:mm")</span>
                <span>Dự kiến: @_endTime.ToString("HH:mm")</span>
            </div>
            <div style="height:8px;border-radius:4px;background:var(--pos-bg-interactive);">
                <div style="height:100%;border-radius:4px;background:linear-gradient(90deg,var(--pos-orange-primary),#F59E0B);width:@(_progress * 100)%;transition:width 0.3s;"></div>
            </div>
        </div>

        @* ═══ SERVICE INFO / THÔNG TIN DỊCH VỤ ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;margin-bottom:16px;">
            <div style="font-size:18px;font-weight:700;margin-bottom:8px;">@_serviceName</div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div style="display:flex;align-items:center;gap:8px;font-size:13px;">
                    <i data-lucide="user" style="width:14px;height:14px;color:var(--pos-text-tertiary);"></i>
                    <span style="color:var(--pos-text-secondary);">Khách:</span>
                    <span style="font-weight:600;">@_customerName</span>
                </div>
                <div style="display:flex;align-items:center;gap:8px;font-size:13px;">
                    <i data-lucide="briefcase" style="width:14px;height:14px;color:var(--pos-text-tertiary);"></i>
                    <span style="color:var(--pos-text-secondary);">KTV:</span>
                    <span style="font-weight:600;">@_therapistName</span>
                </div>
                <div style="display:flex;align-items:center;gap:8px;font-size:13px;">
                    <i data-lucide="clock" style="width:14px;height:14px;color:var(--pos-text-tertiary);"></i>
                    <span style="color:var(--pos-text-secondary);">Thời gian:</span>
                    <span style="font-weight:600;">@_totalDuration phút</span>
                </div>
                <div style="display:flex;align-items:center;gap:8px;font-size:13px;">
                    <i data-lucide="tag" style="width:14px;height:14px;color:var(--pos-text-tertiary);"></i>
                    <span style="color:var(--pos-text-secondary);">Giá:</span>
                    <span style="font-weight:600;color:var(--pos-orange-primary);">@FormatPrice(_servicePrice)</span>
                </div>
            </div>
        </div>

        @* ═══ EXTEND TIME / GIA HẠN THỜI GIAN ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;margin-bottom:16px;">
            <div style="font-size:13px;font-weight:600;margin-bottom:10px;">Gia hạn thêm</div>
            <div style="display:flex;gap:8px;">
                @foreach (var ext in _extendOptions)
                {
                    <button style="flex:1;padding:12px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);
                                   border:1px solid var(--pos-border-default);color:var(--pos-text-primary);
                                   cursor:pointer;font-size:13px;text-align:center;"
                            @onclick="() => ExtendTime(ext)">
                        <div style="font-weight:600;">+@ext phút</div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">
                            +@FormatPrice(ext == 15 ? 125_000 : ext == 30 ? 250_000 : 375_000)
                        </div>
                    </button>
                }
            </div>
        </div>

        @* ═══ NOTES / GHI CHÚ ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;">
            <div style="font-size:13px;font-weight:600;margin-bottom:8px;">Ghi chú</div>
            <textarea @bind="_notes" placeholder="Ghi chú cho buổi trị liệu..."
                      style="width:100%;min-height:80px;padding:12px;border-radius:8px;background:var(--pos-bg-interactive);
                             border:1px solid var(--pos-border-default);color:var(--pos-text-primary);font-size:13px;
                             resize:vertical;outline:none;font-family:inherit;"></textarea>
        </div>
    </div>

    @* ═══ ACTIONS PANEL (RIGHT) / PANEL HÀNH ĐỘNG (PHẢI) ═══ *@
    <div class="pos-cart-panel">
        <div class="pos-cart-header">
            <span class="pos-cart-header__title">Trạng thái</span>
        </div>

        <div class="pos-cart-items" style="padding:16px;">
            @* EN: Status indicator / VI: Chỉ báo trạng thái *@
            <div style="text-align:center;padding:20px 0;margin-bottom:16px;">
                <div style="width:64px;height:64px;border-radius:50%;background:rgba(255,92,0,.15);
                            display:flex;align-items:center;justify-content:center;margin:0 auto 12px;">
                    <i data-lucide="activity" style="width:28px;height:28px;color:var(--pos-orange-primary);"></i>
                </div>
                <div style="font-size:16px;font-weight:700;color:var(--pos-orange-primary);">Đang thực hiện</div>
                <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:4px;">Phòng 3 • Giường 2</div>
            </div>

            @* EN: Session details / VI: Chi tiết phiên *@
            <div style="display:flex;flex-direction:column;gap:8px;">
                <div style="display:flex;justify-content:space-between;font-size:13px;padding:8px 0;border-bottom:1px solid var(--pos-border-subtle);">
                    <span style="color:var(--pos-text-secondary);">Bắt đầu</span>
                    <span style="font-weight:600;">@_startTime.ToString("HH:mm")</span>
                </div>
                <div style="display:flex;justify-content:space-between;font-size:13px;padding:8px 0;border-bottom:1px solid var(--pos-border-subtle);">
                    <span style="color:var(--pos-text-secondary);">Dự kiến kết thúc</span>
                    <span style="font-weight:600;">@_endTime.ToString("HH:mm")</span>
                </div>
                <div style="display:flex;justify-content:space-between;font-size:13px;padding:8px 0;border-bottom:1px solid var(--pos-border-subtle);">
                    <span style="color:var(--pos-text-secondary);">Đã gia hạn</span>
                    <span style="font-weight:600;">@_extendedMinutes phút</span>
                </div>
                <div style="display:flex;justify-content:space-between;font-size:13px;padding:8px 0;">
                    <span style="color:var(--pos-text-secondary);">Dịch vụ tiếp theo</span>
                    <span style="font-weight:600;">Facial collagen</span>
                </div>
            </div>
        </div>

        <div class="pos-cart-footer">
            <div class="pos-cart-total">
                <span class="pos-cart-total__label">Tổng phiên</span>
                <span class="pos-cart-total__value">@FormatPrice(_servicePrice + _extendedMinutes / 15 * 125_000)</span>
            </div>
            <button class="pos-btn-checkout" style="background:var(--pos-success);" @onclick="CompleteTreatment" disabled="@_isCompleting">
                <i data-lucide="check-circle" style="width:18px;height:18px;"></i> @(_isCompleting ? "Đang xử lý..." : "Hoàn thành dịch vụ")
            </button>
        </div>
    </div>
</div>

@code {
    // EN: Route parameter for appointment ID / VI: Tham số route cho ID lịch hẹn
    [Parameter] public Guid? AppointmentId { get; set; }

    // EN: Timer state / VI: Trạng thái đồng hồ
    private string _remainingTime = "00:00";
    private int _totalDuration = 60;
    private double _progress = 0.0;
    private int _extendedMinutes = 0;
    private string _notes = "";
    private bool _isCompleting;
    private System.Threading.Timer? _timer;

    // EN: Appointment details / VI: Chi tiết lịch hẹn
    private string _serviceName = "Dịch vụ";
    private string _customerName = "Khách";
    private string _therapistName = "KTV";
    private decimal _servicePrice = 0;
    private DateTime _startTime = DateTime.Now;
    private DateTime _endTime = DateTime.Now.AddHours(1);

    private readonly int[] _extendOptions = { 15, 30, 45 };

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

        try
        {
            if (AppointmentId.HasValue)
            {
                // EN: Load appointment details / VI: Tải chi tiết lịch hẹn
                var appt = await DataService.GetAppointmentByIdAsync(AppointmentId.Value);
                if (appt is not null)
                {
                    _startTime = appt.StartTime;
                    _endTime = appt.EndTime;
                    _totalDuration = (int)(appt.EndTime - appt.StartTime).TotalMinutes;
                    _serviceName = appt.ResourceName ?? "Dịch vụ";

                    // EN: Load staff name if available / VI: Tải tên nhân viên nếu có
                    if (appt.StaffId.HasValue)
                    {
                        var staffList = await DataService.GetStaffForShopAsync(ShopId);
                        var staff = staffList.FirstOrDefault(s => s.Id == appt.StaffId.Value);
                        if (staff is not null)
                        {
                            var name = $"{staff.FirstName ?? ""} {staff.LastName ?? ""}".Trim();
                            _therapistName = string.IsNullOrEmpty(name) ? (staff.EmployeeCode ?? "KTV") : name;
                        }
                    }
                }
            }
            else
            {
                // EN: Fallback — use default 60 min from now / VI: Mặc định — 60 phút từ hiện tại
                _startTime = DateTime.Now;
                _totalDuration = 60;
                _endTime = _startTime.AddMinutes(_totalDuration);
            }
        }
        catch
        {
            // EN: Use defaults on error / VI: Dùng giá trị mặc định khi lỗi
        }

        // EN: Start real countdown timer / VI: Bắt đầu đồng hồ đếm ngược thật
        UpdateTimerDisplay();
        _timer = new System.Threading.Timer(TimerCallback, null, 0, 1000);
    }

    private void TimerCallback(object? state)
    {
        InvokeAsync(() =>
        {
            UpdateTimerDisplay();
            StateHasChanged();
        });
    }

    private void UpdateTimerDisplay()
    {
        var totalSeconds = (int)(_endTime.AddMinutes(_extendedMinutes) - DateTime.Now).TotalSeconds;
        if (totalSeconds < 0) totalSeconds = 0;

        var minutes = totalSeconds / 60;
        var seconds = totalSeconds % 60;
        _remainingTime = $"{minutes:D2}:{seconds:D2}";

        var totalDurationSeconds = (_totalDuration + _extendedMinutes) * 60;
        var elapsed = totalDurationSeconds - totalSeconds;
        _progress = totalDurationSeconds > 0 ? Math.Clamp((double)elapsed / totalDurationSeconds, 0, 1) : 0;
    }

    private void ExtendTime(int minutes)
    {
        _extendedMinutes += minutes;
    }

    private async Task CompleteTreatment()
    {
        _isCompleting = true;
        try
        {
            if (AppointmentId.HasValue)
            {
                await DataService.UpdateAppointmentStatusAsync(AppointmentId.Value, "complete");
            }
            NavigateTo("spa/therapist-schedule");
        }
        catch
        {
            NavigateTo("spa/therapist-schedule");
        }
        finally
        {
            _isCompleting = false;
        }
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}
