{{--
    Admin — Digital Machines Index
    Authenticated page for Manager / Super Manager roles.
    Uses: <x-app-layout> + <x-module-hero>
    Requirements: 8.2, 8.4
--}}
<x-app-layout>

    <x-module-hero
        title="Health Directory — Machines"
        description="Manage and approve digital health equipment listings"
        icon="fa-cogs"
    >
        <x-slot name="tabs">
            @can('manage institutions')
            <a href="{{ route('admin.institutions.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.institutions.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-hospital text-sm"></i> Institutions
            </a>
            @endcan
            @can('manage machines')
            <a href="{{ route('admin.machines.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.machines.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0"
               aria-current="{{ request()->routeIs('admin.machines.*') ? 'page' : 'false' }}">
                <i class="fas fa-cogs text-sm"></i> Machines
            </a>
            @endcan
            @can('view payments')
            <a href="{{ route('admin.payments.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.payments.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-credit-card text-sm"></i> Payments
            </a>
            @endcan
            @can('view pages')
            <a href="{{ route('admin.pages.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.pages.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-file-alt text-sm"></i> Pages
            </a>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-6">

        {{-- Session Messages --}}
        @if(session('success'))
            <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center">
                <i class="fas fa-check-circle mr-3"></i>{{ session('success') }}
            </div>
        @endif
        @if(session('error'))
            <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center">
                <i class="fas fa-exclamation-circle mr-3"></i>{{ session('error') }}
            </div>
        @endif

        {{-- Stats Row --}}
        @can('view statistics')
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                @foreach([
                    ['label' => 'Total',            'value' => $stats['total']     ?? 0, 'icon' => 'fa-cogs',         'color' => 'bg-blue-600'],
                    ['label' => 'Published',         'value' => $stats['published'] ?? 0, 'icon' => 'fa-check-circle', 'color' => 'bg-green-600'],
                    ['label' => 'Pending Approval',  'value' => $stats['pending']   ?? 0, 'icon' => 'fa-clock',        'color' => 'bg-yellow-500'],
                    ['label' => 'Rejected',          'value' => $stats['rejected']  ?? 0, 'icon' => 'fa-times-circle', 'color' => 'bg-red-600'],
                ] as $stat)
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 flex items-center gap-4">
                        <div class="w-12 h-12 {{ $stat['color'] }} rounded-lg flex items-center justify-center flex-shrink-0">
                            <i class="fas {{ $stat['icon'] }} text-white text-lg"></i>
                        </div>
                        <div>
                            <p class="text-2xl font-bold text-gray-800">{{ $stat['value'] }}</p>
                            <p class="text-xs text-gray-500 font-medium">{{ $stat['label'] }}</p>
                        </div>
                    </div>
                @endforeach
            </div>
        @endcan

        {{-- Search / Filter Bar --}}
        <div class="bg-white border border-gray-200 rounded-lg p-4 mb-4">
            <form method="GET" class="flex flex-wrap gap-3 items-end">
                <div class="flex-1 min-w-[200px]">
                    <label class="block text-xs font-medium text-gray-600 mb-1">Search</label>
                    <input type="text" name="search" value="{{ request('search') }}"
                           placeholder="Name, brand, category…"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:border-green-500 focus:ring-1 focus:ring-green-500 transition">
                </div>
                <div class="min-w-[160px]">
                    <label class="block text-xs font-medium text-gray-600 mb-1">Status</label>
                    <select name="status"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:border-green-500 transition">
                        <option value="">All Statuses</option>
                        <option value="published"        {{ request('status') == 'published'        ? 'selected' : '' }}>Published</option>
                        <option value="pending_approval" {{ request('status') == 'pending_approval' ? 'selected' : '' }}>Pending Approval</option>
                        <option value="pending_payment"  {{ request('status') == 'pending_payment'  ? 'selected' : '' }}>Pending Payment</option>
                        <option value="rejected"         {{ request('status') == 'rejected'         ? 'selected' : '' }}>Rejected</option>
                    </select>
                </div>
                <div class="min-w-[160px]">
                    <label class="block text-xs font-medium text-gray-600 mb-1">Category</label>
                    <select name="category"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:border-green-500 transition">
                        <option value="">All Categories</option>
                        @foreach($categories as $key => $label)
                            <option value="{{ $key }}" {{ request('category') == $key ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="flex gap-2">
                    <button type="submit" class="btn-action-view px-4 py-2">
                        <i class="fas fa-search"></i> Filter
                    </button>
                    <a href="{{ route('admin.machines.index') }}" class="btn-action-delete px-4 py-2">
                        <i class="fas fa-times"></i> Clear
                    </a>
                </div>
            </form>
        </div>

        {{-- Machines Table --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full table-zebra">
                    <thead>
                        <tr>
                            <th class="th-col-1 px-4 py-3 text-left">Machine</th>
                            <th class="th-col-2 px-4 py-3 text-left">Owner</th>
                            <th class="th-col-3 px-4 py-3 text-left">Category / Brand</th>
                            <th class="th-col-4 px-4 py-3 text-left">Status</th>
                            <th class="th-col-5 px-4 py-3 text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($machines as $machine)
                            <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                <td class="px-4 py-3">
                                    <div class="flex items-center gap-3">
                                        <div class="w-12 h-12 rounded-lg bg-blue-100 flex items-center justify-center flex-shrink-0 overflow-hidden">
                                            @if($machine->primary_image)
                                                <img src="{{ asset('storage/' . $machine->primary_image) }}"
                                                     alt="{{ $machine->name }}"
                                                     class="w-full h-full object-cover">
                                            @else
                                                <i class="fas fa-cogs text-blue-500 text-sm"></i>
                                            @endif
                                        </div>
                                        <div>
                                            <div class="font-medium text-gray-800 text-sm">{{ Str::limit($machine->name, 35) }}</div>
                                            @if($machine->model)
                                                <div class="text-xs text-gray-500">Model: {{ $machine->model }}</div>
                                            @endif
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    @if($machine->user)
                                        <div class="text-sm font-medium text-gray-800">{{ $machine->user->name }}</div>
                                        <div class="text-xs text-gray-500">{{ $machine->user->email }}</div>
                                    @else
                                        <span class="text-xs text-gray-400 italic">No owner</span>
                                    @endif
                                </td>
                                <td class="px-4 py-3">
                                    @if($machine->category)
                                        <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">{{ $machine->category }}</span>
                                    @endif
                                    @if($machine->brand)
                                        <div class="text-xs text-gray-500 mt-1">{{ $machine->brand }}</div>
                                    @endif
                                </td>
                                <td class="px-4 py-3">
                                    @php
                                        $statusColors = [
                                            'published'        => 'bg-green-100 text-green-800',
                                            'pending_approval' => 'bg-blue-100 text-blue-800',
                                            'pending_payment'  => 'bg-yellow-100 text-yellow-800',
                                            'rejected'         => 'bg-red-100 text-red-800',
                                            'paused'           => 'bg-gray-100 text-gray-800',
                                        ];
                                        $color = $statusColors[$machine->listing_status] ?? 'bg-gray-100 text-gray-800';
                                    @endphp
                                    <span class="px-2 py-1 rounded-full text-xs font-semibold {{ $color }}">
                                        {{ ucfirst(str_replace('_', ' ', $machine->listing_status)) }}
                                    </span>
                                    @if($machine->listing_status === 'rejected' && $machine->rejection_reason)
                                        <div class="text-xs text-red-600 mt-1 max-w-[150px] truncate"
                                             title="{{ $machine->rejection_reason }}">
                                            {{ Str::limit($machine->rejection_reason, 40) }}
                                        </div>
                                    @endif
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex items-center justify-center gap-1 flex-wrap">
                                        @if($machine->is_published)
                                            <a href="{{ route('machines.show', $machine->slug) }}"
                                               target="_blank"
                                               class="btn-action-view"
                                               title="View Public Page">
                                                <i class="fas fa-external-link-alt"></i>
                                            </a>
                                        @endif

                                        @if($machine->listing_status === 'pending_approval')
                                            @can('approve machines')
                                                <form action="{{ route('admin.machines.approve', $machine) }}"
                                                      method="POST" class="inline">
                                                    @csrf
                                                    <button type="submit" class="btn-action-approve" title="Approve">
                                                        <i class="fas fa-check"></i>
                                                    </button>
                                                </form>
                                                <button type="button"
                                                        onclick="showRejectModal({{ $machine->id }})"
                                                        class="btn-action-reject"
                                                        title="Reject">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            @endcan
                                        @else
                                            @can('manage machines')
                                                <a href="{{ route('dashboard.machines.edit', $machine) }}"
                                                   class="btn-action-edit"
                                                   title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                            @endcan
                                        @endif
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                <td colspan="5" class="px-4 py-12 text-center text-gray-500">
                                    <i class="fas fa-cogs text-4xl text-gray-300 mb-3 block"></i>
                                    No machines found.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            <div class="px-4 py-3 border-t border-gray-200">
                {{ $machines->links() }}
            </div>
        </div>

    </div>

    {{-- Reject Modal (Alpine v3) --}}
    <div id="rejectModalWrapper"
         x-data="{ showRejectModal: false }"
         x-show="showRejectModal"
         x-transition
         class="fixed inset-0 z-50 overflow-y-auto"
         style="display: none;"
         @open-reject-modal.window="showRejectModal = true; document.getElementById('rejectForm').action = '/admin/machines/' + $event.detail.machineId + '/reject'">
        <div class="flex items-center justify-center min-h-screen px-4">
            <div class="fixed inset-0 bg-black/50" @click="showRejectModal = false"></div>
            <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full overflow-hidden">
                <div class="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-red-600 to-red-700">
                    <h3 class="text-base font-semibold text-white flex items-center gap-2">
                        <i class="fas fa-times-circle"></i> Reject Machine Listing
                    </h3>
                    <button type="button" @click="showRejectModal = false" class="text-white/80 hover:text-white transition">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="p-6">
                <form id="rejectForm" method="POST">
                    @csrf
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Rejection Reason <span class="text-red-500">*</span>
                        </label>
                        <textarea name="rejection_reason" rows="4" required
                                  class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:border-red-500 focus:ring-1 focus:ring-red-500 transition"
                                  placeholder="Please provide a reason for rejection…"></textarea>
                    </div>
                    <div class="flex justify-end gap-3">
                        <button type="button" @click="showRejectModal = false"
                                class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition text-sm">
                            Cancel
                        </button>
                        <button type="submit"
                                class="btn-action-delete px-4 py-2">
                            <i class="fas fa-times"></i> Confirm Rejection
                        </button>
                    </div>
                </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        function showRejectModal(machineId) {
            window.dispatchEvent(new CustomEvent('open-reject-modal', { detail: { machineId: machineId } }));
        }
    </script>

</x-app-layout>
