@extends('layouts.app')

@section('title', 'Production Dashboard')

@section('content')
<div class="px-4 sm:px-6 lg:px-8">
    <!-- Header with Per-Page Filter -->
    <div class="sm:flex sm:items-center justify-between mb-6">
        <div class="sm:flex-auto">
            <h1 class="text-2xl font-semibold text-gray-900">Production Dashboard</h1>
            <p class="mt-2 text-sm text-gray-700">Manage orders from printing to completion</p>
        </div>
        <div class="mt-4 sm:mt-0">
            <form method="GET" action="{{ route('dashboard') }}" class="flex items-center gap-2">
                <input type="hidden" name="status" value="{{ $currentStatus }}">
                <label for="per_page" class="text-sm font-medium text-gray-700">Show:</label>
                <select name="per_page" id="per_page"
                        onchange="this.form.submit()"
                        class="rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                    <option value="10" {{ request('per_page') == 10 ? 'selected' : '' }}>10</option>
                    <option value="25" {{ request('per_page', 25) == 25 ? 'selected' : '' }}>25</option>
                    <option value="100" {{ request('per_page') == 100 ? 'selected' : '' }}>100</option>
                </select>
            </form>
        </div>
    </div>

    <!-- Quick Scan AWB -->
    <div class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg shadow-md mb-4 p-6 border-2 border-blue-200">
        <div class="max-w-3xl mx-auto">
            <div class="flex items-center gap-4 mb-3">
                <svg class="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"/>
                </svg>
                <div>
                    <h2 class="text-lg font-bold text-gray-900">Quick Scan AWB</h2>
                    <p class="text-sm text-gray-600">Scan airway bill barcode to mark order as packed</p>
                </div>
            </div>

            <form id="scanForm" class="flex gap-3">
                @csrf
                <div class="flex-1">
                    <input type="text"
                           id="trackingNumberInput"
                           name="tracking_number"
                           placeholder="Scan or enter tracking number..."
                           autocomplete="off"
                           autofocus
                           class="w-full px-4 py-3 text-lg border-2 border-blue-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 shadow-sm">
                </div>
                <button type="submit"
                        id="scanButton"
                        class="px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 shadow-md transition-all flex items-center gap-2">
                    <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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    Scan
                </button>
            </form>

            <!-- Alert Messages -->
            <div id="scanAlert" class="mt-4 hidden"></div>
        </div>
    </div>

    <!-- Status Tabs -->
    <div class="bg-white rounded-lg shadow mb-4 overflow-hidden">
        <nav class="flex border-b border-gray-200" aria-label="Status Tabs">
            @php
                $tabs = [
                    'pending' => ['label' => 'Pending', 'color' => 'yellow', 'description' => 'Orders ready for packing'],
                    'packed' => ['label' => 'Packed', 'color' => 'blue', 'description' => 'Orders that have been packed'],
                    'completed' => ['label' => 'Completed', 'color' => 'green', 'description' => 'Completed orders'],
                ];
            @endphp

            @foreach($tabs as $status => $tab)
                @php
                    $isActive = $currentStatus === $status;
                    $count = $statusCounts[$status] ?? 0;
                    $color = $tab['color'];

                    if ($isActive) {
                        $tabClass = "bg-{$color}-50 text-{$color}-700 border-b-2 border-{$color}-500";
                        $badgeClass = "bg-{$color}-600 text-white";
                    } else {
                        $tabClass = 'text-gray-500 hover:text-gray-700 hover:bg-gray-50';
                        $badgeClass = 'bg-gray-200 text-gray-600';
                    }
                @endphp

                <a href="{{ route('dashboard', ['status' => $status]) }}"
                   class="relative group flex-1 px-6 py-4 text-center font-medium text-sm transition-all duration-200 {{ $tabClass }}"
                   title="{{ $tab['description'] }}">
                    <span class="flex items-center justify-center gap-2">
                        {{ $tab['label'] }}
                        <span class="inline-flex items-center justify-center min-w-[24px] h-6 px-2 text-xs font-semibold rounded-full {{ $badgeClass }}">
                            {{ number_format($count) }}
                        </span>
                    </span>
                </a>
            @endforeach
        </nav>
    </div>

    <!-- Search and Filter Section -->
    <div class="bg-white rounded-lg shadow mb-4 p-4">
        <form method="GET" action="{{ route('dashboard') }}" class="space-y-4">
            <input type="hidden" name="status" value="{{ $currentStatus }}">
            <input type="hidden" name="per_page" value="{{ request('per_page', 25) }}">

            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <!-- Search Input -->
                <div class="md:col-span-1">
                    <label for="search" class="block text-sm font-medium text-gray-700 mb-1">
                        Search
                    </label>
                    <input type="text"
                           name="search"
                           id="search"
                           value="{{ request('search') }}"
                           placeholder="Order #, Tracking #, Customer..."
                           class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm">
                </div>

                <!-- Date From -->
                <div class="md:col-span-1">
                    <label for="date_from" class="block text-sm font-medium text-gray-700 mb-1">
                        Date From
                    </label>
                    <input type="date"
                           name="date_from"
                           id="date_from"
                           value="{{ request('date_from') }}"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm">
                </div>

                <!-- Date To -->
                <div class="md:col-span-1">
                    <label for="date_to" class="block text-sm font-medium text-gray-700 mb-1">
                        Date To
                    </label>
                    <input type="date"
                           name="date_to"
                           id="date_to"
                           value="{{ request('date_to') }}"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm">
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="flex items-center gap-2">
                <button type="submit"
                        class="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 shadow-sm">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                    </svg>
                    Apply Filters
                </button>

                @if(request('search') || request('date_from') || request('date_to'))
                    <a href="{{ route('dashboard', ['status' => $currentStatus, 'per_page' => request('per_page', 25)]) }}"
                       class="inline-flex items-center px-4 py-2 bg-gray-200 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                        Clear Filters
                    </a>
                @endif

                <!-- Active Filters Info -->
                @if(request('search') || request('date_from') || request('date_to'))
                    <div class="ml-auto text-sm text-gray-600">
                        <span class="font-medium">Active filters:</span>
                        @if(request('search'))
                            <span class="inline-flex items-center px-2 py-1 rounded-md bg-blue-100 text-blue-800 text-xs ml-1">
                                Search: "{{ request('search') }}"
                            </span>
                        @endif
                        @if(request('date_from'))
                            <span class="inline-flex items-center px-2 py-1 rounded-md bg-blue-100 text-blue-800 text-xs ml-1">
                                From: {{ request('date_from') }}
                            </span>
                        @endif
                        @if(request('date_to'))
                            <span class="inline-flex items-center px-2 py-1 rounded-md bg-blue-100 text-blue-800 text-xs ml-1">
                                To: {{ request('date_to') }}
                            </span>
                        @endif
                    </div>
                @endif
            </div>
        </form>
    </div>

    <!-- Orders Table -->
    @if(count($orders) > 0)
        <!-- Bulk Complete Form (Packed Status Only) -->
        @if($currentStatus === 'packed')
            <form id="bulkCompleteForm" action="{{ route('orders.bulk-complete') }}" method="POST">
                @csrf
        @endif

        <div class="bg-white shadow overflow-hidden sm:rounded-lg">
            <!-- Bulk Actions Bar (Packed Status Only) -->
            @if($currentStatus === 'packed')
                <div id="bulkActionsBar" class="hidden bg-blue-50 border-b border-blue-200 px-4 py-3">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-3">
                            <span id="selectedCount" class="text-sm font-medium text-blue-900">0 orders selected</span>
                            <button type="button"
                                    onclick="clearSelection()"
                                    class="text-sm text-blue-600 hover:text-blue-800 underline">
                                Clear Selection
                            </button>
                        </div>
                        <button type="submit"
                                onclick="return confirm('Mark ' + document.querySelectorAll('input[name=\'order_ids[]\']:checked').length + ' order(s) as completed?')"
                                class="inline-flex items-center gap-2 px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 shadow-md">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                            </svg>
                            Bulk Complete
                        </button>
                    </div>
                </div>
            @endif

            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-300">
                    <thead class="bg-gray-50">
                        <tr>
                            @if($currentStatus === 'packed')
                                <th scope="col" class="py-3.5 pl-4 pr-3 text-left sm:pl-6">
                                    <input type="checkbox"
                                           id="selectAll"
                                           onchange="toggleSelectAll(this)"
                                           class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 cursor-pointer">
                                </th>
                            @endif
                            <th scope="col" class="py-3.5 {{ $currentStatus === 'packed' ? 'px-3' : 'pl-4 pr-3 sm:pl-6' }} text-left text-sm font-semibold text-gray-900">Order ID</th>
                            <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Customer Name</th>
                            <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Address</th>
                            <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Items (SKU x Qty)</th>
                            <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Created</th>
                            <th scope="col" class="relative py-3.5 pl-3 pr-4 sm:pr-6">
                                <span class="sr-only">Actions</span>
                            </th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200 bg-white">
                        @foreach($orders as $order)
                            <tr class="hover:bg-gray-50">
                                @if($currentStatus === 'packed')
                                    <!-- Checkbox -->
                                    <td class="whitespace-nowrap py-4 pl-4 pr-3 sm:pl-6">
                                        <input type="checkbox"
                                               name="order_ids[]"
                                               value="{{ $order->id }}"
                                               onchange="updateBulkActions()"
                                               class="order-checkbox h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 cursor-pointer">
                                    </td>
                                @endif

                                <!-- Order ID -->
                                <td class="whitespace-nowrap py-4 {{ $currentStatus === 'packed' ? 'px-3' : 'pl-4 pr-3 sm:pl-6' }} text-sm font-medium text-gray-900">
                                    <div class="font-mono text-xs">#{{ $order->order_number }}</div>
                                    <div class="text-xs text-gray-500">{{ $order->global_order_id }}</div>
                                </td>

                                <!-- Customer Name -->
                                <td class="px-3 py-4 text-sm text-gray-900">
                                    <div class="font-medium">{{ $order->customer_name }}</div>
                                    <div class="text-xs text-gray-500">{{ $order->customer_phone }}</div>
                                </td>

                                <!-- Address -->
                                <td class="px-3 py-4 text-sm text-gray-700 max-w-xs">
                                    <div class="whitespace-normal break-words">
                                        {{ $order->delivery_address }}
                                    </div>
                                </td>

                                <!-- Items (SKU x Qty with tooltip) -->
                                <td class="px-3 py-4 text-sm text-gray-900">
                                    <div class="flex flex-wrap gap-2">
                                        @foreach($order->items as $item)
                                            <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-gray-100 text-gray-800 cursor-help"
                                                  title="{{ $item->product_name }}">
                                                {{ $item->product_sku }} x{{ $item->quantity }}
                                            </span>
                                        @endforeach
                                    </div>
                                </td>

                                <!-- Created Date -->
                                <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                    <div>{{ \Carbon\Carbon::parse($order->date_created)->format('M d, Y') }}</div>
                                    <div class="text-xs">{{ \Carbon\Carbon::parse($order->date_created)->format('H:i') }}</div>
                                </td>

                                <!-- Actions -->
                                <td class="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
                                    @if($currentStatus === 'pending')
                                        <!-- Mark as Packed Button -->
                                        <form action="{{ route('orders.pack', $order->id) }}" method="POST" class="inline">
                                            @csrf
                                            <button type="submit"
                                                    onclick="return confirm('Mark order {{ $order->order_number }} as packed?')"
                                                    class="inline-flex items-center gap-1.5 px-3 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 shadow-sm hover:shadow-md transition-all text-sm font-medium">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                                </svg>
                                                Mark Packed
                                            </button>
                                        </form>
                                    @elseif($currentStatus === 'packed')
                                        <div class="flex flex-col items-end gap-2">
                                            <!-- Packed By Info -->
                                            @if($order->packed_at)
                                                <div class="text-xs text-gray-700 bg-blue-50 px-3 py-1.5 rounded border border-blue-200">
                                                    <div class="flex items-center gap-1.5">
                                                        <svg class="w-3.5 h-3.5 text-blue-600 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                                            <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"/>
                                                        </svg>
                                                        <span class="font-semibold truncate">{{ $order->packed_by_name ?? 'Staff' }}</span>
                                                    </div>
                                                    <div class="flex items-center gap-1.5 mt-1">
                                                        <svg class="w-3.5 h-3.5 text-blue-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                                        </svg>
                                                        <span class="whitespace-nowrap">{{ \Carbon\Carbon::parse($order->packed_at)->format('M d, H:i') }}</span>
                                                    </div>
                                                </div>
                                            @endif

                                            <!-- Action Buttons Row -->
                                            <div class="flex items-center gap-2">
                                                <!-- Undo Button (Manager/Admin only) -->
                                                @php
                                                    $userRoles = $user['roles'] ?? [];
                                                    $canUndo = in_array('admin', $userRoles) || in_array('production-manager', $userRoles);
                                                @endphp

                                                @if($canUndo)
                                                    <button type="button"
                                                            onclick="showUndoModal({{ $order->id }}, '{{ $order->order_number }}')"
                                                            class="inline-flex items-center gap-1.5 px-3 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 shadow-sm hover:shadow-md transition-all text-sm font-medium"
                                                            title="Revert to Pending">
                                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"/>
                                                        </svg>
                                                        Undo
                                                    </button>
                                                @endif

                                                <!-- Mark as Completed Button -->
                                                <form action="{{ route('orders.complete', $order->id) }}" method="POST" class="inline">
                                                    @csrf
                                                    <button type="submit"
                                                            onclick="return confirm('Mark order {{ $order->order_number }} as completed?')"
                                                            class="inline-flex items-center gap-1.5 px-3 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 shadow-sm hover:shadow-md transition-all text-sm font-medium">
                                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                                        </svg>
                                                        Mark Completed
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    @else
                                        <!-- Completed - Show completion info -->
                                        <div class="flex flex-col items-end gap-2">
                                            <!-- Completed By Info -->
                                            @if($order->completed_at)
                                                <div class="text-xs text-gray-700 bg-green-50 px-3 py-1.5 rounded border border-green-200">
                                                    <div class="flex items-center gap-1.5">
                                                        <svg class="w-3.5 h-3.5 text-green-600 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                                            <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"/>
                                                        </svg>
                                                        <span class="font-semibold truncate">{{ $order->completed_by_name ?? 'Staff' }}</span>
                                                    </div>
                                                    <div class="flex items-center gap-1.5 mt-1">
                                                        <svg class="w-3.5 h-3.5 text-green-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                                        </svg>
                                                        <span class="whitespace-nowrap">{{ \Carbon\Carbon::parse($order->completed_at)->format('M d, H:i') }}</span>
                                                    </div>
                                                </div>
                                            @endif

                                            <!-- Completed Badge -->
                                            <span class="inline-flex items-center gap-1 px-3 py-2 bg-green-100 text-green-800 rounded-md text-sm font-medium">
                                                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                                                </svg>
                                                Completed
                                            </span>
                                        </div>
                                    @endif
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Pagination -->
        <div class="mt-4">
            {{ $orders->appends(['status' => $currentStatus, 'per_page' => request('per_page', 25)])->links() }}
        </div>

        @if($currentStatus === 'packed')
            </form>
        @endif
    @else
        <!-- Empty State -->
        <div class="bg-white shadow sm:rounded-lg">
            <div class="text-center py-12">
                <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"/>
                                </svg>
                <h3 class="mt-2 text-sm font-medium text-gray-900">No orders in {{ $tabs[$currentStatus]['label'] ?? '' }}</h3>
                <p class="mt-1 text-sm text-gray-500">
                    @if($currentStatus === 'pending')
                        All orders have been packed. Great work!
                    @elseif($currentStatus === 'packed')
                        No packed orders waiting for completion.
                    @else
                        No completed orders yet.
                    @endif
                </p>
            </div>
        </div>
    @endif

    <!-- Summary Footer -->
    <div class="mt-4 bg-gray-50 rounded-lg p-4">
        <div class="flex items-center justify-between text-sm">
            <div class="text-gray-700">
                Showing <span class="font-medium">{{ count($orders) }}</span>
                {{ Str::plural('order', count($orders)) }} in
                <span class="font-medium">{{ $tabs[$currentStatus]['label'] }}</span>
            </div>
            <div class="text-gray-500">
                Last updated: {{ now()->format('M d, Y H:i') }}
            </div>
        </div>
    </div>

    <!-- Undo Modal -->
    <div id="undoModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <div class="flex items-center gap-2 mb-4">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
                        <svg class="h-6 w-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                        </svg>
                    </div>
                    <div class="flex-1">
                        <h3 class="text-lg font-medium text-gray-900">Undo Packed Order</h3>
                        <p class="text-sm text-gray-500 mt-1">Order #<span id="undoOrderNumber"></span></p>
                    </div>
                </div>

                <form id="undoForm" class="mt-4">
                    @csrf
                    <input type="hidden" id="undoOrderId" name="order_id">

                    <div>
                        <label for="undoReason" class="block text-sm font-medium text-gray-700 mb-2">
                            Reason for undoing <span class="text-red-600">*</span>
                        </label>
                        <textarea id="undoReason"
                                  name="reason"
                                  rows="3"
                                  required
                                  minlength="5"
                                  maxlength="500"
                                  placeholder="Explain why this order needs to be unpacked (minimum 5 characters)..."
                                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-red-500"></textarea>
                        <p class="mt-1 text-xs text-gray-500">Minimum 5 characters required</p>
                    </div>

                    <div class="mt-6 flex gap-3">
                        <button type="button"
                                onclick="closeUndoModal()"
                                class="flex-1 px-4 py-2 bg-gray-300 text-gray-800 rounded-md hover:bg-gray-400 transition-all font-medium">
                            Cancel
                        </button>
                        <button type="submit"
                                class="flex-1 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-all font-medium">
                            Confirm Undo
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const scanForm = document.getElementById('scanForm');
    const trackingInput = document.getElementById('trackingNumberInput');
    const scanButton = document.getElementById('scanButton');
    const scanAlert = document.getElementById('scanAlert');

    let isProcessing = false;
    let scannerTimeout = null;

    // Auto-focus input on page load
    trackingInput.focus();

    // Detect barcode scanner input (fast typing + Enter)
    // Scanner types entire barcode in < 100ms, then sends Enter
    trackingInput.addEventListener('input', function() {
        // Clear previous timeout
        if (scannerTimeout) clearTimeout(scannerTimeout);

        // Set timeout to detect if this is scanner input (very fast typing)
        scannerTimeout = setTimeout(() => {
            scannerTimeout = null;
        }, 100);
    });

    // Listen for Enter key (from scanner or manual)
    trackingInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();

            // If timeout still exists, it's likely from scanner (fast input)
            // Auto-submit immediately
            if (scannerTimeout || trackingInput.value.trim().length > 10) {
                submitScan();
            }
        }
    });

    // Manual button click
    scanForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        submitScan();
    });

    async function submitScan() {
        if (isProcessing) return; // Prevent double submission

        const trackingNumber = trackingInput.value.trim();

        if (!trackingNumber) {
            showAlert('Please enter a tracking number', 'error');
            return;
        }

        // Mark as processing
        isProcessing = true;

        // Disable form during submission
        scanButton.disabled = true;
        trackingInput.disabled = true;
        scanButton.innerHTML = '<svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Processing...';

        try {
            const response = await fetch('{{ route("orders.scan") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                },
                body: JSON.stringify({
                    tracking_number: trackingNumber
                })
            });

            const data = await response.json();

            if (data.success) {
                showAlert(`✓ ${data.message}`, 'success');
                trackingInput.value = '';

                // Reload page after 1.5 seconds to show updated list
                setTimeout(() => {
                    window.location.href = '{{ route("dashboard", ["status" => "pending"]) }}';
                }, 1500);
            } else {
                showAlert(data.message, 'error');
                trackingInput.value = '';

                // Re-enable form
                isProcessing = false;
                scanButton.disabled = false;
                trackingInput.disabled = false;
                scanButton.innerHTML = '<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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> Scan';
                trackingInput.focus();
            }
        } catch (error) {
            console.error('Scan error:', error);
            showAlert('Failed to process scan. Please try again.', 'error');

            // Re-enable form
            isProcessing = false;
            scanButton.disabled = false;
            trackingInput.disabled = false;
            scanButton.innerHTML = '<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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> Scan';
            trackingInput.focus();
        }
    }

    function showAlert(message, type) {
        const bgColor = type === 'success' ? 'bg-green-100 border-green-400 text-green-700' : 'bg-red-100 border-red-400 text-red-700';
        const icon = type === 'success'
            ? '<svg class="w-5 h-5 text-green-600" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg>'
            : '<svg class="w-5 h-5 text-red-600" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/></svg>';

        scanAlert.innerHTML = `
            <div class="border-l-4 ${bgColor} p-4 rounded-md flex items-start gap-3 animate-fadeIn">
                ${icon}
                <p class="text-sm font-medium flex-1">${message}</p>
            </div>
        `;
        scanAlert.classList.remove('hidden');

        // Auto-hide after 5 seconds for errors (success will redirect)
        if (type === 'error') {
            setTimeout(() => {
                scanAlert.classList.add('hidden');
            }, 5000);
        }
    }

    // Undo Modal Functions
    window.showUndoModal = function(orderId, orderNumber) {
        document.getElementById('undoOrderId').value = orderId;
        document.getElementById('undoOrderNumber').textContent = orderNumber;
        document.getElementById('undoReason').value = '';
        document.getElementById('undoModal').classList.remove('hidden');
        document.getElementById('undoReason').focus();
    };

    window.closeUndoModal = function() {
        document.getElementById('undoModal').classList.add('hidden');
    };

    // Handle undo form submission
    document.getElementById('undoForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const orderId = document.getElementById('undoOrderId').value;
        const reason = document.getElementById('undoReason').value.trim();

        if (reason.length < 5) {
            alert('Please provide a reason (minimum 5 characters)');
            return;
        }

        try {
            const response = await fetch(`/orders/${orderId}/undo-packed`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                },
                body: JSON.stringify({ reason: reason })
            });

            const data = await response.json();

            if (data.success) {
                closeUndoModal();
                alert(data.message);
                window.location.href = '{{ route("dashboard", ["status" => "packed"]) }}';
            } else {
                alert(data.message);
            }
        } catch (error) {
            console.error('Undo error:', error);
            alert('Failed to undo order. Please try again.');
        }
    });

    // Close modal when clicking outside
    document.getElementById('undoModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeUndoModal();
        }
    });
});

// Bulk Complete Functions
function toggleSelectAll(checkbox) {
    const checkboxes = document.querySelectorAll('.order-checkbox');
    checkboxes.forEach(cb => cb.checked = checkbox.checked);
    updateBulkActions();
}

function updateBulkActions() {
    const checkboxes = document.querySelectorAll('.order-checkbox:checked');
    const count = checkboxes.length;
    const bulkActionsBar = document.getElementById('bulkActionsBar');
    const selectedCount = document.getElementById('selectedCount');
    const selectAllCheckbox = document.getElementById('selectAll');

    if (count > 0) {
        bulkActionsBar.classList.remove('hidden');
        selectedCount.textContent = count + ' order' + (count !== 1 ? 's' : '') + ' selected';
    } else {
        bulkActionsBar.classList.add('hidden');
    }

    // Update "Select All" checkbox state
    const totalCheckboxes = document.querySelectorAll('.order-checkbox').length;
    if (selectAllCheckbox) {
        selectAllCheckbox.checked = count === totalCheckboxes && count > 0;
        selectAllCheckbox.indeterminate = count > 0 && count < totalCheckboxes;
    }
}

function clearSelection() {
    const checkboxes = document.querySelectorAll('.order-checkbox');
    checkboxes.forEach(cb => cb.checked = false);
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
    }
    updateBulkActions();
}
</script>

<style>
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}
.animate-fadeIn {
    animation: fadeIn 0.3s ease-out;
}
</style>
@endsection
