const formPeminjamanElement = document.getElementById('formPeminjaman');

if (formPeminjamanElement) {
    // Ambil data yang sudah disimpan di elemen HTML
    const semuaBuku = JSON.parse(formPeminjamanElement.dataset.semuaBuku);
    const bukuAwal = JSON.parse(formPeminjamanElement.dataset.bukuAwal);

    let bukuTerpilih = [bukuAwal.id];
    const maxBuku = 2;

    document.addEventListener('DOMContentLoaded', function () {
        updateCounter();
        updateSelectedBooks();
        updateCheckboxes();
        updateBtnTambahBuku();
        updateDaftarBuku();
    });

    function updateCounter() {
        document.getElementById('counterBuku').textContent = bukuTerpilih.length;
        document.getElementById('sisaSlot').textContent = maxBuku - bukuTerpilih.length;
    }

    function updateBtnTambahBuku() {
        const btnTambah = document.getElementById('btnTambahBuku');
        if (bukuTerpilih.length >= maxBuku) {
            btnTambah.classList.add('disabled');
            btnTambah.innerHTML = '<i class="bi bi-check-circle me-1"></i>Maksimal Buku Tercapai';
        } else {
            btnTambah.classList.remove('disabled');
            btnTambah.innerHTML = '<i class="bi bi-plus-circle me-1"></i>Tambah Buku';
        }
    }

    function updateSelectedBooks() {
        const container = document.getElementById('selectedBooks');
        const selected = semuaBuku.filter(book => bukuTerpilih.includes(book.id));
        container.innerHTML = selected.map(book => `<li>${book.judul}</li>`).join('');
    }

    function updateCheckboxes() {
        document.querySelectorAll('.book-checkbox').forEach(checkbox => {
            const bookId = parseInt(checkbox.value);
            checkbox.checked = bukuTerpilih.includes(bookId);

            if (bukuTerpilih.length >= maxBuku && !bukuTerpilih.includes(bookId)) {
                checkbox.disabled = true;
            } else if (bookId !== bukuAwal.id) {
                checkbox.disabled = false;
            }
        });
    }

    window.toggleBookSelection = function (bookId) {
        if (bookId === bukuAwal.id) return;

        const checkbox = document.getElementById('book' + bookId);
        if (!checkbox.disabled) {
            checkbox.checked = !checkbox.checked;
            handleCheckboxChange(checkbox);
        }
    }

    function handleCheckboxChange(checkbox) {
        const bookId = parseInt(checkbox.value);
        if (checkbox.checked) {
            if (bukuTerpilih.length < maxBuku && !bukuTerpilih.includes(bookId)) {
                bukuTerpilih.push(bookId);
            } else {
                checkbox.checked = false;
                return;
            }
        } else {
            bukuTerpilih = bukuTerpilih.filter(id => id !== bookId);
        }

        updateCounter();
        updateSelectedBooks();
        updateCheckboxes();
        updateBtnTambahBuku();
    }

    document.addEventListener('change', function (e) {
        if (e.target.classList.contains('book-checkbox')) {
            if (e.target.value != bukuAwal.id) {
                handleCheckboxChange(e.target);
            }
        }
    });

    document.getElementById('searchBuku')?.addEventListener('input', function (e) {
        const searchTerm = e.target.value.toLowerCase();
        document.querySelectorAll('.book-option').forEach(option => {
            const title = option.getAttribute('data-book-title');
            const author = option.getAttribute('data-book-author');

            if (title.includes(searchTerm) || author.includes(searchTerm)) {
                option.style.display = 'block';
            } else {
                option.style.display = 'none';
            }
        });
    });

    function updateDaftarBuku() {
        const container = document.getElementById('daftarBukuPinjam');
        const hiddenInputs = document.getElementById('hiddenInputs');
        const selected = semuaBuku.filter(book => bukuTerpilih.includes(book.id));

        container.innerHTML = selected.map((book) => `
            <div class="book-item border rounded p-3 mb-3 shadow-sm" data-book-id="${book.id}">
                <div class="d-flex align-items-start">
                
                <img src="/${book.cover}" alt="Cover" 
                    class="rounded me-3 form-book-cover"
                    style="width: 60px; height: 80px; object-fit: cover;">
                
                <div class="flex-grow-1">
                    <h6 class="fw-bold mb-1">${book.judul}</h6>
                    <p class="text-muted small mb-1">${book.penulis}</p>
                    <span class="badge bg-info">${book.kategori}</span>
                </div>
                
                <div class="d-flex flex-column align-items-end gap-2">
                    ${book.id === bukuAwal.id
                            ? '<span class="badge bg-success">Buku Utama</span>'
                            : '<span class="badge bg-primary">Tambahan</span>'}
                    
                    ${book.id !== bukuAwal.id
                            ? `<button type="button" class="btn btn-sm btn-outline-danger remove-book" 
                            onclick="removeBuku(${book.id})" 
                            title="Hapus Buku">
                            <i class="bi bi-trash"></i>
                        </button>`
                            : ''}
                </div>
                </div>
            </div>
            `).join('');


        hiddenInputs.innerHTML = bukuTerpilih.map(id =>
            `<input type="hidden" name="buku_ids[]" value="${id}">`
        ).join('');
    }

    window.removeBuku = function (bookId) {
        if (bookId !== bukuAwal.id) {
            bukuTerpilih = bukuTerpilih.filter(id => id !== bookId);
            updateDaftarBuku();
            updateCounter();
            updateSelectedBooks();
            updateCheckboxes();
            updateBtnTambahBuku();
        }
    }

    window.konfirmasiPilihanBuku = function () {
        updateDaftarBuku();
        const modal = bootstrap.Modal.getInstance(document.getElementById('pilihBukuModal'));
        modal.hide();
    }

    document.getElementById('konfirmasiModal')?.addEventListener('show.bs.modal', function () {
        const selected = semuaBuku.filter(book => bukuTerpilih.includes(book.id));
        const ringkasan = selected.map((book, index) =>
            `<div class="d-flex justify-content-between">
                <span>${index + 1}. ${book.judul}</span>
                <small class="text-muted">${book.penulis}</small>
            </div>`
        ).join('');
        document.getElementById('ringkasanBuku').innerHTML = ringkasan;
    });

    window.kirimForm = function () {
        document.getElementById('formPeminjaman').submit();
    }

    document.getElementById('pilihBukuModal')?.addEventListener('hidden.bs.modal', function () {
        const searchInput = document.getElementById('searchBuku');
        if (searchInput) {
            searchInput.value = '';
            document.querySelectorAll('.book-option').forEach(option => {
                option.style.display = 'block';
            });
        }
    });
}