<x-app-layout>
    @section('page-title', $pageTitle)

    <div class="card shadow-sm border-0">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h5 class="my-0 fw-bold">Daftar Buku</h5>
            <a href="{{ route('admin.buku.create') }}" class="btn btn-primary">
                <i class="bi bi-plus-circle-fill me-2"></i>Tambah Buku
            </a>
        </div>
        <div class="card-body">
            {{-- NAV TABS --}}
            <ul class="nav nav-tabs" id="bukuTab" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="offline-tab" data-bs-toggle="tab"
                        data-bs-target="#offline-tab-pane" type="button" role="tab">Peminjaman Offline (<span
                            id="countOffline">{{ $bukuOffline->count() }}</span>)</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="online-tab" data-bs-toggle="tab" data-bs-target="#online-tab-pane"
                        type="button" role="tab">Baca Online (<span id="countOnline">{{ $bukuOnline->count()
                            }}</span>)</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link text-warning" id="arsip-tab" data-bs-toggle="tab"
                        data-bs-target="#arsip-tab-pane" type="button" role="tab">
                        <i class="bi bi-archive-fill me-1"></i>Diarsipkan (<span id="countArsip">0</span>)
                    </button>
                </li>
            </ul>

            <div class="tab-content" id="bukuTabContent">

                {{-- BUKU OFFLINE --}}
                <div class="tab-pane fade show active" id="offline-tab-pane" role="tabpanel">
                    <div class="table-responsive mt-3">
                        <table class="table table-hover align-middle" id="tableOffline">
                            <thead class="table-light">
                                <tr>
                                    <th>No</th>
                                    <th>Cover</th>
                                    <th>Judul</th>
                                    <th>Kode Buku</th>
                                    <th>Penulis</th>
                                    <th>Stok</th>
                                    <th>Status</th>
                                    <th class="text-center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($bukuOffline as $buku)
                                <tr>
                                    <td>{{ $loop->iteration }}</td>
                                    <td><img src="{{ asset($buku['cover']) }}" alt="{{ $buku['judul'] }}"
                                            width="50" class="rounded"></td>
                                    <td>{{ $buku['judul'] }}</td>
                                    <td>{{ $buku['kode_buku'] }}</td>
                                    <td>{{ $buku['penulis'] }}</td>
                                    <td>
                                        @if ($buku['status'] == 'Tersedia')
                                        <span
                                            class="badge bg-success-subtle text-success-emphasis">Tersedia</span>
                                        @else
                                        <span
                                            class="badge bg-warning-subtle text-warning-emphasis">Dipinjam</span>
                                        @endif
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal"
                                            data-bs-target="#detailBukuModal" data-id="{{ $buku['id'] }}"
                                            data-cover="{{ asset($buku['cover']) }}"
                                            data-judul="{{ $buku['judul'] }}"
                                            data-kode_buku="{{ $buku['kode_buku'] }}"
                                            data-penulis="{{ $buku['penulis'] }}"
                                            data-kategori="{{ $buku->category->name ?? '-' }}"
                                            data-tahun="{{ $buku['tahun'] }}" data-status="{{ $buku['status'] }}">
                                            <i class="bi bi-eye-fill"></i> Detail
                                        </button>
                                        <button class="btn btn-sm btn-outline-warning btn-arsipkan"
                                            data-judul="{{ $buku['judul'] }}" title="Arsipkan Buku">
                                            <i class="bi bi-archive-fill"></i> Arsip
                                        </button>
                    </div>
                    </td>
                    </tr>
                    @empty
                    <tr class="empty-row">
                        <td colspan="8" class="text-center py-4 text-muted">Tidak ada data buku offline.
                        </td>
                    </tr>
                    @endforelse
                    </tbody>
                    </table>
                </div>
            </div>

            {{-- BUKU ONLINE --}}
            <div class="tab-pane fade" id="online-tab-pane" role="tabpanel">
                <div class="table-responsive mt-3">
                    <table class="table table-hover align-middle" id="tableOnline">
                        <thead class="table-light">
                            <tr>
                                <th>No</th>
                                <th>Cover</th>
                                <th>Judul</th>
                                <th>Penulis</th>
                                <th>File PDF</th>
                                <th class="text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($bukuOnline as $buku)
                            <tr>
                                <td>{{ $loop->iteration }}</td>
                                <td><img src="{{ asset($buku['cover']) }}" alt="{{ $buku['judul'] }}"
                                        width="50" class="rounded"></td>
                                <td>{{ $buku['judul'] }}</td>
                                <td>{{ $buku['penulis'] }}</td>
                                <td><span
                                        class="badge bg-info-subtle text-info-emphasis">{{ $buku['file_pdf'] ?? 'N/A' }}</span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal"
                                        data-bs-target="#detailBukuModal" data-id="{{ $buku['id'] }}"
                                        data-cover="{{ asset($buku['cover']) }}"
                                        data-judul="{{ $buku['judul'] }}"
                                        data-penulis="{{ $buku['penulis'] }}"
                                        data-kategori="{{ $buku->category->name ?? '-' }}"
                                        data-tahun="{{ $buku['tahun'] }}" data-status="Dapat Dibaca Online">
                                        <i class="bi bi-eye-fill"></i> Detail
                                    </button>
                                    <button class="btn btn-sm btn-outline-warning btn-arsipkan"
                                        data-judul="{{ $buku['judul'] }}" title="Arsipkan Buku">
                                        <i class="bi bi-archive-fill"></i> Arsip
                                    </button>
                </div>
                </td>
                </tr>
                @empty
                <tr class="empty-row">
                    <td colspan="6" class="text-center py-4 text-muted">Tidak ada data buku online.</td>
                </tr>
                @endforelse
                </tbody>
                </table>
            </div>
        </div>

        {{-- ARSIP --}}
        <div class="tab-pane fade" id="arsip-tab-pane" role="tabpanel">
            <div class="table-responsive mt-3">
                <table class="table table-hover align-middle" id="tableArsip">
                    <thead class="table-light">
                        <tr>
                            <th>No</th>
                            <th>Cover</th>
                            <th>Judul</th>
                            <th>Penulis</th>
                            <th>Tipe Asal</th>
                            <th class="text-center">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="empty-row-arsip">
                            <td colspan="6" class="text-center py-5 text-muted">
                                <i class="bi bi-inbox fs-1 d-block mb-2 text-secondary opacity-50"></i>
                                Belum ada buku yang diarsipkan.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
    </div>
    </div>

    {{-- MODAL DETAIL BUKU --}}
    <div class="modal fade" id="detailBukuModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content border-0 shadow">
                <div class="modal-header border-0">
                    <h5 class="modal-title fw-bold" id="modalJudul">Detail Buku</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4 text-center mb-3">
                            <img src="" id="modalCover" class="img-fluid rounded shadow"
                                style="max-height: 250px; object-fit: cover;">
                        </div>
                        <div class="col-md-8">
                            <h3 id="modalJudulContent" class="fw-bold text-dark mb-1"></h3>
                            <p class="text-muted mb-3" id="modalPenulis"></p>

                            <div class="bg-light p-3 rounded-3">
                                <table class="table table-sm table-borderless mb-0">
                                    <tr>
                                        <td class="text-secondary" width="130">Kategori</td>
                                        <td id="modalKategori" class="fw-bold"></td>
                                    </tr>
                                    <tr id="rowKodeBuku">
                                        <td class="text-secondary">Kode Buku</td>
                                        <td id="modalKode" class="fw-bold font-monospace"></td>
                                    </tr>
                                    <tr>
                                        <td class="text-secondary">Tahun Terbit</td>
                                        <td id="modalTahun" class="fw-bold"></td>
                                    </tr>
                                    <tr>
                                        <td class="text-secondary">Stok</td>
                                        <td id="modalStok" class="fw-bold"></td>
                                    </tr>
                                    <tr>
                                        <td class="text-secondary">Status</td>
                                        <td><span id="modalStatus" class="badge"></span></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0 bg-light">
                    <button type="button" class="btn btn-secondary rounded-pill px-4"
                        data-bs-dismiss="modal">Tutup</button>
                    <a href="#" id="modalEditButton" class="btn btn-primary rounded-pill px-4">
                        <i class="bi bi-pencil-square me-2"></i>Edit Buku
                    </a>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {

            function updateTableNumbers() {
                ['#tableOffline', '#tableOnline', '#tableArsip'].forEach(tableId => {
                    let count = 0;
                    $(tableId + ' tbody tr').not('[class^="empty-row"]').each(function(index) {
                        $(this).find('.row-number').text(index + 1);
                        count++;
                    });

                    if (tableId === '#tableOffline') $('#countOffline').text(count);
                    if (tableId === '#tableOnline') $('#countOnline').text(count);
                    if (tableId === '#tableArsip') {
                        $('#countArsip').text(count);
                        if (count === 0) $('.empty-row-arsip').show();
                        else $('.empty-row-arsip').hide();
                    }
                });
            }

            // LOGIC MODAL DETAIL
            $('#detailBukuModal').on('show.bs.modal', function(event) {
                const button = $(event.relatedTarget);
                const buku = button.data('buku');

                $('#modalCover').attr('src', "{{ asset('') }}" + buku.cover);
                $('#modalJudulContent').text(buku.judul);
                $('#modalPenulis').text('Penulis: ' + buku.penulis);
                $('#modalKategori').text(buku.kategori);
                $('#modalTahun').text(buku.tahun);
                $('#modalStok').text(buku.stok ? buku.stok + ' Buku' : '-');

                if (buku.kode_buku) {
                    $('#rowKodeBuku').show();
                    $('#modalKode').text(buku.kode_buku);
                } else {
                    $('#rowKodeBuku').hide();
                }

                // Status Badge
                const statusBadge = $('#modalStatus');
                statusBadge.removeClass().addClass('badge');
                if (buku.status === 'Tersedia' || !buku.status) {
                    statusBadge.addClass('bg-success-subtle text-success-emphasis').text('Tersedia / Online');
                } else {
                    statusBadge.addClass('bg-warning-subtle text-warning-emphasis').text('Dipinjam');
                }

                $('#modalEditButton').attr('href', "{{ url('admin/buku') }}/" + buku.id + "/edit");
            });

            // LOGIC ARSIPKAN BUKU
            $(document).on('click', '.btn-arsipkan', function() {
                const row = $(this).closest('tr');
                const judul = $(this).data('judul');
                const tipe = row.data('tipe');

                const rowData = row.prop('outerHTML');

                modernSwal.fire({
                    title: 'Arsipkan Buku?',
                    text: `Buku "${judul}" akan dipindahkan ke tab Arsip.`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Ya, Arsipkan',
                    cancelButtonText: 'Batal',
                    confirmButtonColor: '#ffc107',
                }).then((result) => {
                    if (result.isConfirmed) {
                        row.fadeOut(300, function() {
                            const coverHtml = row.find('td:eq(1)').html();
                            const penulis = row.find('td:eq(3)').text();
                            const badgeTipe = tipe === 'offline' ?
                                '<span class="badge bg-secondary"><i class="bi bi-book me-1"></i>Offline</span>' :
                                '<span class="badge bg-info"><i class="bi bi-globe me-1"></i>Online</span>';

                            const originalDataEncoded = encodeURIComponent(rowData);

                            const arsipRow = `
                                <tr data-origin="${originalDataEncoded}">
                                    <td class="row-number"></td>
                                    <td>${coverHtml}</td>
                                    <td class="fw-bold text-muted">${judul}</td>
                                    <td class="text-muted">${penulis}</td>
                                    <td>${badgeTipe}</td>
                                    <td class="text-center">
                                        <button class="btn btn-sm btn-outline-success btn-pulihkan" 
                                            data-judul="${judul}" title="Kembalikan ke Daftar Aktif">
                                            <i class="bi bi-arrow-counterclockwise me-1"></i>Kembalikan
                                        </button>
                                    </td>
                                </tr>
                            `;

                            $('#tableArsip tbody').append(arsipRow);
                            $(this).remove();

                            updateTableNumbers();
                            Toast.fire({
                                icon: 'success',
                                title: 'Diarsipkan',
                                text: `Buku "${judul}" berhasil diarsipkan.`
                            });
                        });
                    }
                });
            });

            // LOGIC PULIHKAN BUKU 
            $(document).on('click', '.btn-pulihkan', function() {
                const row = $(this).closest('tr');
                const judul = $(this).data('judul');
                const originalDataEncoded = row.data('origin');

                modernSwal.fire({
                    title: 'Kembalikan Buku?',
                    text: `Buku "${judul}" akan dikembalikan ke daftar aktif.`,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Ya, Kembalikan',
                    cancelButtonText: 'Batal',
                    confirmButtonColor: '#198754',
                }).then((result) => {
                    if (result.isConfirmed) {
                        row.fadeOut(300, function() {
                            const originalRowHtml = decodeURIComponent(originalDataEncoded);
                            const $originalRow = $(originalRowHtml);

                            const tipe = $originalRow.data('tipe');
                            const targetTable = tipe === 'offline' ? '#tableOffline' : '#tableOnline';

                            $originalRow.removeAttr('style');

                            $(targetTable + ' tbody').append($originalRow);
                            $(this).remove();

                            updateTableNumbers();
                            Toast.fire({
                                icon: 'success',
                                title: 'Dipulihkan',
                                text: `Buku "${judul}" aktif kembali.`
                            });
                        });
                    }
                });
            });

        });
    </script>
    @endpush
</x-app-layout>