<x-layout>
    <div class="mb-4">
        <h2 class="text-xl font-semibold text-white">Add Maintenance</h2>
    </div>
    <div class="bg-slate-800 rounded-md shadow-lg border-t-4 border-t-indigo-500 max-w-full">
        <form action="{{ route('maintenance.update', $mntData->mnt_num) }}" method="POST" enctype="multipart/form-data" id="maintenanceForm">
            @method('PUT')
            @csrf
            
            <div class="pt-3 pb-6 px-6 space-y-4">
                <div class="">
                    <div>
                        <label for="unit_name" class="block text-sm font-medium text-slate-300 mb-2">
                            Unit<span class="text-red-400">*</span>
                        </label>
                        <input type="hidden" name="unit_code" id="unit_code" value="{{ $mntData->unit_code }}">
                        <input type="text" name="unit_name" id="unit_name" value="{{ $mntData->unit_code . ' - ' . $mntData->unit->unit_name }}"
                            class="block w-full rounded-sm border border-slate-700 bg-slate-900/50 py-2.5 px-3 text-white placeholder:text-slate-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors cursor-not-allowed" readonly>
                        @error('unit_name')
                            <span class="text-red-400 text-xs italic mt-1 block">{{ $message }}</span>
                        @enderror
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-4 gap-6">
    
                    <!-- Field Maintenance Code (50% atau 2 dari 4 kolom) -->
                    <div class="sm:col-span-2">
                        <label for="mnt_code" class="block text-sm font-medium text-slate-300 mb-2">
                            Maintenance Code <span class="text-red-400">*</span>
                        </label>
                        <input type="hidden" name="mnt_num" value="{{ $mntData->mnt_num }}">
                        <input type="text" name="mnt_code" id="mnt_code" value="{{ $mntData->mnt_code }}"
                            class="block w-full rounded-sm border border-slate-700 bg-slate-900/50 py-2.5 px-3 text-white placeholder:text-slate-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors cursor-not-allowed" readonly>
                        @error('mnt_code')
                            <span class="text-red-400 text-xs italic mt-1 block">{{ $message }}</span>
                        @enderror
                    </div>

                    <!-- Field Step (25% atau 1 dari 4 kolom) -->
                    <div class="sm:col-span-1">
                        <label for="step" class="block text-sm font-medium text-slate-300 mb-2">
                            Step <span class="text-red-400">*</span>
                        </label>
                        <input type="text" name="step" id="step" placeholder="Contoh: Step 1" value="{{ $mntData->step }}"
                            class="block w-full rounded-sm border border-slate-700 bg-slate-900/50 py-2.5 px-3 text-white placeholder:text-slate-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors cursor-not-allowed" readonly>
                        @error('step')
                            <span class="text-red-400 text-xs italic mt-1 block">{{ $message }}</span>
                        @enderror
                    </div>

                    <!-- Field Date (25% atau 1 dari 4 kolom) -->
                    <div class="sm:col-span-1">
                        <label for="mnt_date" class="block text-sm font-medium text-slate-300 mb-2">
                            Date <span class="text-red-400">*</span>
                        </label>
                        <!-- Tambahin class "datepicker" di sini -->
                        <input type="text" name="mnt_date" id="mnt_date" placeholder="Pilih Tanggal..." value="{{ $mntData->mnt_date }}"
                            class="datepicker block w-full rounded-sm border border-slate-600 bg-slate-900 py-2.5 px-3 text-white placeholder:text-slate-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors">
                        @error('mnt_date')
                            <span class="text-red-400 text-xs italic mt-1 block">{{ $message }}</span>
                        @enderror
                    </div>

                </div>
                <!-- Field Maintenance Description (Dibuat full width mengambil 2 kolom) -->
                <div class="sm:col-span-2">
                    <label for="mnt_description" class="block text-sm font-medium text-slate-300 mb-2">
                        Maintenance Description
                    </label>
                    <textarea name="mnt_description" id="mnt_description" rows="4" placeholder="Tuliskan detail deskripsi maintenance..."
                        class="block w-full rounded-sm border border-slate-600 bg-slate-900 py-2.5 px-3 text-white placeholder:text-slate-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors">{{ $mntData->description }}</textarea>
                </div>

                <!-- Field Input File -->
                <div>
                    <label for="file_upload" class="block text-sm font-medium text-slate-300 mb-2">
                        Upload File / Dokumen
                    </label>
                    <!-- Styling khusus input file di Tailwind -->
                    <input type="file" name="file_upload" id="file_upload" accept=".pdf, .PDF"
                        class="block w-full text-sm text-slate-400 file:mr-4 file:py-2.5 file:px-4 file:rounded-sm file:border-0 file:text-sm file:font-semibold file:bg-slate-700 file:text-white hover:file:bg-slate-600 border border-slate-600 bg-slate-900 rounded-sm focus:outline-none transition-colors cursor-pointer">
                    @error('file_upload')
                        <span class="text-red-400 text-xs italic mt-1 block">{{ $message }}</span>
                    @enderror

                    <!-- WADAH FILE YANG SUDAH DIUPLOAD -->
                    <!-- Sesuaikan variabel $mntDoc->upl_filename dengan nama field di database kamu -->
        
                    @if(isset($mntDocs))
                        @foreach ($mntDocs as $mntDoc)
                        <div data-id="" id="attachmentRow" class="mt-3 p-3 flex items-center justify-between bg-slate-900/50 border border-slate-700 rounded-sm">
                            
                            <!-- Info File (Icon & Nama File) -->
                            <div class="flex items-center gap-3 overflow-hidden">
                                <!-- Icon Dokumen / PDF (Warna merah biar ikonik) -->
                                <svg class="w-6 h-6 text-red-500 shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                                    <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.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .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>
                                
                                <!-- Nama File (Pakai truncate biar kalau namanya kepanjangan otomatis jadi "...") -->
                                <span class="text-sm font-medium text-slate-200 truncate" title="{{ $mntDoc->upl_filename }}">
                                    {{ $mntDoc->upl_filename }}
                                </span>
                            </div>

                            <!-- Group Tombol Aksi -->
                            <div class="flex items-center gap-2 shrink-0 pl-3">
                                
                                <!-- Tombol View (Buka di tab baru) -->
                                <!-- Sesuaikan path assetnya dengan struktur folder storage kamu -->
                                <a href="{{ asset('storage/maintenance_files/' . $mntData->unit_code . '/' . $mntDoc->upl_filename) }}" target="_blank" title="View File" 
                                    class="inline-flex items-center justify-center p-1.5 bg-indigo-600 text-white rounded-sm hover:bg-indigo-500 transition-colors">
                                    <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" />
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                    </svg>
                                </a>
                                
                                <!-- Tombol Download (Pake atribut 'download') -->
                                <a href="{{ asset('storage/maintenance_files/' . $mntData->unit_code . '/' . $mntDoc->upl_filename) }}" download title="Download File" 
                                    class="inline-flex items-center justify-center p-1.5 bg-emerald-600 text-white rounded-sm hover:bg-emerald-500 transition-colors">
                                    <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
                                    </svg>
                                </a>

                                <!-- Tombol Delete -->
                                <!-- Pake x-iconpark punyamu biar seragam dengan tombol hapus lain -->
                                <button type="button" onclick="handleClickDelete('{{ $mntDoc->upl_num }}', '{{ $mntDoc->upl_filename }}')" title="Delete File" 
                                    class="inline-flex items-center justify-center p-1.5 bg-red-600 text-white rounded-sm hover:bg-red-500 transition-colors cursor-pointer">
                                    <x-iconpark-delete-o class="h-4 w-4"/>
                                </button>
                                
                            </div>
                        </div>
                        @endforeach
                    @endif
                </div>
            </div>

            <!-- Card Footer -->
            <div class="bg-slate-900/50 border-t border-slate-700 px-6 py-4 flex items-center justify-end gap-3 rounded-b-md">
                
                <!-- Tombol Batal -->
                <a href="/unit/maintenance_list/{{ $mntData['unit_code'] }}" class="inline-flex items-center gap-2 text-sm font-medium bg-slate-700 text-white hover:bg-slate-600 px-4 py-2.5 rounded-sm transition-colors border border-slate-600">
                     <x-iconpark-back class="w-4 h-4" /> Batal
                </a>
                
                <!-- Tombol Simpan -->
                <button type="submit" class="inline-flex items-center gap-2 text-sm font-medium bg-indigo-600 text-white hover:bg-indigo-500 px-4 py-2.5 rounded-sm transition-colors cursor-pointer shadow-sm">
                    <x-iconpark-save class="w-4 h-4" /> Simpan
                </button>
                
            </div>
        </form>
    </div>

    <script>
        function handleClickDelete(upl_num, file_name)
        {
            // Tambahkan config Dark Mode untuk SweetAlert
            const swalDarkConfig = {
                background: '#1e293b', 
                color: '#f8fafc'       
            };

            Swal.fire({
                title: "Are you sure want to delete file "+file_name+"?",
                icon: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                confirmButtonColor: "#d33",
                focusCancel: true,
                ...swalDarkConfig // <-- Terapkan warnanya di sini
                }).then((result) => {
                if (result.isConfirmed){
                    async function deleteUnit(){
                        try {
                            const response      = await fetch('/unit/maintenance_list/maintenance_detail/'+upl_num, {
                                method: 'DELETE',
                                headers: {
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                    'Accept': 'application/json'
                                }
                            });

                            if (!response.ok) {
                                throw new Error(`HTTP error! Status: ${response.status}`);
                            }

                            const data = await response.json();
                            
                            if(data.success){
                                Swal.fire({
                                    title: "Deleted!",
                                    text: "File "+file_name+" has been deleted",
                                    icon: "success",
                                    ...swalDarkConfig // <-- Terapkan juga di alert sukses
                                }).then(() => {
                                    document.getElementById('attachmentRow').remove()
                                });
                            }
                        } catch (error) {
                           console.error('Fetch failed:', error); 
                        }
                    }

                    deleteUnit();
                }
            });
        }

        const form = document.getElementById('maintenanceForm');
        form.addEventListener('submit', (event) => {
            event.preventDefault();

            const swalDarkConfig = {
                background: '#1e293b', 
                color: '#f8fafc'       
            };

            Swal.fire({
                title: "Data saved",
                icon: "success",
                ...swalDarkConfig
            }).then(() => {
                form.submit();
            });
            
        })
    </script>
</x-layout>