@extends('layouts.admin')

@section('title', 'Kelola Lowongan')

@section('content')
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
    <form action="{{ route('admin.jobs.index') }}" method="GET" class="flex flex-wrap items-center gap-2">
        <input type="text" name="search" value="{{ request('search') }}" placeholder="Cari lowongan..."
            class="border border-gray-200 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-indigo-500 outline-none w-full sm:w-64">
        <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">Cari</button>
    </form>
    <a href="{{ route('admin.jobs.create') }}" class="bg-indigo-600 text-white px-5 py-2.5 rounded-lg text-sm font-medium hover:outline hover:outline-2 hover:outline-indigo-800">
        + Tambah Lowongan
    </a>
</div>

<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">Posisi</th>
                <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase">Perusahaan</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">Gaji</th>
                <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase">Status</th>
                <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase">Lamaran</th>
                <th class="text-right px-6 py-3 text-xs font-medium text-gray-500 uppercase">Aksi</th>
            </tr>
        </thead>
        <tbody class="divide-y divide-gray-50">
            @forelse($jobs as $job)
            <tr class="hover:bg-gray-50">
                <td class="px-6 py-4">
                    <p class="font-medium text-gray-800">{{ $job->title }}</p>
                    <p class="text-xs text-gray-400">{{ $job->location }}</p>
                </td>
                <td class="px-6 py-4 text-sm text-gray-600">{{ $job->company }}</td>
                <td class="px-6 py-4">
                    <span class="text-xs font-medium px-2 py-1 rounded-full bg-blue-100 text-blue-700">{{ $job->type }}</span>
                </td>
                <td class="px-6 py-4 text-sm text-green-600 font-medium">{{ $job->formatted_salary }}</td>
                <td class="px-6 py-4">
                    <span class="inline-block w-2 h-2 rounded-full {{ $job->is_active ? 'bg-green-500' : 'bg-gray-300' }}"></span>
                    <span class="text-xs text-gray-500 ml-1">{{ $job->is_active ? 'Aktif' : 'Nonaktif' }}</span>
                </td>
                <td class="px-6 py-4 text-sm text-gray-600">{{ $job->applications_count ?? $job->applications()->count() }}</td>
                <td class="px-6 py-4 text-right space-x-2">
                    <a href="{{ route('admin.jobs.edit', $job) }}" class="text-indigo-600 hover:text-indigo-800 text-sm font-medium">Edit</a>
                    <form action="{{ route('admin.jobs.copy', $job) }}" method="POST" class="inline" id="copy-job-form-{{ $job->id }}">
                        @csrf
                        <input type="hidden" name="company" value="">
                        <button
                            type="button"
                            data-copy-job-trigger
                            data-job-id="{{ $job->id }}"
                            data-job-title="{{ $job->title }}"
                            data-job-company="{{ $job->company }}"
                            class="text-emerald-600 hover:text-emerald-800 text-sm font-medium"
                        >
                            Copy
                        </button>
                    </form>
                    <form action="{{ route('admin.jobs.destroy', $job) }}" method="POST" class="inline" onsubmit="return confirm('Yakin hapus lowongan ini?')">
                        @csrf @method('DELETE')
                        <button class="text-red-600 hover:text-red-800 text-sm font-medium">Hapus</button>
                    </form>
                </td>
            </tr>
            @empty
            <tr>
                <td colspan="7" class="px-6 py-12 text-center text-gray-400">Belum ada lowongan</td>
            </tr>
            @endforelse
        </tbody>
    </table>
</div>

<div class="mt-6">{{ $jobs->links('pagination') }}</div>

<div id="copy-job-modal" class="fixed inset-0 z-50 hidden" aria-hidden="true">
    <div class="absolute inset-0 bg-black/40" data-close-copy-modal></div>
    <div class="relative min-h-full flex items-center justify-center p-4">
        <div class="w-full max-w-md bg-white border border-gray-100 rounded-xl shadow-xl">
            <div class="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
                <h3 class="text-base font-semibold text-gray-800">Copy Lowongan</h3>
                <button type="button" data-close-copy-modal class="text-gray-400 hover:text-gray-600 text-lg leading-none">&times;</button>
            </div>
            <form id="copy-job-modal-form" class="p-5 space-y-4">
                <div class="bg-gray-50 border border-gray-100 rounded-lg px-3 py-2 text-sm text-gray-600 space-y-1">
                    <p>Lowongan: <span id="copy-job-current-title" class="font-medium text-gray-800">-</span></p>
                    <p>Perusahaan asal: <span id="copy-job-current-company" class="font-medium text-gray-800">-</span></p>
                </div>

                <div>
                    <label for="copy-job-company-input" class="block text-sm font-medium text-gray-700 mb-1">Nama perusahaan baru</label>
                    <input
                        id="copy-job-company-input"
                        type="text"
                        class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 outline-none"
                        placeholder="Contoh: PT Nusantara Sejahtera"
                        autocomplete="off"
                    >
                    <p class="mt-1 text-xs text-gray-500">Lowongan hasil copy akan langsung dibuat dan diarahkan ke halaman edit.</p>
                    <p id="copy-job-modal-error" class="hidden mt-2 text-sm text-red-600"></p>
                </div>

                <div class="flex items-center justify-end gap-2 pt-2">
                    <button type="button" data-close-copy-modal class="px-4 py-2 text-sm rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50">Batal</button>
                    <button type="submit" class="px-4 py-2 text-sm rounded-lg bg-emerald-600 text-white font-medium hover:bg-emerald-700">Copy Lowongan</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    (function () {
        var modal = document.getElementById('copy-job-modal');
        var modalForm = document.getElementById('copy-job-modal-form');
        var titleEl = document.getElementById('copy-job-current-title');
        var companyEl = document.getElementById('copy-job-current-company');
        var companyInputEl = document.getElementById('copy-job-company-input');
        var errorEl = document.getElementById('copy-job-modal-error');
        var submitButton = modalForm ? modalForm.querySelector('button[type="submit"]') : null;

        if (!modal || !modalForm || !titleEl || !companyEl || !companyInputEl || !errorEl || !submitButton) {
            return;
        }

        var selectedCopyJobId = null;
        var selectedCopyJobCompany = '';
        var initialSubmitLabel = submitButton.textContent;

        function openModal(jobId, jobTitle, currentCompany) {
            selectedCopyJobId = jobId;
            selectedCopyJobCompany = currentCompany ? String(currentCompany).trim() : '';

            titleEl.textContent = jobTitle ? String(jobTitle).trim() : '-';
            companyEl.textContent = selectedCopyJobCompany || '-';
            companyInputEl.value = '';
            clearError();

            modal.classList.remove('hidden');
            modal.setAttribute('aria-hidden', 'false');

            setTimeout(function () {
                companyInputEl.focus();
            }, 50);
        }

        function closeModal() {
            modal.classList.add('hidden');
            modal.setAttribute('aria-hidden', 'true');

            companyInputEl.value = '';
            clearError();
            setSubmitLoading(false);

            selectedCopyJobId = null;
            selectedCopyJobCompany = '';
        }

        function setSubmitLoading(isLoading) {
            submitButton.disabled = isLoading;
            submitButton.classList.toggle('opacity-60', isLoading);
            submitButton.classList.toggle('cursor-not-allowed', isLoading);
            submitButton.textContent = isLoading ? 'Memproses...' : initialSubmitLabel;
        }

        function showError(message) {
            errorEl.textContent = message;
            errorEl.classList.remove('hidden');
        }

        function clearError() {
            errorEl.textContent = '';
            errorEl.classList.add('hidden');
        }

        function validateCompany(company) {
            if (!company) {
                return 'Nama perusahaan wajib diisi.';
            }

            if (selectedCopyJobCompany && company.toLowerCase() === selectedCopyJobCompany.toLowerCase()) {
                return 'Nama perusahaan harus berbeda dari lowongan asal.';
            }

            return null;
        }

        document.addEventListener('click', function (event) {
            var trigger = event.target.closest('[data-copy-job-trigger]');
            if (trigger) {
                event.preventDefault();

                var jobId = trigger.getAttribute('data-job-id');
                var jobTitle = trigger.getAttribute('data-job-title');
                var jobCompany = trigger.getAttribute('data-job-company');

                openModal(jobId, jobTitle, jobCompany);
                return;
            }

            if (event.target.matches('[data-close-copy-modal]')) {
                event.preventDefault();
                closeModal();
            }
        });

        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape' && !modal.classList.contains('hidden')) {
                closeModal();
            }
        });

        modalForm.addEventListener('submit', function (event) {
            event.preventDefault();

            clearError();

            var company = companyInputEl.value.trim();
            var validationError = validateCompany(company);

            if (validationError) {
                showError(validationError);
                return;
            }

            if (!selectedCopyJobId) {
                showError('Lowongan yang akan dicopy tidak valid. Muat ulang halaman lalu coba lagi.');
                return;
            }

            var targetForm = document.getElementById('copy-job-form-' + selectedCopyJobId);
            if (!targetForm) {
                showError('Form copy tidak ditemukan. Muat ulang halaman lalu coba lagi.');
                return;
            }

            var hiddenCompanyInput = targetForm.querySelector('input[name="company"]');
            if (!hiddenCompanyInput) {
                showError('Input perusahaan tidak ditemukan. Muat ulang halaman lalu coba lagi.');
                return;
            }

            hiddenCompanyInput.value = company;
            setSubmitLoading(true);
            targetForm.submit();
        });
    })();
</script>
@endpush
