<x-app-layout>
    @section('title', 'Data Resep')

    <div class="space-y-6">
        <!-- Header -->
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-[#2F347A]">Data Resep</h1>
            </div>
            @if(auth()->user()->canManageResep())
                <x-btn type="primary" href="{{ route('resep.create') }}">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
                    </svg>
                    Tambah Resep
                </x-btn>
            @endif
        </div>

        <!-- Success Message -->
        @if(session('success'))
            <div class="bg-[#C9F7E3] border border-[#1F9254] text-[#1F9254] px-4 py-3 rounded-lg">
                {{ session('success') }}
            </div>
        @endif

        <!-- Error Message -->
        @if($errors->any())
            <div class="bg-[#FFD6D6] border border-[#C0392B] text-[#C0392B] px-4 py-3 rounded-lg">
                @foreach($errors->all() as $error)
                    <p>{{ $error }}</p>
                @endforeach
            </div>
        @endif

        <!-- Filters -->
        <x-card class="p-6">
            <form method="GET" action="{{ route('resep.index') }}" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div class="md:col-span-2">
                    <input type="text" name="search" value="{{ request('search') }}" 
                           placeholder="Cari no resep atau nama pasien..." 
                           class="w-full px-4 py-2.5 border border-[#E5E7F2] rounded-lg focus:ring-2 focus:ring-[#4A538F] focus:border-[#4A538F] text-[#2F347A] placeholder-[#7A7FAE]">
                </div>
                <div>
                    <select name="status" class="w-full px-4 py-2.5 border border-[#E5E7F2] rounded-lg focus:ring-2 focus:ring-[#4A538F] focus:border-[#4A538F] bg-white text-[#2F347A]">
                        <option value="">Semua Status</option>
                        <option value="proses" {{ request('status') == 'proses' ? 'selected' : '' }}>Proses</option>
                        <option value="selesai" {{ request('status') == 'selesai' ? 'selected' : '' }}>Selesai</option>
                        <option value="dibatalkan" {{ request('status') == 'dibatalkan' ? 'selected' : '' }}>Dibatalkan</option>
                    </select>
                </div>
                <div class="flex gap-2">
                    <button type="submit" class="flex-1 px-4 py-2.5 bg-[#4A538F] text-white rounded-lg hover:bg-[#424B84] transition-colors">
                        Filter
                    </button>
                    <a href="{{ route('resep.index') }}" class="px-4 py-2.5 bg-[#E9EBF5] text-[#4A538F] rounded-lg hover:bg-[#d8dce8] transition-colors">
                        Reset
                    </a>
                </div>
            </form>
        </x-card>

        <!-- Table -->
        <x-card class="overflow-hidden">
            <div class="px-6 py-4 table-header-custom">
                <h2 class="text-lg font-semibold">Daftar Resep</h2>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-[#F4F6FF] border-b border-[#E5E7F2]">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-[#7A7FAE] uppercase tracking-wider">No. Resep</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-[#7A7FAE] uppercase tracking-wider">Tanggal</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-[#7A7FAE] uppercase tracking-wider">Nama Pasien</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-[#7A7FAE] uppercase tracking-wider">Dokter</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-[#7A7FAE] uppercase tracking-wider">Jumlah Obat</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-[#7A7FAE] uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-[#7A7FAE] uppercase tracking-wider">Aksi</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-[#E5E7F2]">
                        @forelse($reseps as $resep)
                            <tr class="hover:bg-[#F4F6FF]">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="font-medium text-[#2F347A]">{{ $resep->no_resep }}</div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-[#7A7FAE]">
                                    {{ $resep->tanggal_resep->format('d M Y') }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="font-medium text-[#2F347A] flex items-center gap-2">
                                        {{ $resep->nama_pasien }}
                                        @if(auth()->user()->isApoteker() && !$resep->is_read)
                                            <span class="inline-block w-2 h-2 rounded-full bg-red-500"></span>
                                        @endif
                                    </div>
                                    @if($resep->umur_pasien)
                                        <div class="text-sm text-[#7A7FAE]">{{ $resep->umur_pasien }} tahun</div>
                                    @endif
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-[#7A7FAE]">
                                    {{ $resep->user->name ?? 'N/A' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-[#7A7FAE]">
                                    {{ $resep->items->count() }} item
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <x-badge :type="$resep->status_color">
                                        {{ ucfirst($resep->status) }}
                                    </x-badge>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm" x-data="{ open: false }">
                                    <div class="relative">
                                        <button @click="open = !open" class="p-2 hover:bg-[#E9EBF5] rounded-lg">
                                            <svg class="w-5 h-5 text-[#7A7FAE]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z"/>
                                            </svg>
                                        </button>
                                        <div x-show="open" @click.away="open = false" 
                                             class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-[#E5E7F2] z-10">
                                            <a href="{{ route('resep.show', $resep) }}" class="block px-4 py-2 text-sm text-[#2F347A] hover:bg-[#F4F6FF]">Detail</a>
                                            <a href="{{ route('resep.print', $resep) }}" target="_blank" class="block px-4 py-2 text-sm text-[#2F347A] hover:bg-[#F4F6FF]">Print</a>
                                            @if(auth()->user()->isApoteker() && $resep->status !== 'selesai')
                                                <button onclick="openStatusModal({{ $resep->id }}, '{{ $resep->no_resep }}', '{{ $resep->status }}'); return false;" class="block w-full text-left px-4 py-2 text-sm text-[#4A538F] hover:bg-[#F4F6FF]">
                                                    Edit Status
                                                </button>
                                            @endif
                                            @if(auth()->user()->canManageResep() && $resep->status !== 'selesai')
                                                <a href="{{ route('resep.edit', $resep) }}" class="block px-4 py-2 text-sm text-[#2F347A] hover:bg-[#F4F6FF]">Edit</a>
                                                <form method="POST" action="{{ route('resep.destroy', $resep) }}" 
                                                      onsubmit="return confirm('Yakin ingin menghapus resep ini? Stok obat akan dikembalikan.')">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit" class="block w-full text-left px-4 py-2 text-sm text-[#C0392B] hover:bg-[#FFD6D6]">Hapus</button>
                                                </form>
                                            @endif
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="7" class="px-6 py-12 text-center text-[#7A7FAE]">
                                    Belum ada data resep
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            <div class="px-6 py-4 border-t border-[#E5E7F2]">
                {{ $reseps->withQueryString()->links() }}
            </div>
        </x-card>
    </div>

    {{-- Global Status Modal (Pure JavaScript - No Alpine.js) --}}
    @if(auth()->user()->isApoteker())
    <div id="statusModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 9999;">
        {{-- Backdrop - Semi-transparent overlay --}}
        <div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5);" onclick="closeStatusModal()"></div>
        
        {{-- Modal Content --}}
        <div style="position: relative; z-index: 10000; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 1rem;">
            <div class="relative bg-white rounded-lg shadow-xl w-full max-w-md">
                <form id="statusForm" method="POST">
                    @csrf
                    @method('PATCH')
                    <div class="px-6 pt-5 pb-4">
                        <h3 class="text-lg font-semibold text-[#2F347A] mb-4">
                            Update Status Resep: <span id="modalResepNo"></span>
                        </h3>
                        <label class="block text-sm font-medium text-[#2F347A] mb-2">Status</label>
                        <select name="status" id="modalStatus" class="w-full px-4 py-2.5 border border-[#E5E7F2] rounded-lg focus:ring-2 focus:ring-[#4A538F] focus:border-[#4A538F] bg-white text-[#2F347A]">
                            <option value="proses">Proses</option>
                            <option value="selesai">Selesai</option>
                            <option value="dibatalkan">Dibatalkan</option>
                        </select>
                    </div>
                    <div class="bg-gray-50 px-6 py-3 flex justify-end gap-3 rounded-b-lg">
                        <button type="button" onclick="closeStatusModal()" class="px-4 py-2 border border-[#E5E7F2] rounded-lg text-sm font-medium text-[#7A7FAE] hover:bg-gray-50">
                            Batal
                        </button>
                        <button type="submit" class="px-4 py-2 bg-[#4A538F] text-white rounded-lg text-sm font-medium hover:bg-[#424B84]">
                            Update
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        console.log('Status modal script loaded');
        
        function openStatusModal(resepId, noResep, currentStatus) {
            console.log('openStatusModal called', { resepId, noResep, currentStatus });
            
            try {
                const modal = document.getElementById('statusModal');
                const form = document.getElementById('statusForm');
                const modalResepNo = document.getElementById('modalResepNo');
                const modalStatus = document.getElementById('modalStatus');
                
                console.log('Elements found:', { 
                    modal: !!modal, 
                    form: !!form, 
                    modalResepNo: !!modalResepNo, 
                    modalStatus: !!modalStatus 
                });
                
                if (!modal) {
                    alert('ERROR: Modal element not found! Please contact admin.');
                    return;
                }
                
                // Set form action
                form.action = '{{ url("resep") }}/' + resepId + '/update-status';
                console.log('Form action set to:', form.action);
                
                // Set modal content
                modalResepNo.textContent = noResep;
                modalStatus.value = currentStatus;
                
                // Show modal
                modal.style.display = 'block';
                console.log('Modal should now be visible');
            } catch (error) {
                console.error('Error in openStatusModal:', error);
                alert('ERROR: ' + error.message);
            }
        }

        function closeStatusModal() {
            console.log('closeStatusModal called');
            try {
                const modal = document.getElementById('statusModal');
                if (modal) {
                    modal.style.display = 'none';
                    console.log('Modal closed');
                }
            } catch (error) {
                console.error('Error in closeStatusModal:', error);
            }
        }

        // Close on ESC key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeStatusModal();
            }
        });
        
        // Verify modal exists on page load
        document.addEventListener('DOMContentLoaded', function() {
            const modal = document.getElementById('statusModal');
            console.log('Page loaded. Modal exists:', !!modal);
        });
    </script>
    @endif
</x-app-layout>
