/* =============================================
   admin.js — Admin CRUD E-Book Logic
   ============================================= */

'use strict';

let currentAdminPage = 1;
let currentAdminSearch = '';
let currentAdminKategori = '';
let deleteTargetId = null;
const ADMIN_LIMIT = 10;

function initAdminEbooks() {
  loadAdminEbooks(1);

  // Search
  const searchInp = document.getElementById('adminSearchInput');
  const searchClr = document.getElementById('adminSearchClear');
  const katFilter = document.getElementById('adminKategoriFilter');

  searchInp && searchInp.addEventListener('input', debounce(e => {
    currentAdminSearch = e.target.value.trim();
    searchClr && searchClr.classList.toggle('d-none', !currentAdminSearch);
    loadAdminEbooks(1);
  }));

  searchClr && searchClr.addEventListener('click', () => {
    searchInp.value = '';
    currentAdminSearch = '';
    searchClr.classList.add('d-none');
    loadAdminEbooks(1);
  });

  katFilter && katFilter.addEventListener('change', e => {
    currentAdminKategori = e.target.value;
    loadAdminEbooks(1);
  });

  // Form submit
  const form = document.getElementById('ebookForm');
  form && form.addEventListener('submit', handleEbookFormSubmit);

  // Delete confirm
  const confirmBtn = document.getElementById('confirmDeleteBtn');
  confirmBtn && confirmBtn.addEventListener('click', handleDeleteConfirm);

  // File upload previews
  setupFileUploads();

  // PDF modal reset on close
  const viewModal = document.getElementById('viewPdfModal');
  viewModal && viewModal.addEventListener('hidden.bs.modal', () => {
    document.getElementById('viewPdfFrame').src = '';
    document.getElementById('viewPdfLoading').style.display = 'flex';
    document.getElementById('viewPdfFrame').classList.add('d-none');
  });
}

// -----------------------------------------------
// Load Ebook Table
// -----------------------------------------------
function loadAdminEbooks(page) {
  currentAdminPage = page;
  const tbody = document.getElementById('adminEbookBody');
  const info = document.getElementById('adminTableInfo');
  const paginEl = document.getElementById('adminPaginationWrapper');
  const countBadge = document.getElementById('adminResultsCount');

  tbody.innerHTML = `<tr><td colspan="7" class="text-center py-5"><div class="table-loading"><i class="fas fa-spinner fa-spin"></i> Memuat data...</div></td></tr>`;

  let url = `api/ebooks?page=${page}&limit=${ADMIN_LIMIT}`;
  if (currentAdminSearch) url += `&search=${encodeURIComponent(currentAdminSearch)}`;
  if (currentAdminKategori) url += `&kategori=${encodeURIComponent(currentAdminKategori)}`;

  apiGet(url).then(res => {
    if (!res.status) {
      tbody.innerHTML = `<tr><td colspan="7" class="text-center py-4 text-muted">Gagal memuat data</td></tr>`;
      return;
    }
    const { ebooks, total, total_pages } = res.data;

    if (countBadge) countBadge.textContent = `${total} ebook`;

    if (ebooks.length === 0) {
      tbody.innerHTML = `
        <tr><td colspan="7">
          <div class="empty-state" style="padding:60px 20px">
            <i class="fas fa-book-open"></i>
            <h4>${currentAdminSearch ? `"${escHtml(currentAdminSearch)}" tidak ditemukan` : 'Belum ada e-book'}</h4>
            <p>${currentAdminSearch ? 'Coba kata kunci lain.' : 'Klik "Tambah E-Book" untuk menambahkan.'}</p>
          </div>
        </td></tr>`;
      if (paginEl) paginEl.innerHTML = '';
      if (info) info.textContent = '';
      return;
    }

    tbody.innerHTML = ebooks.map((e, i) => `
      <tr id="row-${e.id}">
        <td>${(page - 1) * ADMIN_LIMIT + i + 1}</td>
        <td>
          ${e.cover_url && !e.cover_url.includes('no-cover')
        ? `<img src="${e.cover_url}" class="table-cover" alt="" loading="lazy">`
        : `<div class="table-cover-placeholder"><i class="fas fa-book"></i></div>`}
        </td>
        <td><span class="table-title">${escHtml(e.judul)}</span></td>
        <td>${escHtml(e.penulis)}</td>
        <td><span class="badge-kategori">${escHtml(e.kategori)}</span></td>
        <td>${formatDate(e.created_at)}</td>
        <td>
          <div class="table-actions">
            <button class="btn-action btn-view" title="Lihat PDF" onclick="adminViewPdf(${e.id})">
              <i class="fas fa-eye"></i>
            </button>
            <button class="btn-action btn-edit" title="Edit" onclick="openEditModal(${e.id})">
              <i class="fas fa-pen"></i>
            </button>
            <button class="btn-action btn-delete" title="Hapus" onclick="openDeleteModal(${e.id}, '${escHtml(e.judul)}')">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </td>
      </tr>`).join('');

    // Info & pagination
    const from = (page - 1) * ADMIN_LIMIT + 1;
    const to = Math.min(page * ADMIN_LIMIT, total);
    if (info) info.textContent = `Menampilkan ${from}–${to} dari ${total} e-book`;
    if (paginEl) paginEl.innerHTML = renderAdminPagination(page, total_pages);

  }).catch(() => {
    tbody.innerHTML = `<tr><td colspan="7" class="text-center py-4 text-danger">Koneksi gagal</td></tr>`;
  });
}

// -----------------------------------------------
// Open Add Modal
// -----------------------------------------------
function openAddModal() {
  const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('ebookModal'));
  const form = document.getElementById('ebookForm');

  document.getElementById('ebookModalLabel').textContent = 'Tambah E-Book Baru';
  document.getElementById('ebookId').value = '';
  document.getElementById('pdfRequired').style.display = '';
  form.reset();
  clearUpload('pdf');
  clearUpload('cover');
  resetFormSaveBtn();
  modal.show();
}

// -----------------------------------------------
// Open Edit Modal
// -----------------------------------------------
function openEditModal(id) {
  apiGet(`api/ebooks/${id}`).then(res => {
    if (!res.status) { showToast('danger', 'Error', 'Gagal memuat data ebook.'); return; }
    const e = res.data;

    const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('ebookModal'));
    document.getElementById('ebookModalLabel').textContent = 'Edit E-Book';
    document.getElementById('ebookId').value = id;
    document.getElementById('fJudul').value = e.judul;
    document.getElementById('fPenulis').value = e.penulis;
    document.getElementById('fKategori').value = e.kategori;
    document.getElementById('fDeskripsi').value = e.deskripsi || '';
    document.getElementById('pdfRequired').style.display = 'none';

    // Show current cover preview
    if (e.cover_url && !e.cover_url.includes('no-cover')) {
      const img = document.getElementById('coverPreviewImg');
      const ph = document.getElementById('coverPlaceholder');
      img.src = e.cover_url;
      img.classList.remove('d-none');
      ph.classList.add('d-none');
      document.getElementById('coverClearBtn').classList.remove('d-none');
    }

    resetFormSaveBtn();
    modal.show();
  });
}

// -----------------------------------------------
// Handle Form Submit
// -----------------------------------------------
async function handleEbookFormSubmit(e) {
  e.preventDefault();
  const id = document.getElementById('ebookId').value;
  const btn = document.getElementById('ebookSaveBtn');

  const judul = document.getElementById('fJudul').value.trim();
  const penulis = document.getElementById('fPenulis').value.trim();
  const kategori = document.getElementById('fKategori').value.trim();

  if (!judul || !penulis || !kategori) {
    showToast('warning', 'Validasi', 'Judul, penulis, dan kategori wajib diisi.'); return;
  }

  if (!id && !document.getElementById('fFile').files.length) {
    showToast('warning', 'Validasi', 'File PDF wajib diunggah.'); return;
  }

  setFormLoading(btn, true);

  const fd = new FormData(e.target);
  const url = id ? `api/ebooks/${id}` : `api/ebooks`;

  try {
    const res = await fetch(BASE_URL + url, { method: 'POST', body: fd });
    const data = await res.json();

    if (data.status) {
      bootstrap.Modal.getInstance(document.getElementById('ebookModal')).hide();
      showToast('success', 'Berhasil!', id ? 'E-Book berhasil diperbarui.' : 'E-Book baru berhasil ditambahkan.');
      loadAdminEbooks(id ? currentAdminPage : 1);
    } else {
      showToast('danger', 'Gagal', data.message);
    }
  } catch (err) {
    showToast('danger', 'Error', 'Koneksi gagal. Coba lagi.');
  } finally {
    setFormLoading(btn, false);
  }
}

// -----------------------------------------------
// Delete
// -----------------------------------------------
function openDeleteModal(id, judul) {
  deleteTargetId = id;
  document.getElementById('deleteEbookTitle').textContent = `"${judul}" akan dihapus permanen beserta filenya.`;
  bootstrap.Modal.getOrCreateInstance(document.getElementById('deleteModal')).show();
}

async function handleDeleteConfirm() {
  if (!deleteTargetId) return;
  const btn = document.getElementById('confirmDeleteBtn');
  btn.querySelector('.btn-text').classList.add('d-none');
  btn.querySelector('.btn-loader').classList.remove('d-none');
  btn.disabled = true;

  try {
    const res = await fetch(BASE_URL + `api/ebooks/${deleteTargetId}`, { method: 'DELETE' });
    const data = await res.json();

    bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();

    if (data.status) {
      showToast('success', 'Dihapus!', 'E-Book berhasil dihapus.');
      loadAdminEbooks(currentAdminPage);
    } else {
      showToast('danger', 'Gagal', data.message);
    }
  } catch {
    showToast('danger', 'Error', 'Koneksi gagal.');
  } finally {
    btn.querySelector('.btn-text').classList.remove('d-none');
    btn.querySelector('.btn-loader').classList.add('d-none');
    btn.disabled = false;
    deleteTargetId = null;
  }
}

// -----------------------------------------------
// Admin PDF Viewer
// -----------------------------------------------
function adminViewPdf(id) {
  const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('viewPdfModal'));
  const frame = document.getElementById('viewPdfFrame');
  const loading = document.getElementById('viewPdfLoading');
  const titleEl = document.getElementById('viewPdfTitle');
  const authEl = document.getElementById('viewPdfAuthor');
  const dlBtn = document.getElementById('adminBtnDownload');

  frame.classList.add('d-none');
  loading.style.display = 'flex';
  frame.src = '';
  modal.show();

  apiGet(`api/ebooks/${id}`).then(res => {
    if (!res.status) { showToast('danger', 'Error', 'Ebook tidak ditemukan.'); modal.hide(); return; }
    const e = res.data;
    titleEl.textContent = e.judul;
    authEl.textContent = `${e.penulis} · ${e.kategori}`;
    dlBtn.href = e.file_url;
    dlBtn.setAttribute('download', e.judul + '.pdf');

    frame.src = e.file_url;
    frame.onload = () => {
      loading.style.display = 'none';
      frame.classList.remove('d-none');
    };
    setTimeout(() => {
      if (frame.classList.contains('d-none')) {
        loading.style.display = 'none';
        frame.classList.remove('d-none');
      }
    }, 3000);
  });
}

// -----------------------------------------------
// File Upload Setup
// -----------------------------------------------
function setupFileUploads() {
  // PDF
  const pdfInput = document.getElementById('fFile');
  if (pdfInput) {
    pdfInput.addEventListener('change', function () {
      if (this.files[0]) {
        document.getElementById('pdfFileName').textContent = this.files[0].name;
        document.getElementById('pdfPreview').classList.remove('d-none');
        document.getElementById('pdfUploadZone').style.display = 'none';
      }
    });
  }

  // Cover
  const coverInput = document.getElementById('fCover');
  if (coverInput) {
    coverInput.addEventListener('change', function () {
      if (this.files[0]) {
        const reader = new FileReader();
        reader.onload = e => {
          const img = document.getElementById('coverPreviewImg');
          const ph = document.getElementById('coverPlaceholder');
          const clr = document.getElementById('coverClearBtn');
          img.src = e.target.result;
          img.classList.remove('d-none');
          ph.classList.add('d-none');
          clr.classList.remove('d-none');
        };
        reader.readAsDataURL(this.files[0]);
      }
    });
  }

  // Drag & Drop
  ['pdfUploadZone', 'coverUploadZone'].forEach(zoneId => {
    const zone = document.getElementById(zoneId);
    if (!zone) return;
    zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
    zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
    zone.addEventListener('drop', e => { e.preventDefault(); zone.classList.remove('drag-over'); });
  });
}

function clearUpload(type) {
  if (type === 'pdf') {
    const inp = document.getElementById('fFile');
    if (inp) inp.value = '';
    document.getElementById('pdfPreview').classList.add('d-none');
    document.getElementById('pdfUploadZone').style.display = '';
    document.getElementById('pdfFileName').textContent = '';
  } else {
    const inp = document.getElementById('fCover');
    if (inp) inp.value = '';
    const img = document.getElementById('coverPreviewImg');
    const ph = document.getElementById('coverPlaceholder');
    const clr = document.getElementById('coverClearBtn');
    img.src = '';
    img.classList.add('d-none');
    ph.classList.remove('d-none');
    clr && clr.classList.add('d-none');
  }
}

// -----------------------------------------------
// Helpers
// -----------------------------------------------
function setFormLoading(btn, state) {
  btn.querySelector('.btn-text').classList.toggle('d-none', state);
  btn.querySelector('.btn-loader').classList.toggle('d-none', !state);
  btn.disabled = state;
}

function resetFormSaveBtn() {
  const btn = document.getElementById('ebookSaveBtn');
  if (!btn) return;
  btn.querySelector('.btn-text').classList.remove('d-none');
  btn.querySelector('.btn-loader').classList.add('d-none');
  btn.disabled = false;
}

function renderAdminPagination(current, total) {
  if (total <= 1) return '';
  let html = '';
  html += `<button class="page-btn" onclick="loadAdminEbooks(${current - 1})" ${current <= 1 ? 'disabled' : ''}><i class="fas fa-chevron-left"></i></button>`;
  for (let p = Math.max(1, current - 2); p <= Math.min(total, current + 2); p++) {
    html += `<button class="page-btn ${p === current ? 'active' : ''}" onclick="loadAdminEbooks(${p})">${p}</button>`;
  }
  html += `<button class="page-btn" onclick="loadAdminEbooks(${current + 1})" ${current >= total ? 'disabled' : ''}><i class="fas fa-chevron-right"></i></button>`;
  return html;
}

function formatDate(str) {
  if (!str) return '-';
  const d = new Date(str);
  return d.toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' });
}
