@extends('layouts.admin')

@section('title', 'Produk')

@section('content')

    <!-- Breadcrumb -->
    @php
    $breadcrumbs = [
        ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
        ['label' => 'Master', 'url' => '#'],
        ['label' => 'Produk Jasa', 'url' => route('admin.master.products.index')]
    ];
    @endphp
    <x-breadcrumb :items="$breadcrumbs" />

    <!-- Notifikasi Modern -->
    <x-admin-notification />

    <!-- Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800 dark:text-white mb-4">Daftar Produk</h1>

        <!-- Filter Section -->
        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <form method="GET" action="{{ route('admin.master.products.index') }}" id="filterForm" class="flex flex-col sm:flex-row items-end gap-3">
                <!-- Search Bar -->
                <div class="relative flex-1 w-full sm:w-auto">
                    <input type="text" name="search" id="searchInput" value="{{ request('search') }}" placeholder="Cari produk..."
                        class="form-input-search" />
                    <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none"></i>
                    @if (request('search'))
                        <button type="button" onclick="clearSearch()"
                            class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300">
                            <i class="fas fa-times"></i>
                        </button>
                    @endif
                </div>

                <!-- Category Filter -->
                <div class="relative w-full sm:w-auto">
                    <select name="category" id="categoryFilter" onchange="submitFilter()" class="form-select">
                        <option value="">Semua Kategori</option>
                        @foreach ($parentCategories as $parent)
                            <option value="{{ $parent->id }}" {{ request('category') == $parent->id ? 'selected' : '' }}>
                                {{ $parent->name }}
                            </option>
                            @foreach ($childCategories->where('parent_id', $parent->id) as $child)
                                <option value="{{ $child->id }}" {{ request('category') == $child->id ? 'selected' : '' }}>
                                    &nbsp;&nbsp;└─ {{ $child->name }}
                                </option>
                            @endforeach
                        @endforeach
                    </select>
                    <i class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none text-xs"></i>
                </div>

                <!-- Status Filter -->
                <div class="relative w-full sm:w-auto">
                    <select name="status" id="statusFilter" onchange="submitFilter()" class="form-select">
                        <option value="">Semua Status</option>
                        <option value="1" {{ request('status') == '1' ? 'selected' : '' }}>Aktif</option>
                        <option value="0" {{ request('status') == '0' ? 'selected' : '' }}>Nonaktif</option>
                    </select>
                    <i class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none text-xs"></i>
                </div>

                <!-- Action Buttons -->
                <div class="flex items-center gap-2 w-full sm:w-auto">
                    <button id="bulkDeleteBtn" onclick="confirmBulkDelete()" disabled class="action-btn-danger">
                        <i class="fas fa-trash mr-2"></i>
                        <span>Hapus Terpilih</span>
                    </button>
                    <a href="{{ route('admin.master.products.create') }}" class="action-btn-primary">
                        <i class="fas fa-plus mr-2"></i>
                        <span>Tambah Produk</span>
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- Active Filters Info -->
    @if (request('search') || request('category') || request()->has('status'))
        <div class="mb-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg p-4">
            <div class="flex flex-wrap items-center gap-2">
                <span class="text-sm font-medium text-blue-800 dark:text-blue-200">Filter Aktif:</span>
                
                @if (request('search'))
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-800 dark:text-blue-200">
                        <i class="fas fa-search mr-1"></i>
                        Pencarian: "{{ request('search') }}"
                        <button onclick="clearFilter('search')" class="ml-2 hover:text-blue-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif
                
                @if (request('category'))
                    @php
                        $selectedCategory = $parentCategories->firstWhere('id', request('category')) ?? $childCategories->firstWhere('id', request('category'));
                    @endphp
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-200">
                        <i class="fas fa-tag mr-1"></i>
                        Kategori: {{ $selectedCategory ? $selectedCategory->name : 'Unknown' }}
                        <button onclick="clearFilter('category')" class="ml-2 hover:text-green-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif
                
                @if (request()->has('status'))
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-800 dark:text-purple-200">
                        <i class="fas fa-toggle-{{ request('status') == '1' ? 'on' : 'off' }} mr-1"></i>
                        Status: {{ request('status') == '1' ? 'Aktif' : 'Nonaktif' }}
                        <button onclick="clearFilter('status')" class="ml-2 hover:text-purple-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif
                
                <button onclick="clearAllFilters()" 
                    class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-700 transition-colors">
                    <i class="fas fa-times-circle mr-1"></i>
                    Hapus Semua Filter
                </button>
            </div>
        </div>
    @endif

    <!-- Table Container -->
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden transition-colors duration-300">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-600">
                    <tr>
                        <th class="w-12 px-4 py-3.5 text-center">
                            <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)"
                                class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
                        </th>
                        <th class="w-16 px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">
                            No
                        </th>
                        <th class="px-6 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Gambar</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Nama Produk</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Kategori</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Harga</th>
                        <th class="px-6 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Materials</th>
                        <th class="px-6 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Spareparts</th>
                        <th class="px-6 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Status</th>
                        <th class="px-6 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Aksi</th>
                    </tr>
                </thead>

                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                    @forelse ($products as $product)
                        <tr class="hover:bg-blue-50/50 dark:hover:bg-gray-700/80 transition-colors duration-200 cursor-pointer">
                            <!-- Checkbox -->
                            <td class="px-4 py-4 text-center align-middle">
                                <input type="checkbox" name="product_ids[]" value="{{ $product->id }}" 
                                    onchange="updateBulkDeleteButton()"
                                    class="product-checkbox w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
                            </td>

                            <!-- No -->
                            <td class="px-4 py-4 text-sm text-gray-900 dark:text-gray-100 text-center align-middle">
                                {{ $loop->iteration + $products->firstItem() - 1 }}
                            </td>

                            <!-- Gambar -->
                            <td class="px-6 py-4 text-center align-middle">
                                <div class="flex justify-center">
                                    <div class="relative">
                                        @if ($product->product_image)
                                            <img src="{{ asset('uploads/products/' . $product->product_image) }}"
                                                alt="Gambar Produk"
                                                class="h-14 w-14 object-contain rounded"
                                                style="background: transparent;">
                                        @elseif ($product->images && $product->images->count() > 0)
                                            <img src="{{ asset('uploads/products/' . $product->images->first()->image_path) }}"
                                                alt="Gambar Produk"
                                                class="h-14 w-14 object-contain rounded"
                                                style="background: transparent;">
                                        @else
                                            <div class="h-14 w-14 bg-gray-100 dark:bg-gray-600 rounded flex items-center justify-center">
                                                <i class="fas fa-image text-gray-400 dark:text-gray-500 text-lg"></i>
                                            </div>
                                        @endif

                                        @php
                                            $totalImages = ($product->product_image ? 1 : 0) + ($product->images ? $product->images->count() : 0);
                                        @endphp

                                        <!-- Badge jumlah gambar total -->
                                        @if ($totalImages > 1)
                                            <span
                                                class="absolute -top-2 -right-2 bg-blue-500 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center">
                                                {{ $totalImages }}
                                            </span>
                                        @endif
                                    </div>
                                </div>
                            </td>

                            <td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100 font-medium align-middle">
                                <div class="flex items-center gap-2">
                                    {{ $product->product_title }}
                                    @php
                                        $mismatchedCount = ($product->productions ?? collect())->filter(function($production) use ($product) {
                                            return $production->labor_cost && 
                                                   $production->labor_cost != ($product->service_fee ?? 0);
                                        })->count();
                                    @endphp
                                    @if($mismatchedCount > 0)
                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200" 
                                              title="Ada {{ $mismatchedCount }} produksi dengan labor cost berbeda dari upah jasa default">
                                            <i class="fas fa-exclamation-triangle mr-1"></i>
                                            {{ $mismatchedCount }}
                                        </span>
                                    @endif
                                </div>
                            </td>

                            <td class="px-6 py-4 text-sm text-gray-700 dark:text-gray-300 align-middle">
                                {{ $product->category_name }}
                            </td>

                            <td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100 font-semibold align-middle">
                                Rp {{ number_format($product->product_prices, 0, ',', '.') }}
                            </td>

                            <td class="px-6 py-4 text-center align-middle">
                                @if ($product->materials && $product->materials->count() > 0)
                                    <span class="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-blue-100 dark:bg-blue-900/40 text-blue-800 dark:text-blue-200">
                                        {{ $product->materials->count() }} bahan
                                    </span>
                                @else
                                    <span class="text-gray-400 dark:text-gray-500 text-sm">-</span>
                                @endif
                            </td>

                            <td class="px-6 py-4 text-center align-middle">
                                @if ($product->spareparts && $product->spareparts->count() > 0)
                                    <span class="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-green-100 dark:bg-green-900/40 text-green-800 dark:text-green-200">
                                        {{ $product->spareparts->count() }} sparepart
                                    </span>
                                @else
                                    <span class="text-gray-400 dark:text-gray-500 text-sm">-</span>
                                @endif
                            </td>

                            <td class="px-6 py-4 text-center align-middle">
                                @if ($product->is_active)
                                    <span class="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-green-100 dark:bg-green-900/40 text-green-800 dark:text-green-200">
                                        Aktif
                                    </span>
                                @else
                                    <span class="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-red-100 dark:bg-red-900/40 text-red-800 dark:text-red-200">
                                        Nonaktif
                                    </span>
                                @endif
                            </td>

                            <td class="px-6 py-4 text-center align-middle">
                                <div class="flex justify-center items-center space-x-3">
                                    <!-- Tombol Show -->
                                    <a href="{{ route('admin.master.products.show', $product->id) }}"
                                        class="inline-flex items-center justify-center w-9 h-9 text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 rounded transition-colors duration-200"
                                        title="Detail">
                                        <i class="fas fa-eye text-base"></i>
                                    </a>

                                    <!-- Tombol Edit -->
                                    <a href="{{ route('admin.master.products.edit', $product->id) }}?{{ http_build_query(request()->only(['page', 'search', 'category', 'status'])) }}"
                                        class="inline-flex items-center justify-center w-9 h-9 text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded transition-colors duration-200"
                                        title="Edit">
                                        <i class="fas fa-edit text-base"></i>
                                    </a>

                                    <!-- Tombol Hapus -->
                                    <button onclick="confirmDelete({{ $product->id }})"
                                        class="inline-flex items-center justify-center w-9 h-9 text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors duration-200"
                                        title="Hapus">
                                        <i class="fas fa-trash text-base"></i>
                                    </button>
                                </div>

                                <form id="delete-form-{{ $product->id }}"
                                    action="{{ route('admin.master.products.destroy', $product->id) }}" method="POST"
                                    class="hidden">
                                    @csrf
                                    @method('DELETE')
                                </form>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="10" class="px-6 py-16">
                                <x-empty-state 
                                    icon="fas fa-box"
                                    title="Belum Ada Data Produk Jasa"
                                    message="Mulai dengan menambahkan produk jasa pertama Anda"
                                    :action="[
                                        'primary' => ['label' => 'Tambah Produk Jasa', 'url' => route('admin.master.products.create'), 'icon' => 'fas fa-plus'],
                                        'secondary' => ['label' => 'Kembali ke Dashboard', 'url' => route('admin.dashboard'), 'icon' => 'fas fa-home']
                                    ]"
                                />
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <!-- Pagination -->
    @if ($products->hasPages())
        <div class="mt-6 flex justify-center">
            {{ $products->onEachSide(1)->links() }}
        </div>
    @endif

    <!-- Form Bulk Delete Tersembunyi -->
    <form id="bulkDeleteForm" action="{{ route('admin.master.products.bulkDestroy') }}" method="POST" class="hidden">
        @csrf
        @method('DELETE')
        <input type="hidden" name="ids" id="bulkDeleteIds">
    </form>

    <script>
        function confirmDelete(id) {
            Swal.fire({
                title: 'Yakin ingin menghapus?',
                text: "Data ini akan dihapus secara permanen!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Ya, hapus!',
                cancelButtonText: 'Batal',
                reverseButtons: true,
                customClass: {
                    popup: 'rounded-lg',
                    confirmButton: 'px-4 py-2 rounded-md font-medium',
                    cancelButton: 'px-4 py-2 rounded-md font-medium'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    document.getElementById('delete-form-' + id).submit();
                }
            });
        }

        function toggleSelectAll(checkbox) {
            const checkboxes = document.querySelectorAll('.product-checkbox');
            checkboxes.forEach(cb => {
                cb.checked = checkbox.checked;
            });
            updateBulkDeleteButton();
        }

        function updateBulkDeleteButton() {
            const checkboxes = document.querySelectorAll('.product-checkbox:checked');
            const bulkDeleteBtn = document.getElementById('bulkDeleteBtn');
            
            if (checkboxes.length > 0) {
                bulkDeleteBtn.disabled = false;
            } else {
                bulkDeleteBtn.disabled = true;
                document.getElementById('selectAll').checked = false;
            }
        }

        function confirmBulkDelete() {
            const checkboxes = document.querySelectorAll('.product-checkbox:checked');
            const ids = Array.from(checkboxes).map(cb => cb.value);

            if (ids.length === 0) {
                return;
            }

            Swal.fire({
                title: 'Yakin ingin menghapus?',
                text: `Anda akan menghapus ${ids.length} produk secara permanen!`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Ya, hapus!',
                cancelButtonText: 'Batal',
                reverseButtons: true,
                customClass: {
                    popup: 'rounded-lg',
                    confirmButton: 'px-4 py-2 rounded-md font-medium',
                    cancelButton: 'px-4 py-2 rounded-md font-medium'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    document.getElementById('bulkDeleteIds').value = JSON.stringify(ids);
                    document.getElementById('bulkDeleteForm').submit();
                }
            });
        }

        // Clear individual filter
        function clearFilter(filterName) {
            const url = new URL(window.location);
            url.searchParams.delete(filterName);
            window.location.href = url.toString();
        }

        // Clear all filters
        function clearAllFilters() {
            window.location.href = '{{ route("admin.master.products.index") }}';
        }

        // Clear search only
        function clearSearch() {
            const url = new URL(window.location);
            url.searchParams.delete('search');
            window.location.href = url.toString();
        }

        // Submit filter dengan parameter yang bersih
        function submitFilter() {
            const form = document.getElementById('filterForm');
            const params = new URLSearchParams();
            
            // Ambil nilai dari setiap input/select
            const search = document.getElementById('searchInput')?.value?.trim() || '';
            const category = document.getElementById('categoryFilter')?.value || '';
            const status = document.getElementById('statusFilter')?.value || '';
            
            // Hanya tambahkan parameter yang memiliki nilai
            if (search) {
                params.append('search', search);
            }
            if (category) {
                params.append('category', category);
            }
            if (status) {
                params.append('status', status);
            }
            
            // Redirect dengan parameter yang bersih
            const url = '{{ route("admin.master.products.index") }}' + (params.toString() ? '?' + params.toString() : '');
            window.location.href = url;
        }

        // Submit form search dengan Enter
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('searchInput');
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        submitFilter();
                    }
                });
            }
        });
    </script>

    <style>
        /* Konsisten Style untuk semua Index Pages */
        .form-input-search,
        .form-select {
            height: 40px !important;
            min-height: 40px !important;
            max-height: 40px !important;
            box-sizing: border-box !important;
            line-height: 1.5 !important;
            padding: 0 2.5rem 0 2.5rem !important;
            margin: 0 !important;
        }
        
        .form-input-search {
            width: 100%;
            padding-left: 2.5rem !important;
            padding-right: 2.5rem !important;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            background-color: white;
            color: rgb(17 24 39);
            font-size: 0.875rem;
            transition: all 0.2s;
        }
        
        .dark .form-input-search {
            border-color: rgb(75 85 99);
            background-color: rgb(55 65 81);
            color: white;
        }
        
        .form-input-search:focus {
            outline: none;
            ring: 2px;
            ring-color: rgb(59 130 246);
        }
        
        .form-select {
            width: 100%;
            padding-left: 1rem !important;
            padding-right: 2.5rem !important;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            background-color: white;
            color: rgb(17 24 39);
            font-size: 0.875rem;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            transition: all 0.2s;
        }
        
        .dark .form-select {
            border-color: rgb(75 85 99);
            background-color: rgb(55 65 81);
            color: white;
        }
        
        .form-select:focus {
            outline: none;
            ring: 2px;
            ring-color: rgb(59 130 246);
        }
        
        .action-btn-primary,
        .action-btn-danger {
            height: 40px !important;
            min-height: 40px !important;
            max-height: 40px !important;
            box-sizing: border-box !important;
            padding: 0 1rem !important;
            margin: 0 !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            font-weight: 500;
            border-radius: 0.5rem;
            transition: all 0.2s;
            white-space: nowrap;
        }
        
        .action-btn-primary {
            background-color: rgb(59 130 246);
            color: white;
        }
        
        .action-btn-primary:hover {
            background-color: rgb(37 99 235);
        }
        
        .action-btn-danger {
            background-color: rgb(239 68 68);
            color: white;
        }
        
        .action-btn-danger:hover:not(:disabled) {
            background-color: rgb(220 38 38);
        }
        
        .action-btn-danger:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    </style>
@endsection
