<x-admin-layout>
    <div class="mb-6">
        <h2 class="text-2xl font-bold text-slate-800">تسجيل صيانة جديدة</h2>
        <p class="text-slate-500 text-sm">إضافة سجل صيانة للمركبة واستهلاك قطع الغيار</p>
    </div>

    <form action="{{ route('admin.maintenance.store') }}" method="POST">
        @csrf

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Main Info -->
            <div class="lg:col-span-1 space-y-6">
                <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-6">
                    <h3 class="font-bold text-slate-800 mb-4 border-b pb-2">بيانات الصيانة</h3>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">المركبة <span class="text-red-500">*</span></label>
                            <select name="vehicle_id" required class="w-full rounded-xl border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                                <option value="">اختر المركبة...</option>
                                @foreach($vehicles as $vehicle)
                                    <option value="{{ $vehicle->id }}">{{ $vehicle->name }} ({{ $vehicle->plate_number }})</option>
                                @endforeach
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">عنوان الصيانة <span class="text-red-500">*</span></label>
                            <input type="text" name="title" required placeholder="مثال: تغيير زيت وفلتر" class="w-full rounded-xl border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">التاريخ <span class="text-red-500">*</span></label>
                            <input type="date" name="start_date" value="{{ date('Y-m-d') }}" required class="w-full rounded-xl border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">الفني المسؤول</label>
                            <input type="text" name="technician" placeholder="اسم الفني" class="w-full rounded-xl border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">الوصف / ملاحظات</label>
                            <textarea name="description" rows="3" class="w-full rounded-xl border-gray-200 focus:border-blue-500 focus:ring-blue-500"></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Parts & Labor -->
            <div class="lg:col-span-2 space-y-6">
                <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-6">
                    <h3 class="font-bold text-slate-800 mb-4 border-b pb-2">قطع الغيار والمواد المستهلكة</h3>
                    
                    <div class="mb-4 bg-blue-50 text-blue-800 p-3 rounded-lg text-sm flex items-start gap-2">
                        <x-icon name="InformationCircle" class="h-5 w-5 mt-0.5" />
                        <p>عند اختيار قطعة غيار، سيتم خصم الكمية تلقائياً من المخزون وسيتم احتساب التكلفة بناءً على سعر التكلفة الحالي.</p>
                    </div>

                    <div class="space-y-4" id="items-container">
                        <!-- Items will be added here dynamically -->
                    </div>

                    <button type="button" onclick="addItem()" class="mt-4 flex items-center gap-2 text-blue-600 font-bold hover:text-blue-700 transition-colors">
                        <x-icon name="PlusCircle" class="h-5 w-5" />
                        إضافة صنف
                    </button>
                </div>

                <div class="flex justify-end gap-4">
                    <a href="{{ route('maintenance-admin') }}" class="px-6 py-2.5 rounded-xl border border-gray-200 text-gray-700 font-semibold hover:bg-gray-50 transition-colors">إلغاء</a>
                    <button type="submit" class="px-6 py-2.5 rounded-xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition-colors shadow-sm">
                        حفظ السجل
                    </button>
                </div>
            </div>
        </div>
    </form>

    <!-- Template for Item Row -->
    <template id="item-row-template">
        <div class="item-row grid grid-cols-1 md:grid-cols-12 gap-4 items-end p-4 bg-gray-50 rounded-xl border border-gray-200 relative">
            <button type="button" onclick="removeItem(this)" class="absolute top-2 left-2 text-red-500 hover:text-red-700">
                <x-icon name="Trash" class="h-4 w-4" />
            </button>

            <div class="md:col-span-5">
                <label class="block text-xs font-medium text-slate-500 mb-1">المنتج / قطعة الغيار</label>
                <select name="items[INDEX][product_id]" class="w-full rounded-lg border-gray-200 text-sm focus:border-blue-500 focus:ring-blue-500 product-select" onchange="updateProductDetails(this)">
                    <option value="">-- اختر --</option>
                    @foreach($products as $product)
                        <option value="{{ $product->id }}" data-price="{{ $product->cost_price ?? $product->price }}" data-stock="{{ $product->quantity }}">
                            {{ $product->name }} (Stock: {{ $product->quantity }})
                        </option>
                    @endforeach
                </select>
                <input type="text" name="items[INDEX][description]" placeholder="أو اكتب وصف حر..." class="mt-2 w-full rounded-lg border-gray-200 text-sm focus:border-blue-500 focus:ring-blue-500 custom-desc hidden">
            </div>

            <div class="md:col-span-2">
                <label class="block text-xs font-medium text-slate-500 mb-1">الكمية</label>
                <input type="number" name="items[INDEX][quantity]" value="1" min="1" class="w-full rounded-lg border-gray-200 text-sm focus:border-blue-500 focus:ring-blue-500 qty-input" onchange="calculateRow(this)">
            </div>

            <div class="md:col-span-3">
                <label class="block text-xs font-medium text-slate-500 mb-1">التكلفة (للوحدة)</label>
                <input type="number" name="items[INDEX][unit_cost]" step="0.01" class="w-full rounded-lg border-gray-200 text-sm focus:border-blue-500 focus:ring-blue-500 cost-input" onchange="calculateRow(this)">
            </div>

            <div class="md:col-span-2 text-left">
                <span class="block text-xs font-medium text-slate-500 mb-1">الإجمالي</span>
                <span class="font-bold text-slate-800 total-display">0.00</span>
            </div>
        </div>
    </template>

    <script>
        let itemIndex = 0;

        function addItem() {
            const template = document.getElementById('item-row-template');
            const clone = template.content.cloneNode(true);
            const container = document.getElementById('items-container');
            
            // Replace INDEX placeholder
            clone.querySelectorAll('[name*="INDEX"]').forEach(el => {
                el.name = el.name.replace('INDEX', itemIndex);
            });

            container.appendChild(clone);
            itemIndex++;
        }

        function removeItem(btn) {
            btn.closest('.item-row').remove();
        }

        function updateProductDetails(select) {
            const row = select.closest('.item-row');
            const customDesc = row.querySelector('.custom-desc');
            const costInput = row.querySelector('.cost-input');
            const selectedOption = select.options[select.selectedIndex];

            if (select.value) {
                customDesc.classList.add('hidden');
                costInput.value = selectedOption.dataset.price || 0;
                costInput.readOnly = true; // Prevent editing cost for inventory items (optional policy)
                costInput.classList.add('bg-gray-100');
            } else {
                customDesc.classList.remove('hidden');
                costInput.value = '';
                costInput.readOnly = false;
                costInput.classList.remove('bg-gray-100');
            }
            calculateRow(select);
        }

        function calculateRow(el) {
            const row = el.closest('.item-row');
            const qty = parseFloat(row.querySelector('.qty-input').value) || 0;
            const cost = parseFloat(row.querySelector('.cost-input').value) || 0;
            const total = qty * cost;
            row.querySelector('.total-display').innerText = total.toFixed(2);
        }

        // Add one empty row by default
        document.addEventListener('DOMContentLoaded', () => {
            addItem();
        });
    </script>
</x-admin-layout>
