@extends('layouts.admin')

@section('title', 'Edit Tahap: ' . $stage->name)

@section('content')
<div class="max-w-4xl">
    <a href="{{ route('admin.jobs.stages.index', $job) }}" class="text-indigo-600 hover:text-indigo-800 text-sm font-medium">← Kembali ke Tahapan</a>
    <p class="text-sm text-gray-500 mt-1">Lowongan: <strong>{{ $job->title }}</strong></p>

    <div class="bg-white rounded-xl border border-gray-100 p-8 mt-4">
        <form action="{{ route('admin.jobs.stages.update', [$job, $stage]) }}"
            method="POST" id="stageForm">
            @csrf
            @method('PUT')

            <div class="space-y-5">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Nomor Tahap *</label>
                        <input type="number" name="stage_number" min="1"
                            value="{{ old('stage_number', $stage->stage_number) }}"
                            readonly
                            class="w-full border border-gray-200 rounded-lg px-4 py-3 focus:ring-2 focus:ring-indigo-500 outline-none bg-gray-50">
                        @error('stage_number') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Nama Tahap *</label>
                        <input type="text" name="name" value="{{ old('name', $stage->name) }}" required
                            placeholder="contoh: Seleksi Administrasi, Tes Kemampuan, dll"
                            class="w-full border border-gray-200 rounded-lg px-4 py-3 focus:ring-2 focus:ring-indigo-500 outline-none">
                        @error('name') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Deskripsi (Opsional)</label>
                    <textarea name="description" rows="2"
                        placeholder="Penjelasan tentang tahap ini untuk pelamar"
                        class="w-full border border-gray-200 rounded-lg px-4 py-3 focus:ring-2 focus:ring-indigo-500 outline-none">{{ old('description', $stage->description) }}</textarea>
                </div>

                <div class="flex items-center">
                    <label class="flex items-center space-x-3">
                        <input type="checkbox" name="is_active" value="1"
                            {{ old('is_active', $stage->is_active) ? 'checked' : '' }}
                            class="w-4 h-4 text-indigo-600 rounded focus:ring-indigo-500">
                        <span class="text-sm font-medium text-gray-700">Aktif</span>
                    </label>
                </div>

                {{-- Dynamic Form Fields Builder --}}
                <div class="border-t border-gray-100 pt-5">
                    <div class="flex items-center justify-between mb-4">
                        <div>
                            <h3 class="text-sm font-semibold text-gray-800">Field Formulir</h3>
                            <p class="text-xs text-gray-500 mt-0.5">Atur field yang harus diisi pelamar pada tahap ini. Kosongkan jika tahap ini hanya seleksi admin.</p>
                        </div>
                        <button type="button" onclick="addField()"
                            class="bg-green-50 text-green-600 px-4 py-2 rounded-lg text-sm font-medium hover:outline hover:outline-2 hover:outline-green-300">
                            + Tambah Field
                        </button>
                    </div>

                    <div id="fieldsContainer" class="space-y-3">
                        {{-- Fields will be rendered here by JavaScript --}}
                    </div>

                    <input type="hidden" name="form_fields" id="formFieldsInput">
                </div>
            </div>

            <div class="flex items-center space-x-3 mt-8">
                <button type="submit" onclick="prepareSubmit()"
                    class="bg-indigo-600 text-white px-6 py-2.5 rounded-lg font-medium hover:outline hover:outline-2 hover:outline-indigo-800">
                    {{ 'Simpan Perubahan' }}
                </button>
                <a href="{{ route('admin.jobs.stages.index', $job) }}" class="text-gray-500 hover:text-gray-700 font-medium">Batal</a>
            </div>
        </form>
    </div>
</div>

<script>
let fields = @json($stage->form_fields ? $stage->form_fields : []);
let fieldIndex = 0;

function renderFields() {
    const container = document.getElementById('fieldsContainer');
    container.innerHTML = '';

    if (fields.length === 0) {
        container.innerHTML = '<div class="text-center py-6 bg-gray-50 rounded-lg text-sm text-gray-400">Tidak ada field formulir. Tahap ini hanya berupa seleksi admin.</div>';
        return;
    }

    fields.forEach((field, index) => {
        const optionsHtml = (field.type === 'select' || field.type === 'radio' || field.type === 'checkbox')
            ? `<div class="mt-2">
                <label class="block text-xs text-gray-500 mb-1">Opsi (pisahkan dengan koma)</label>
                <input type="text" value="${(field.options || []).join(', ')}"
                    onchange="updateFieldOptions(${index}, this.value)"
                    placeholder="Opsi 1, Opsi 2, Opsi 3"
                    class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
               </div>`
            : '';

        container.innerHTML += `
        <div class="p-4 bg-gray-50 rounded-xl border border-gray-200 relative" id="field_${index}">
            <button type="button" onclick="removeField(${index})"
                class="absolute top-2 right-2 text-red-400 hover:text-red-600 text-lg font-bold">&times;</button>
            <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3">
                <div>
                    <label class="block text-xs text-gray-500 mb-1">Nama Field *</label>
                    <input type="text" value="${field.name || ''}"
                        onchange="updateField(${index}, 'name', this.value)"
                        placeholder="nama_field"
                        class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                </div>
                <div>
                    <label class="block text-xs text-gray-500 mb-1">Label *</label>
                    <input type="text" value="${field.label || ''}"
                        onchange="updateField(${index}, 'label', this.value)"
                        placeholder="Label untuk User"
                        class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                </div>
                <div>
                    <label class="block text-xs text-gray-500 mb-1">Tipe</label>
                    <select onchange="updateField(${index}, 'type', this.value); renderFields()"
                        class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                        ${['text','textarea','number','email','tel','select','radio','checkbox','date','file'].map(t =>
                            `<option value="${t}" ${field.type === t ? 'selected' : ''}>${t}</option>`
                        ).join('')}
                    </select>
                </div>
                <div class="flex items-end">
                    <label class="flex items-center space-x-2 py-2">
                        <input type="checkbox" ${field.required ? 'checked' : ''}
                            onchange="updateField(${index}, 'required', this.checked)"
                            class="w-4 h-4 text-indigo-600 rounded focus:ring-indigo-500">
                        <span class="text-sm text-gray-600">Wajib</span>
                    </label>
                </div>
            </div>
            ${optionsHtml}
        </div>`;
    });
}

function addField() {
    fields.push({
        name: '',
        label: '',
        type: 'text',
        required: false,
        options: []
    });
    renderFields();
}

function removeField(index) {
    fields.splice(index, 1);
    renderFields();
}

function updateField(index, key, value) {
    fields[index][key] = value;
}

function updateFieldOptions(index, value) {
    fields[index].options = value.split(',').map(s => s.trim()).filter(Boolean);
}

function prepareSubmit() {
    // Clean empty fields
    const validFields = fields.filter(f => f.name && f.label);
    document.getElementById('formFieldsInput').value = validFields.length > 0 ? JSON.stringify(validFields) : '';
}

// Initialize
renderFields();

document.getElementById('stageForm').addEventListener('submit', function(e) {
    prepareSubmit();
});
</script>
@endsection
