@extends('layouts.vendor')

@section('title', 'Edit Product')
@section('page-title', 'Edit Product')

@section('content')
<div class="bg-white rounded-xl shadow-sm p-6">
    <form action="{{ route('vendor.products.update', $product->id) }}" method="POST" enctype="multipart/form-data" id="productForm">
        @csrf @method('PUT')

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {{-- Basic Info --}}
            <div class="lg:col-span-2">
                <h3 class="font-semibold text-gray-700 mb-4 border-b pb-2">Basic Information</h3>
            </div>

            <div class="lg:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1">Product Name *</label>
                <input type="text" name="name" value="{{ old('name', $product->name) }}" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Category *</label>
                <select name="category_id" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    @foreach($categories as $cat)
                    <option value="{{ $cat->id }}" {{ old('category_id', $product->category_id) == $cat->id ? 'selected' : '' }}>{{ $cat->name }}</option>
                    @endforeach
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Brand</label>
                <select name="brand_id" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="">No Brand</option>
                    @foreach($brands as $brand)
                    <option value="{{ $brand->id }}" {{ old('brand_id', $product->brand_id) == $brand->id ? 'selected' : '' }}>{{ $brand->name }}</option>
                    @endforeach
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Price ({{ currency_symbol() }}) *</label>
                <input type="number" name="price" value="{{ old('price', $product->price) }}" required step="0.01" min="0" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Sale Price ({{ currency_symbol() }})</label>
                <input type="number" name="sale_price" value="{{ old('sale_price', $product->sale_price) }}" step="0.01" min="0" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Stock Quantity *</label>
                <input type="number" name="stock_quantity" value="{{ old('stock_quantity', $product->stock_quantity) }}" required min="0" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Condition</label>
                <select name="condition" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="new" {{ old('condition', $product->condition) == 'new' ? 'selected' : '' }}>New</option>
                    <option value="used" {{ old('condition', $product->condition) == 'used' ? 'selected' : '' }}>Used</option>
                    <option value="refurbished" {{ old('condition', $product->condition) == 'refurbished' ? 'selected' : '' }}>Refurbished</option>
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Part Number</label>
                <input type="text" name="part_number" value="{{ old('part_number', $product->part_number) }}" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">OEM Number</label>
                <input type="text" name="oem_number" value="{{ old('oem_number', $product->oem_number) }}" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Weight (kg)</label>
                <input type="number" name="weight" value="{{ old('weight', $product->weight) }}" step="0.01" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
            </div>

            <div class="lg:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1">Short Description</label>
                <input type="text" name="short_description" value="{{ old('short_description', $product->short_description) }}" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
            </div>

            <div class="lg:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1">Full Description</label>
                <textarea name="description" rows="5" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">{{ old('description', $product->description) }}</textarea>
            </div>

            <div class="flex items-center gap-2 lg:col-span-2">
                <input type="checkbox" name="is_active" value="1" id="is_active" {{ old('is_active', $product->is_active) ? 'checked' : '' }} class="w-4 h-4 text-blue-600 rounded">
                <label for="is_active" class="text-sm text-gray-700">Active (visible in store)</label>
            </div>

            {{-- Images --}}
            <div class="lg:col-span-2 border-t pt-6">
                <h3 class="font-semibold text-gray-700 mb-4">Product Images</h3>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Thumbnail Image</label>
                <input type="file" name="thumbnail" accept="image/*" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                @if($product->thumbnail)
                <div class="mt-2">
                    <img src="{{ asset('storage/' . $product->thumbnail) }}" class="w-24 h-24 object-cover rounded">
                </div>
                @endif
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Additional Images</label>
                <input type="file" name="images[]" accept="image/*" multiple class="w-full border border-gray-300 rounded-lg px-3 py-2">
                @if($product->images->count())
                <div class="flex gap-2 mt-2 flex-wrap">
                    @foreach($product->images as $img)
                    <div class="relative">
                        <img src="{{ asset('storage/' . $img->image_path) }}" class="w-20 h-20 object-cover rounded">
                    </div>
                    @endforeach
                </div>
                @endif
            </div>

            {{-- Vehicle Compatibility - New Intuitive Design --}}
            <div class="lg:col-span-2 border-t pt-6">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <h3 class="font-semibold text-gray-700">Vehicle Compatibility</h3>
                        <p class="text-sm text-gray-500">Select which vehicles this part is compatible with</p>
                    </div>
                    <div class="flex gap-2">
                        <span id="selectedCount" class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-medium">0 selected</span>
                        <button type="button" onclick="clearAllVehicles()" class="text-sm text-red-600 hover:text-red-800 underline">Clear All</button>
                    </div>
                </div>

                {{-- Search & Filter --}}
                <div class="bg-gray-50 rounded-lg p-4 mb-4">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Search Make/Model</label>
                            <input type="text" id="vehicleSearch" placeholder="Type to search..." 
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                                onkeyup="filterVehicles()">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Filter by Make</label>
                            <select id="makeFilter" onchange="filterVehicles()" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                                <option value="">All Makes</option>
                                @foreach($carMakes as $make)
                                    <option value="{{ $make->id }}">{{ $make->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Year Range</label>
                            <div class="flex gap-2">
                                <select id="yearFrom" onchange="filterVehicles()" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                                    <option value="">From</option>
                                    @for($y = date('Y'); $y >= 1990; $y--)
                                        <option value="{{ $y }}">{{ $y }}</option>
                                    @endfor
                                </select>
                                <select id="yearTo" onchange="filterVehicles()" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                                    <option value="">To</option>
                                    @for($y = date('Y'); $y >= 1990; $y--)
                                        <option value="{{ $y }}">{{ $y }}</option>
                                    @endfor
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Selected Vehicles Preview --}}
                <div id="selectedVehicles" class="mb-4 hidden">
                    <h4 class="text-sm font-medium text-gray-700 mb-2">Selected Vehicles:</h4>
                    <div id="selectedList" class="flex flex-wrap gap-2"></div>
                </div>

                {{-- Vehicle Selection Cards --}}
                <div id="vehicleContainer" class="space-y-4 max-h-96 overflow-y-auto">
                    @php
                        $selectedYears = old('car_years', $product->carYears ? $product->carYears->pluck('id')->toArray() : []);
                    @endphp
                    @foreach($carMakes as $make)
                    <div class="vehicle-make bg-white border rounded-lg overflow-hidden" data-make="{{ $make->id }}" data-make-name="{{ strtolower($make->name) }}">
                        <div class="bg-gray-100 px-4 py-3 flex items-center justify-between cursor-pointer" onclick="toggleMake({{ $make->id }})">
                            <div class="flex items-center gap-3">
                                <input type="checkbox" id="make_all_{{ $make->id }}" onchange="toggleMakeAll({{ $make->id }})" onclick="event.stopPropagation()" class="w-5 h-5 text-blue-600 rounded">
                                <span class="font-semibold text-gray-800">{{ $make->name }}</span>
                                <span class="text-sm text-gray-500">(<span id="make_count_{{ $make->id }}">0</span> selected)</span>
                            </div>
                            <svg id="arrow_{{ $make->id }}" class="w-5 h-5 text-gray-500 transform transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                            </svg>
                        </div>
                        
                        <div id="make_content_{{ $make->id }}" class="hidden">
                            @foreach($make->models as $model)
                            <div class="vehicle-model border-t px-4 py-3" data-model="{{ $model->id }}" data-model-name="{{ strtolower($model->name) }}">
                                <div class="flex items-center justify-between mb-2">
                                    <div class="flex items-center gap-2">
                                        <input type="checkbox" id="model_all_{{ $model->id }}" onchange="toggleModelAll({{ $model->id }})" class="w-4 h-4 text-blue-600 rounded">
                                        <span class="font-medium text-gray-700">{{ $model->name }}</span>
                                    </div>
                                    <span class="text-xs text-gray-500"><span id="model_count_{{ $model->id }}">0</span> years selected</span>
                                </div>
                                
                                <div class="ml-6 flex flex-wrap gap-2">
                                    @foreach($model->years as $year)
                                    <label class="vehicle-year inline-flex items-center gap-1 px-3 py-1 bg-gray-100 rounded-full text-sm cursor-pointer hover:bg-blue-100 transition-colors" 
                                           data-year="{{ $year->year }}">
                                        <input type="checkbox" name="car_years[]" value="{{ $year->id }}" 
                                            {{ in_array($year->id, $selectedYears) ? 'checked' : '' }}
                                            onchange="updateSelection()"
                                            class="year-checkbox w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                                        <span>{{ $year->year }}</span>
                                    </label>
                                    @endforeach
                                </div>
                            </div>
                            @endforeach
                        </div>
                    </div>
                    @endforeach
                </div>

                @error('car_years')
                <p class="text-red-500 text-sm mt-2">{{ $message }}</p>
                @enderror
            </div>
        </div>

        <div class="flex gap-4 mt-6 pt-6 border-t">
            <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 font-medium">Update Product</button>
            <a href="{{ route('vendor.products.index') }}" class="bg-gray-100 text-gray-700 px-6 py-2 rounded-lg hover:bg-gray-200">Cancel</a>
        </div>
    </form>
</div>

<script>
    // Toggle make expansion
    function toggleMake(makeId) {
        const content = document.getElementById('make_content_' + makeId);
        const arrow = document.getElementById('arrow_' + makeId);
        content.classList.toggle('hidden');
        arrow.classList.toggle('rotate-180');
    }

    // Toggle all years for a make
    function toggleMakeAll(makeId) {
        const checkbox = document.getElementById('make_all_' + makeId);
        const content = document.getElementById('make_content_' + makeId);
        const yearCheckboxes = content.querySelectorAll('.year-checkbox');
        
        yearCheckboxes.forEach(cb => {
            cb.checked = checkbox.checked;
        });
        
        updateSelection();
    }

    // Toggle all years for a model
    function toggleModelAll(modelId) {
        const checkbox = document.getElementById('model_all_' + modelId);
        const modelDiv = checkbox.closest('.vehicle-model');
        const yearCheckboxes = modelDiv.querySelectorAll('.year-checkbox');
        
        yearCheckboxes.forEach(cb => {
            cb.checked = checkbox.checked;
        });
        
        updateSelection();
    }

    // Update selection counts and display
    function updateSelection() {
        const selected = document.querySelectorAll('.year-checkbox:checked');
        const totalCount = selected.length;
        
        // Update main counter
        document.getElementById('selectedCount').textContent = totalCount + ' selected';
        
        // Update make counts
        document.querySelectorAll('.vehicle-make').forEach(makeDiv => {
            const makeId = makeDiv.dataset.make;
            const makeCheckboxes = makeDiv.querySelectorAll('.year-checkbox:checked');
            document.getElementById('make_count_' + makeId).textContent = makeCheckboxes.length;
            
            // Update make checkbox state
            const makeCheckbox = document.getElementById('make_all_' + makeId);
            const totalMakeCheckboxes = makeDiv.querySelectorAll('.year-checkbox').length;
            makeCheckbox.checked = makeCheckboxes.length === totalMakeCheckboxes && totalMakeCheckboxes > 0;
            makeCheckbox.indeterminate = makeCheckboxes.length > 0 && makeCheckboxes.length < totalMakeCheckboxes;
        });
        
        // Update model counts
        document.querySelectorAll('.vehicle-model').forEach(modelDiv => {
            const modelCheckbox = modelDiv.querySelector('input[type="checkbox"]');
            const modelId = modelCheckbox.id.replace('model_all_', '');
            const modelCheckboxes = modelDiv.querySelectorAll('.year-checkbox:checked');
            const totalModelCheckboxes = modelDiv.querySelectorAll('.year-checkbox').length;
            document.getElementById('model_count_' + modelId).textContent = modelCheckboxes.length;
            
            // Update model checkbox state
            const modelAllCheckbox = document.getElementById('model_all_' + modelId);
            modelAllCheckbox.checked = modelCheckboxes.length === totalModelCheckboxes && totalModelCheckboxes > 0;
            modelAllCheckbox.indeterminate = modelCheckboxes.length > 0 && modelCheckboxes.length < totalModelCheckboxes;
        });
        
        // Update selected list display
        updateSelectedList();
    }

    // Update the selected vehicles list display
    function updateSelectedList() {
        const selectedList = document.getElementById('selectedList');
        const selectedVehicles = document.getElementById('selectedVehicles');
        const selected = document.querySelectorAll('.year-checkbox:checked');
        
        if (selected.length === 0) {
            selectedVehicles.classList.add('hidden');
            return;
        }
        
        selectedVehicles.classList.remove('hidden');
        selectedList.innerHTML = '';
        
        selected.forEach(cb => {
            const label = cb.closest('label');
            const year = label.dataset.year;
            const modelDiv = cb.closest('.vehicle-model');
            const modelName = modelDiv.querySelector('.font-medium').textContent;
            const makeDiv = cb.closest('.vehicle-make');
            const makeName = makeDiv.querySelector('.font-semibold').textContent;
            
            const tag = document.createElement('div');
            tag.className = 'bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm flex items-center gap-2';
            tag.innerHTML = `
                ${makeName} ${modelName} ${year}
                <button type="button" onclick="removeVehicle(${cb.value})" class="text-blue-600 hover:text-blue-800">×</button>
            `;
            selectedList.appendChild(tag);
        });
    }

    // Remove a specific vehicle selection
    function removeVehicle(yearId) {
        const checkbox = document.querySelector(`input[value="${yearId}"]`);
        if (checkbox) {
            checkbox.checked = false;
            updateSelection();
        }
    }

    // Clear all selections
    function clearAllVehicles() {
        document.querySelectorAll('.year-checkbox').forEach(cb => {
            cb.checked = false;
        });
        document.querySelectorAll('input[type="checkbox"]').forEach(cb => {
            if (cb.id.startsWith('make_all_') || cb.id.startsWith('model_all_')) {
                cb.checked = false;
                cb.indeterminate = false;
            }
        });
        updateSelection();
    }

    // Filter vehicles based on search and filters
    function filterVehicles() {
        const search = document.getElementById('vehicleSearch').value.toLowerCase();
        const makeFilter = document.getElementById('makeFilter').value;
        const yearFrom = parseInt(document.getElementById('yearFrom').value) || 0;
        const yearTo = parseInt(document.getElementById('yearTo').value) || 9999;
        
        document.querySelectorAll('.vehicle-make').forEach(makeDiv => {
            const makeId = makeDiv.dataset.make;
            const makeName = makeDiv.dataset.makeName;
            let makeVisible = false;
            
            // Check make filter
            if (makeFilter && makeFilter !== makeId) {
                makeDiv.classList.add('hidden');
                return;
            }
            
            // Check models
            makeDiv.querySelectorAll('.vehicle-model').forEach(modelDiv => {
                const modelName = modelDiv.dataset.modelName;
                let modelVisible = false;
                
                // Check years
                modelDiv.querySelectorAll('.vehicle-year').forEach(yearLabel => {
                    const year = parseInt(yearLabel.dataset.year);
                    const matchesSearch = makeName.includes(search) || modelName.includes(search);
                    const matchesYear = year >= yearFrom && year <= yearTo;
                    
                    if (matchesSearch && matchesYear) {
                        yearLabel.classList.remove('hidden');
                        modelVisible = true;
                        makeVisible = true;
                    } else {
                        yearLabel.classList.add('hidden');
                    }
                });
                
                if (modelVisible) {
                    modelDiv.classList.remove('hidden');
                } else {
                    modelDiv.classList.add('hidden');
                }
            });
            
            if (makeVisible || (search === '' && !makeFilter && yearFrom === 0 && yearTo === 9999)) {
                makeDiv.classList.remove('hidden');
            } else if (!makeVisible) {
                makeDiv.classList.add('hidden');
            }
        });
    }

    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        updateSelection();
    });
</script>
@endsection
