@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render(request()->route()->getName()) }}
@endsection

@section('content')
<style>
    /* Styling untuk sidebar kategori */
    .category-sidebar {
        background: #f8fafc;
        border-radius: 8px;
        padding: 1.5rem;
        height: fit-content;
    }

    .category-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.75rem 1rem;
        margin: 0.25rem 0;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.2s ease;
        border: 1px solid transparent;
    }

    .category-item:hover {
        background: #e2e8f0;
        border-color: #cbd5e1;
    }

    .category-item.active {
        background: #3b82f6;
        color: white;
        border-color: #2563eb;
    }

    .category-count {
        background: #e2e8f0;
        color: #64748b;
        padding: 0.25rem 0.5rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 500;
    }

    .category-item.active .category-count {
        background: rgba(255, 255, 255, 0.2);
        color: white;
    }

    .sidebar-title {
        font-size: 1.125rem;
        font-weight: 600;
        margin-bottom: 1rem;
        color: #1e293b;
    }

    /* Loading state */
    body.loading {
        cursor: wait;
    }

    body.loading * {
        pointer-events: none;
    }

    @media (max-width: 768px) {
        .category-sidebar {
            margin-bottom: 1.5rem;
        }

        .category-item {
            padding: 0.5rem 0.75rem;
            font-size: 0.875rem;
        }
    }

    @media (max-width: 768px) {
        #previewContent {
            height: 400px;
            overflow: auto;
        }
    }

</style>

    <div class="flex flex-col gap-7 lg:flex-row">
        <!-- Sidebar Kategori -->
        <div class="w-full lg:w-80">
            <div class="category-sidebar">
                <h3 class="sidebar-title">
                    <i class="mr-2 ki-filled ki-category"></i>
                    Kategori
                </h3>

                <!-- Semua Kategori -->
                <div class="category-item {{ !request('category') ? 'active' : '' }}" onclick="filterByCategory('', 'Semua Kategori')">
                    <span>Semua Kategori</span>
                    <span class="category-count">{{ $total ?? 0 }}</span>
                </div>

                <!-- Daftar Kategori -->
                @foreach ($categories as $category)
                    <div class="category-item {{ request('category') == $category->id ? 'active' : '' }}" onclick="filterByCategory({{ $category->id }}, '{{ $category->name }}')">
                        <span>{{ $category->name }}</span>
                        <span class="category-count">{{ $category->daftarPustaka_count ?? 0 }}</span>
                    </div>
                @endforeach
            </div>
        </div>

        <!-- Konten Utama -->
        <div class="flex-1">
            <div class="flex flex-col gap-7 items-stretch">
        <div class="flex gap-3 items-center w-full">
            <div class="w-full input">
                <i class="ki-filled ki-magnifier">
                </i>
                <input id="search" placeholder="Search Daftar Pustaka, Judul" type="text">
                <span class="badge badge-outline -me-1.5">
                    ⌘ K
                </span>
            </div>
            <!--Filter-->
            <a class="btn btn-info" id="search_filter" onclick="filterSearch()">
                <i class="ki-filled ki-filter">
                </i>
                Filter
            </a>
            <a class="btn btn-light" id="reset_filter" onclick="resetFilter()">
                <i class="ki-filled ki-arrow-circle-left"></i>
                Reset Filter
            </a>
        </div>

        <div class="flex flex-wrap gap-5 justify-between items-center mt-3">
            <h3 class="text-sm font-medium text-mono">
                page {{ $page }} of {{ $pageCount }} — {{ $limit }} items per page, total
                {{ $total }} items.
            </h3>
            <div class="flex gap-2.5">
                <div class="flex toggle-group" data-kt-tabs="true" data-kt-tabs-initialized="true">
                    <a class="btn btn-icon active selected" data-kt-tab-toggle="#daftar_pustaka_grid" onclick="showGrid()"
                        href="javascript:void(0)">
                        <i class="ki-filled ki-category"></i>
                    </a>
                    <a class="btn btn-icon" data-kt-tab-toggle="#daftar_pustaka_list" onclick="showList()"
                        href="javascript:void(0)">
                        <i class="ki-filled ki-row-horizontal"></i>
                    </a>
                    @if (auth()->user()->hasRole(['administrator', 'admin']))
                        <a href="{{ route('daftar-pustaka.create') }}" class="btn btn-primary">
                            <i class="ki-filled ki-plus"></i>
                            Tambah
                        </a>
                    @endif
                </div>
            </div>

        </div>



        <div class="grid grid-cols-1 gap-4 md:grid-cols-3 lg:grid-cols-4" id="daftar_pustaka_grid">
            @if (isset($daftar_pustaka))
                @foreach ($daftar_pustaka as $item)
                    <div class="flex flex-col border shadow-none card">
                        <a class="show-pustaka h-[150px] bg-gray-200 w-full block" href="{{ route('daftar-pustaka.show', $item->id) }}"
                            data-url="{{ $item->attachment }}">
                            <div class="flex overflow-hidden justify-center items-center p-4 w-full h-full">
                                <div class="flex justify-center items-center text-red-500 rounded">
                                <i class="text-3xl ki-filled ki-document"></i>
                            </div>
                            </div>
                        </a>

                        <div class="flex flex-col flex-grow p-4 card-body">
                            <div>
                                <p class="text-xs text-gray-700 badge badge-xs badge-outline badge-success">
                                # {{ $item->category->name }}</p>
                            </div>
                            <div class="flex-grow mt-2">
                                <a href="{{ route('daftar-pustaka.show', $item->id) }}">
                                    <h3 class="text-sm font-bold text-gray-900 hover:text-primary">
                                        {{ $item->judul }}</h3>
                                    <p class="text-xs text-gray-700">
                                        {{-- batasi panjang deskripsi 50 --}}
                                        {{ substr($item->deskripsi, 0, 50) }}
                                    </p>
                                </a>
                            </div>
                            @if (auth()->user()->hasRole(['administrator', 'admin']))
                                <div class="flex gap-2 items-center mt-5">
                                    <a class="w-full text-center btn btn-xs btn-danger" onclick="deleteData({{ $item->id }})">
                                        <i class="ki-filled ki-trash"></i>
                                        Hapus
                                    </a>
                                    <a class="w-full text-center btn btn-xs btn-primary" href="{{ route('daftar-pustaka.edit', $item->id) }}">
                                        <i class="ki-filled ki-pencil"></i>
                                        Edit
                                    </a>
                                </div>
                            @endif
                        </div>
                    </div>
                @endforeach
            @endif
        </div>


        <div class="grid hidden grid-cols-1 gap-4" id="daftar_pustaka_list">
            @if (isset($daftar_pustaka))
                @foreach ($daftar_pustaka as $item)
                    <div class="card">
                        <div class="flex flex-wrap justify-between items-center p-2 card-body pe-5 gap-4.5">
                            <div class="flex gap-3.5 items-center">
                                <div
                                    class="card bg-gray-200 flex items-center justify-center bg-accent/50 h-[70px] w-[90px] shadow-none">
                                    <a class="show-pustaka h-[90px] w-full block"
                                        href="{{ route('daftar-pustaka.show', $item->id) }}"
                                        data-url="{{ $item->attachment }}">
                                        <div class="flex overflow-hidden justify-center items-center p-4 w-full h-full">
                                            <div class="flex justify-center items-center text-red-500 rounded">
                                <i class="text-3xl ki-filled ki-document"></i>
                            </div>
                                        </div>
                                    </a>
                                </div>
                                <a href="{{ route('daftar-pustaka.show', $item->id) }}">
                                <div class="flex flex-col cursor-pointer">
                                        <p class="text-xs text-gray-700 badge badge-xs badge-outline badge-success">
                                    # {{ $item->category->name }}</p>
                                        <div class="flex items-center">
                                            <a class="text-sm font-bold hover:text-primary text-mono leading-5.5">
                                                {{ $item->judul }}
                                            </div>
                                        </a>
                                        <div class="flex flex-wrap gap-3 items-center">
                                            <span class="gap-1 rounded-full kt-badge kt-badge-warning kt-badge-sm">
                                                <span class="text-xs font-medium text-foreground">
                                                    {{ substr($item->deskripsi, 0, 50) }}
                                                </span>
                                            </span>

                                        </div>
                                    </div>
                                </a>
                            </div>
                            <div class="flex gap-1.5 items-center">
                                @auth
                                    @if (auth()->user()->hasRole(['administrator', 'admin']))
                                        <div>
                                            <a class="btn btn-sm btn-danger" onclick="deleteData({{ $item->id }})">
                                                <i class="ki-filled ki-trash">
                                                </i>
                                                Hapus
                                            </a>
                                            <a class="btn btn-sm btn-info"
                                                href="{{ route('daftar-pustaka.edit', $item->id) }}">
                                                <i class="ki-filled ki-pencil">
                                                </i>
                                                Edit
                                            </a>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                        </div>
                    </div>
                @endforeach
            @endif
        </div>


        <div class="flex gap-2 justify-center mt-5 pagination">
            @if ($daftar_pustaka->onFirstPage())
                <span class="btn disabled"><i class="ki-filled ki-black-left"></i></span>
            @else
                <a href="{{ $daftar_pustaka->previousPageUrl() }}" class="btn">
                    <i class="ki-filled ki-black-left"></i>
                </a>
            @endif

            @foreach ($daftar_pustaka->getUrlRange(1, $daftar_pustaka->lastPage()) as $page => $url)
                <a href="{{ $url }}" class="btn {{ $page == $daftar_pustaka->currentPage() ? 'active' : '' }}">
                    {{ $page }}
                </a>
            @endforeach

            @if ($daftar_pustaka->hasMorePages())
                <a href="{{ $daftar_pustaka->nextPageUrl() }}" class="btn">
                    <i class="ki-filled ki-black-right"></i>
                </a>
            @else
                <span class="btn disabled"><i class="ki-filled ki-black-right"></i></span>
            @endif
        </div>
    </div>
@endsection

@push('scripts')
    <script type="text/javascript">
        function deleteData(data) {
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        }
                    });

                    $.ajax(`daftar-pustaka/${data}`, {
                        type: 'DELETE'
                    }).then((response) => {
                        swal.fire('Deleted!', 'User has been deleted.', 'success').then(() => {
                            window.location.reload();
                        });
                    }).catch((error) => {
                        console.error('Error:', error);
                        Swal.fire('Error!', 'An error occurred while deleting the file.', 'error');
                    });
                }
            })
        }




        function showGrid() {
            document.getElementById("daftar_pustaka_grid").classList.remove("hidden");
            document.getElementById("daftar_pustaka_grid").classList.add("active");

            document.getElementById("daftar_pustaka_list").classList.add("hidden");
            document.getElementById("daftar_pustaka_list").classList.remove("active");

            // Update button active class
            document.querySelectorAll(".toggle-group a").forEach(btn => btn.classList.remove("selected", "active"));
            event.currentTarget.classList.add("selected", "active");
        }

        function showList() {
            document.getElementById("daftar_pustaka_list").classList.remove("hidden");
            document.getElementById("daftar_pustaka_list").classList.add("active");

            document.getElementById("daftar_pustaka_grid").classList.add("hidden");
            document.getElementById("daftar_pustaka_grid").classList.remove("active");

            // Update button active class
            document.querySelectorAll(".toggle-group a").forEach(btn => btn.classList.remove("selected", "active"));
            event.currentTarget.classList.add("selected", "active");
        }

        function filterSearch() {
            const search = document.getElementById('search')?.value || '';

            const params = new URLSearchParams(window.location.search);

            if (search) {
                params.set('search', search);
            } else {
                params.delete('search');
            }

            // Reset to first page when searching
            params.set('page', '1');

            window.location.href = `{{ route('daftar-pustaka.index') }}?${params.toString()}`;
        }


        function resetFilter() {
            const url = "{{ route('daftar-pustaka.index') }}";
            window.location.href = url;
        }

        function filterByCategory(categoryId, categoryName) {
            // Add loading state
            document.body.classList.add('loading');

            // Update active state
            document.querySelectorAll('.category-item').forEach(item => {
                item.classList.remove('active');
            });
            event.currentTarget.classList.add('active');

            // Get current search parameter
            const search = document.getElementById('search')?.value || '';

            // Build URL with category parameter
            const params = new URLSearchParams(window.location.search);

            if (search) {
                params.set('search', search);
            }

            if (categoryId) {
                params.set('category', categoryId);
            } else {
                params.delete('category');
            }

            // Reset to first page when filtering
            params.set('page', '1');

            window.location.href = `{{ route('daftar-pustaka.index') }}?${params.toString()}`;
        }
    </script>
@endpush
