@extends('layouts.admin')

@section('title', 'Antrian Notifikasi')

@section('content')
{{-- Stats Cards --}}
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
    <div class="bg-white rounded-xl border border-gray-100 p-4">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-xs text-gray-500 uppercase font-medium">Total Dijadwalkan</p>
                <p class="text-2xl font-bold text-gray-800 mt-1">{{ $stats['total_scheduled'] }}</p>
            </div>
            <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            </div>
        </div>
    </div>
    <div class="bg-white rounded-xl border border-gray-100 p-4">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-xs text-gray-500 uppercase font-medium">Email Menunggu</p>
                <p class="text-2xl font-bold text-blue-600 mt-1">{{ $stats['email_scheduled'] }}</p>
            </div>
            <div class="w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"/></svg>
            </div>
        </div>
    </div>
    <div class="bg-white rounded-xl border border-gray-100 p-4">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-xs text-gray-500 uppercase font-medium">WhatsApp Menunggu</p>
                <p class="text-2xl font-bold text-green-600 mt-1">{{ $stats['wa_scheduled'] }}</p>
            </div>
            <div class="w-10 h-10 bg-green-50 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8.625 12a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 01-2.555-.337A5.972 5.972 0 015.41 20.97a5.969 5.969 0 01-.474-.065 4.48 4.48 0 00.978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25z"/></svg>
            </div>
        </div>
    </div>
    <div class="bg-white rounded-xl border border-gray-100 p-4">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-xs text-gray-500 uppercase font-medium">Siap Kirim Sekarang</p>
                <p id="dueNowCount" class="text-2xl font-bold {{ $stats['due_now'] > 0 ? 'text-orange-600' : 'text-gray-400' }} mt-1">{{ $stats['due_now'] }}</p>
            </div>
            <div id="dueNowIconWrap" class="w-10 h-10 {{ $stats['due_now'] > 0 ? 'bg-orange-100' : 'bg-gray-50' }} rounded-lg flex items-center justify-center">
                <svg id="dueNowIcon" class="w-5 h-5 {{ $stats['due_now'] > 0 ? 'text-orange-500' : 'text-gray-400' }}" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z"/></svg>
            </div>
        </div>
    </div>
</div>

{{-- Action Buttons --}}
<div class="flex flex-wrap items-center gap-3 mb-6">
    @if($stats['due_now'] > 0)
    <form action="{{ route('admin.notifications.send-all-due') }}" method="POST" onsubmit="return confirm('Kirim semua {{ $stats['due_now'] }} notifikasi yang sudah jatuh tempo?')">
        @csrf
        <button class="bg-indigo-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-indigo-700 flex items-center gap-2">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"/></svg>
            Kirim Semua yang Jatuh Tempo ({{ $stats['due_now'] }})
        </button>
    </form>
    @endif

    @if($stats['total_scheduled'] > 0)
    <form action="{{ route('admin.notifications.cancel-all') }}" method="POST" onsubmit="return confirm('Batalkan SEMUA {{ $stats['total_scheduled'] }} notifikasi yang dijadwalkan?')">
        @csrf
        <button class="bg-red-50 text-red-600 px-4 py-2 rounded-lg text-sm font-medium hover:bg-red-100 flex items-center gap-2">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
            Batalkan Semua
        </button>
    </form>
    @endif

    <a href="{{ route('admin.notifications') }}" class="bg-gray-100 text-gray-600 px-4 py-2 rounded-lg text-sm font-medium hover:bg-gray-200 flex items-center gap-2">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m5.231 13.481L15 17.25m-4.5-15H5.625c-.621 0-1.125.504-1.125 1.125v16.5c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"/></svg>
        Lihat Log Notifikasi
    </a>
</div>

{{-- Filter --}}
<div class="mb-6">
    <form action="{{ route('admin.notifications.queue') }}" method="GET" class="flex flex-wrap items-center gap-2">
        <select name="channel" class="border border-gray-200 rounded-lg px-4 py-2 text-sm">
            <option value="">Semua Channel</option>
            <option value="email" {{ request('channel') === 'email' ? 'selected' : '' }}>Email</option>
            <option value="whatsapp" {{ request('channel') === 'whatsapp' ? 'selected' : '' }}>WhatsApp</option>
        </select>
        <select name="type" class="border border-gray-200 rounded-lg px-4 py-2 text-sm">
            <option value="">Semua Tipe</option>
            <option value="application_received" {{ request('type') === 'application_received' ? 'selected' : '' }}>Lamaran Diterima</option>
            <option value="accepted" {{ request('type') === 'accepted' ? 'selected' : '' }}>Diterima</option>
            <option value="rejected" {{ request('type') === 'rejected' ? 'selected' : '' }}>Ditolak</option>
        </select>
        <select name="job_id" class="border border-gray-200 rounded-lg px-4 py-2 text-sm">
            <option value="">Semua Lowongan</option>
            @foreach($jobs as $job)
                <option value="{{ $job->id }}" {{ request('job_id') == $job->id ? 'selected' : '' }}>{{ $job->title }}</option>
            @endforeach
        </select>
        <button class="bg-gray-100 text-gray-600 px-4 py-2 rounded-lg text-sm hover:outline hover:outline-2 hover:outline-gray-400">Filter</button>
    </form>
</div>

{{-- Queue Table --}}
<div class="bg-white rounded-xl border border-gray-100 overflow-x-auto">
    <table class="w-full min-w-[700px]">
        <thead>
            <tr class="bg-gray-50 border-b border-gray-100">
                <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase">Pelamar</th>
                <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase">Lowongan</th>
                <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase">Tipe</th>
                <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase">Channel</th>
                <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase">Dijadwalkan</th>
                <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase">Countdown</th>
                <th class="text-center px-6 py-3 text-xs font-medium text-gray-500 uppercase">Aksi</th>
            </tr>
        </thead>
        <tbody class="divide-y divide-gray-50">
            @forelse($pendingLogs as $log)
            <tr data-log-row="{{ $log->id }}" class="hover:bg-gray-50">
                <td class="px-6 py-3">
                    <div class="text-sm font-medium text-gray-800">{{ $log->recipient_name ?? ($log->application->applicant->name ?? 'N/A') }}</div>
                    <div class="text-xs text-gray-400">{{ $log->recipient_contact ?? '' }}</div>
                </td>
                <td class="px-6 py-3 text-sm text-gray-600">
                    {{ $log->application->jobListing->title ?? '-' }}
                </td>
                <td class="px-6 py-3">
                    <span class="text-xs px-2 py-1 rounded-full bg-gray-100 text-gray-700">{{ $log->type }}</span>
                </td>
                <td class="px-6 py-3">
                    <span class="text-xs px-2 py-1 rounded-full {{ $log->channel === 'email' ? 'bg-blue-100 text-blue-700' : 'bg-green-100 text-green-700' }}">
                        {{ $log->channel === 'email' ? 'Email' : 'WhatsApp' }}
                    </span>
                </td>
                <td class="px-6 py-3 text-sm text-gray-600">
                    @if($log->scheduled_at)
                        {{ $log->scheduled_at->format('d/m/Y H:i') }}
                    @else
                        <span class="text-gray-400">-</span>
                    @endif
                </td>
                <td class="px-6 py-3 text-sm">
                    @if($log->scheduled_at)
                        <span class="js-queue-countdown {{ $log->scheduled_at->isPast() ? 'text-blue-600 font-medium' : 'text-gray-500' }}" data-log-id="{{ $log->id }}" data-scheduled-at="{{ $log->scheduled_at->toIso8601String() }}">
                            {{ $log->scheduled_at->isPast() ? 'Mengirim...' : $log->scheduled_at->diffForHumans() }}
                        </span>
                    @endif
                </td>
                <td class="px-6 py-3 text-center">
                    <div class="flex items-center justify-center gap-1">
                        {{-- Send Now --}}
                        <form action="{{ route('admin.notifications.send-now', $log) }}" method="POST" class="inline" onsubmit="return confirm('Kirim notifikasi ini sekarang?')">
                            @csrf
                            <button class="text-indigo-600 hover:text-indigo-800 p-1 rounded hover:bg-indigo-50" title="Kirim Sekarang">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"/></svg>
                            </button>
                        </form>

                        {{-- Reschedule --}}
                        <button onclick="openReschedule({{ $log->id }}, '{{ $log->scheduled_at?->format('Y-m-d\TH:i') }}')" class="text-yellow-600 hover:text-yellow-800 p-1 rounded hover:bg-yellow-50" title="Ubah Jadwal">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                        </button>

                        {{-- Cancel --}}
                        <form action="{{ route('admin.notifications.cancel', $log) }}" method="POST" class="inline" onsubmit="return confirm('Batalkan notifikasi ini?')">
                            @csrf
                            <button class="text-red-500 hover:text-red-700 p-1 rounded hover:bg-red-50" title="Batalkan">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                            </button>
                        </form>
                    </div>
                </td>
            </tr>
            @empty
            <tr>
                <td colspan="7" class="px-6 py-12 text-center text-gray-400">
                    <svg class="w-12 h-12 mx-auto mb-3 text-gray-300" fill="none" stroke="currentColor" stroke-width="1" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    Tidak ada notifikasi yang dijadwalkan
                </td>
            </tr>
            @endforelse
        </tbody>
    </table>
</div>

<div class="mt-6">{{ $pendingLogs->appends(request()->query())->links('pagination') }}</div>

{{-- Reschedule Modal --}}
<div id="rescheduleModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center">
    <div class="bg-white rounded-xl p-6 w-full max-w-md mx-4">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Ubah Jadwal Notifikasi</h3>
        <form id="rescheduleForm" method="POST">
            @csrf
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">Jadwal Baru</label>
                <input type="datetime-local" name="scheduled_at" id="rescheduleInput" class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm" required>
            </div>
            <div class="flex justify-end gap-2">
                <button type="button" onclick="closeReschedule()" class="px-4 py-2 text-sm text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200">Batal</button>
                <button type="submit" class="px-4 py-2 text-sm text-white bg-indigo-600 rounded-lg hover:bg-indigo-700">Simpan</button>
            </div>
        </form>
    </div>
</div>

@endsection

@push('scripts')
<script>
function openReschedule(id, currentDate) {
    document.getElementById('rescheduleModal').classList.remove('hidden');
    document.getElementById('rescheduleInput').value = currentDate || '';
    document.getElementById('rescheduleForm').action = '/admin/notifications/' + id + '/reschedule';
}

function closeReschedule() {
    document.getElementById('rescheduleModal').classList.add('hidden');
}

// Close modal on backdrop click
document.getElementById('rescheduleModal').addEventListener('click', function(e) {
    if (e.target === this) closeReschedule();
});

const queueStatsUrl = "{{ route('admin.notifications.queue-stats') }}";
const sendAllDueUrl = "{{ route('admin.notifications.send-all-due') }}";
const csrfToken = "{{ csrf_token() }}";
const AUTO_SEND_COOLDOWN_MS = 8000;

let latestDueNow = {{ (int) $stats['due_now'] }};
let latestTotalScheduled = {{ (int) $stats['total_scheduled'] }};
let autoSendInProgress = false;
let lastAutoSendAt = 0;

function formatRemainingTime(remainingMs) {
    const totalSeconds = Math.max(0, Math.floor(remainingMs / 1000));

    if (totalSeconds < 60) {
        return `${totalSeconds} detik lagi`;
    }

    const totalMinutes = Math.floor(totalSeconds / 60);
    if (totalMinutes < 60) {
        return `${totalMinutes} menit lagi`;
    }

    const totalHours = Math.floor(totalMinutes / 60);
    if (totalHours < 24) {
        return `${totalHours} jam lagi`;
    }

    const totalDays = Math.floor(totalHours / 24);
    return `${totalDays} hari lagi`;
}

function updateDueNowWidget(dueCount) {
    const dueNowCount = document.getElementById('dueNowCount');
    const dueNowIconWrap = document.getElementById('dueNowIconWrap');
    const dueNowIcon = document.getElementById('dueNowIcon');
    const hasDue = dueCount > 0;

    if (dueNowCount) {
        dueNowCount.textContent = String(dueCount);
        dueNowCount.className = `text-2xl font-bold mt-1 ${hasDue ? 'text-orange-600' : 'text-gray-400'}`;
    }

    if (dueNowIconWrap) {
        dueNowIconWrap.className = `w-10 h-10 rounded-lg flex items-center justify-center ${hasDue ? 'bg-orange-100' : 'bg-gray-50'}`;
    }

    if (dueNowIcon) {
        dueNowIcon.className = `w-5 h-5 ${hasDue ? 'text-orange-500' : 'text-gray-400'}`;
    }
}

function renderCountdowns() {
    const countdowns = document.querySelectorAll('.js-queue-countdown[data-scheduled-at]');
    const nowMs = Date.now();
    let visibleDueCount = 0;

    countdowns.forEach((node) => {
        const scheduledAt = node.dataset.scheduledAt;
        const targetMs = Date.parse(scheduledAt);

        if (!scheduledAt || Number.isNaN(targetMs)) {
            return;
        }

        const row = node.closest('tr');
        const remainingMs = targetMs - nowMs;

        if (remainingMs <= 0) {
            visibleDueCount++;
            node.textContent = autoSendInProgress ? 'Mengirim...' : 'Siap diproses...';
            node.classList.remove('text-gray-500', 'text-orange-600');
            node.classList.add('text-blue-600', 'font-medium');
            if (row) {
                row.classList.remove('bg-orange-50');
                row.classList.add('bg-blue-50');
            }
            return;
        }

        node.textContent = formatRemainingTime(remainingMs);
        node.classList.remove('text-orange-600', 'text-blue-600', 'font-medium');
        node.classList.add('text-gray-500');
    });

    return visibleDueCount;
}

function markDueRowsAsProcessing() {
    const countdowns = document.querySelectorAll('.js-queue-countdown[data-scheduled-at]');
    const nowMs = Date.now();

    countdowns.forEach((node) => {
        const targetMs = Date.parse(node.dataset.scheduledAt);
        if (Number.isNaN(targetMs) || targetMs > nowMs) {
            return;
        }

        node.textContent = 'Mengirim...';
        node.classList.remove('text-gray-500', 'text-orange-600');
        node.classList.add('text-blue-600', 'font-medium');

        const row = node.closest('tr');
        if (row) {
            row.classList.remove('bg-orange-50');
            row.classList.add('bg-blue-50', 'opacity-80');
        }
    });
}

function hideDueRowsTemporarily() {
    const countdowns = document.querySelectorAll('.js-queue-countdown[data-scheduled-at]');
    const nowMs = Date.now();

    countdowns.forEach((node) => {
        const targetMs = Date.parse(node.dataset.scheduledAt);
        if (Number.isNaN(targetMs) || targetMs > nowMs) {
            return;
        }

        const row = node.closest('tr');
        if (row) {
            row.style.display = 'none';
        }
    });
}

function canTriggerAutoSend() {
    const now = Date.now();
    return !autoSendInProgress && (now - lastAutoSendAt) >= AUTO_SEND_COOLDOWN_MS;
}

async function triggerAutoSend(dueCount) {
    if (dueCount <= 0 || !canTriggerAutoSend()) {
        return;
    }

    autoSendInProgress = true;
    lastAutoSendAt = Date.now();
    markDueRowsAsProcessing();

    try {
        const response = await fetch(sendAllDueUrl, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': csrfToken,
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            },
        });

        if (!response.ok) {
            return;
        }

        const payload = await response.json();
        if ((payload.due_count ?? 0) > 0) {
            hideDueRowsTemporarily();
            updateDueNowWidget(0);
            setTimeout(() => window.location.reload(), 1200);
        }
    } catch (error) {
        console.error('Auto send gagal dipicu:', error);
    } finally {
        autoSendInProgress = false;
    }
}

async function refreshQueueStats() {
    try {
        const response = await fetch(queueStatsUrl, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            },
        });

        if (!response.ok) {
            return;
        }

        const stats = await response.json();
        const totalScheduled = Number(stats.total_scheduled ?? 0);
        latestDueNow = Number(stats.due_now ?? 0);

        // Refresh page when queue size changes to keep table clean without manual reload.
        if (totalScheduled !== latestTotalScheduled) {
            window.location.reload();
            return;
        }

        latestTotalScheduled = totalScheduled;
        updateDueNowWidget(latestDueNow);

        if (latestDueNow > 0) {
            await triggerAutoSend(latestDueNow);
        }
    } catch (error) {
        console.error('Gagal memuat stats queue:', error);
    }
}

function tickQueueCountdown() {
    const visibleDueCount = renderCountdowns();

    if (visibleDueCount > latestDueNow) {
        latestDueNow = visibleDueCount;
        updateDueNowWidget(latestDueNow);
    }

    if (visibleDueCount > 0) {
        triggerAutoSend(visibleDueCount);
    }
}

document.addEventListener('DOMContentLoaded', function () {
    updateDueNowWidget(latestDueNow);
    tickQueueCountdown();

    // Keep countdown moving in realtime
    setInterval(tickQueueCountdown, 1000);

    // Poll queue stats so due items outside current table page are still detected
    setInterval(refreshQueueStats, 5000);

    // Trigger immediately when page opens and there are due notifications
    if (latestDueNow > 0) {
        triggerAutoSend(latestDueNow);
    }
});
</script>
@endpush
