@extends('layouts.admin')

@section('title', 'Brands')

@section('page-title', 'Brands')

@section('content')
<div class="max-w-[1400px] mx-auto">
    <!-- Header Section -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-900 text-gray-900">Brands</h1>
        <div class="flex items-center gap-3">
            <button onclick="openBrandModal()" class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium shadow-lg shadow-primary/30 hover:bg-blue-600 transition-colors">
                <span class="material-symbols-outlined text-lg">add</span>
                <span>New Brand</span>
            </button>
            <select class="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-primary">
                <option>10 / page</option>
                <option>25 / page</option>
                <option>50 / page</option>
                <option>100 / page</option>
            </select>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-4">
        <input type="text" placeholder="Search..." class="w-full max-w-md h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary">
    </div>

    <!-- Brands Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">#</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">BRAND NAME</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">SLUG</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">STATUS</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right">ACTIONS</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @forelse($brands ?? [] as $index => $brand)
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="py-4 px-6 text-sm text-gray-600">{{ ($brands->currentPage() - 1) * $brands->perPage() + $index + 1 }}</td>
                        <td class="py-4 px-6 text-sm font-medium text-gray-900">{{ $brand->name }}</td>
                        <td class="py-4 px-6 text-sm text-gray-600">{{ $brand->slug ?? \Illuminate\Support\Str::slug($brand->name) }}</td>
                        <td class="py-4 px-6">
                            <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                <input type="checkbox" 
                                       class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300" 
                                       data-brand-id="{{ $brand->id }}"
                                       {{ $brand->is_active ? 'checked' : '' }}
                                       onchange="toggleBrandStatus({{ $brand->id }}, this.checked, this)">
                                <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300 {{ $brand->is_active ? 'bg-primary' : '' }}"></span>
                            </label>
                            <span class="ml-3 text-sm font-medium text-gray-700">
                                {{ $brand->is_active ? 'Active' : 'Inactive' }}
                            </span>
                        </td>
                        <td class="py-4 px-6 text-right">
                            <div class="flex items-center justify-end gap-2">
                                <button onclick="editBrand({{ $brand->id }})" class="p-2 text-gray-500 hover:text-primary hover:bg-gray-100 rounded-lg transition-colors">
                                    <span class="material-symbols-outlined text-lg">edit</span>
                                </button>
                                <button onclick="deleteBrand({{ $brand->id }})" class="p-2 text-gray-500 hover:text-red-500 hover:bg-gray-100 rounded-lg transition-colors">
                                    <span class="material-symbols-outlined text-lg">delete</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="5" class="py-12 px-6 text-center text-gray-500">
                            <span class="material-symbols-outlined text-4xl mb-2 block">branding_watermark</span>
                            <p>No brands found</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if(isset($brands) && $brands->hasPages())
        <div class="px-6 py-4 border-t border-gray-200">
            {{ $brands->links() }}
        </div>
        @endif
    </div>
</div>

<!-- Add Brand Modal -->
<div id="brandModal" data-admin-modal class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="closeBrandModal()"></div>
    <div class="absolute right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300">
        <div class="flex flex-col h-full">
            <!-- Header -->
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900 text-gray-900" id="brandModalTitle">Add New Brand</h2>
                <button onclick="closeBrandModal()" class="p-2 text-gray-500 hover:text-gray-700-300 hover:bg-gray-100700 rounded-lg transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>

            <!-- Form -->
            <form id="brandForm" method="POST" enctype="multipart/form-data" class="flex-1 overflow-y-auto">
                @csrf
                <input type="hidden" id="brandId" name="id">
                <div class="p-6 space-y-6">
                    <!-- Image Upload -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Image
                        </label>
                        <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-primary transition-colors cursor-pointer" onclick="document.getElementById('brandImage').click()">
                            <div class="space-y-1 text-center">
                                <div id="brandImagePreview" class="hidden">
                                    <img id="brandImagePreviewImg" src="" alt="Preview" class="mx-auto h-24 w-24 object-cover rounded-lg">
                                </div>
                                <div id="brandImagePlaceholder">
                                    <span class="material-symbols-outlined text-4xl text-gray-400">cloud_upload</span>
                                    <p class="text-sm text-gray-600">Upload Image</p>
                                </div>
                                <p class="text-xs text-gray-500">JPG, PNG. Max 5MB.</p>
                            </div>
                        </div>
                        <input type="file" id="brandImage" name="image" accept="image/jpeg,image/png" class="hidden" onchange="previewBrandImage(this)">
                    </div>

                    <!-- Name -->
                    <div>
                        <label for="brandName" class="block text-sm font-medium text-gray-700 mb-2">
                            Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="brandName" name="name" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="Enter brand name">
                    </div>

                    <!-- Description -->
                    <div>
                        <label for="brandDescription" class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                        <textarea id="brandDescription" name="description" rows="3" class="w-full px-4 py-3 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow resize-none"></textarea>
                    </div>
                </div>
            </form>

            <!-- Footer -->
            <div class="px-6 py-4 border-t border-gray-200 flex items-center justify-end gap-3">
                <button type="button" onclick="closeBrandModal()" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50800 transition-colors">
                    Cancel
                </button>
                <button type="submit" form="brandForm" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 shadow-sm transition-colors flex items-center gap-2">
                    <span class="material-symbols-outlined text-lg">save</span>
                    Save Brand
                </button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    let currentBrandId = null;

    function openBrandModal(id = null) {
        currentBrandId = id;
        const modal = document.getElementById('brandModal');
        const form = document.getElementById('brandForm');
        const title = document.getElementById('brandModalTitle');
        
        modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
        
        if (id) {
            title.textContent = 'Edit Brand';
            form.action = `{{ route('admin.products.brands.index') }}/${id}`;
            
            // Fetch brand data
            fetch(`{{ route('admin.products.brands.index') }}/${id}`, {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.brand) {
                    document.getElementById('brandId').value = data.brand.id;
                    document.getElementById('brandName').value = data.brand.name;
                    document.getElementById('brandDescription').value = data.brand.description || '';
                    if (data.brand.image) {
                        document.getElementById('brandImagePreviewImg').src = `{{ asset('storage/') }}/${data.brand.image}`;
                        document.getElementById('brandImagePreview').classList.remove('hidden');
                        document.getElementById('brandImagePlaceholder').classList.add('hidden');
                    }
                }
            })
            .catch(error => console.error('Error loading brand:', error));
        } else {
            title.textContent = 'Add New Brand';
            form.action = '{{ route("admin.products.brands.store") }}';
            form.reset();
            document.getElementById('brandId').value = '';
            document.getElementById('brandImagePreview').classList.add('hidden');
            document.getElementById('brandImagePlaceholder').classList.remove('hidden');
        }
    }

    function closeBrandModal() {
        document.getElementById('brandModal').classList.add('hidden');
        document.body.style.overflow = '';
        document.getElementById('brandForm').reset();
        document.getElementById('brandId').value = '';
        document.getElementById('brandImagePreview').classList.add('hidden');
        document.getElementById('brandImagePlaceholder').classList.remove('hidden');
        currentBrandId = null;
    }

    function previewBrandImage(input) {
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('brandImagePreviewImg').src = e.target.result;
                document.getElementById('brandImagePreview').classList.remove('hidden');
                document.getElementById('brandImagePlaceholder').classList.add('hidden');
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    function editBrand(id) {
        openBrandModal(id);
    }

    function toggleBrandStatus(id, isActive, checkboxElement) {
        const originalState = !isActive;
        
        fetch(`{{ route('admin.products.brands.index') }}/${id}`, {
            method: 'PUT',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                is_active: isActive,
                _method: 'PUT'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update the label text
                const label = checkboxElement.closest('label').querySelector('span');
                label.textContent = isActive ? 'Active' : 'Inactive';
            } else {
                // Revert checkbox state on error
                checkboxElement.checked = originalState;
                alert(data.message || 'Error updating status');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            checkboxElement.checked = originalState;
            alert('Error updating status');
        });
    }

    function deleteBrand(id) {
        if (confirm('Are you sure you want to delete this brand? This action cannot be undone.')) {
            fetch(`{{ route('admin.products.brands.index') }}/${id}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (response.ok) {
                    location.reload();
                } else {
                    return response.json().then(data => {
                        alert(data.message || 'Error deleting brand');
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                location.reload();
            });
        }
    }

    // Handle form submission
    document.getElementById('brandForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        const brandId = document.getElementById('brandId').value;
        const url = brandId 
            ? `{{ route('admin.products.brands.index') }}/${brandId}`
            : '{{ route("admin.products.brands.store") }}';
        const method = brandId ? 'PUT' : 'POST';
        
        // Add _method for PUT requests
        if (method === 'PUT') {
            formData.append('_method', 'PUT');
        }
        
        fetch(url, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert('Error saving brand: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            location.reload();
        });
    });
</script>
@endpush
@endsection
