import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
  static targets = ["checkbox", "modal", "modalContent"]

  toggleAllCheckboxes(event) {
    this.checkboxTargets.forEach(checkbox => {
      checkbox.checked = event.target.checked;
    });
  }

  updateMangaInfo(event) {
    const select = event.target;
    const selectedOption = select.options[select.selectedIndex];
    const mangaInfo = JSON.parse(selectedOption.dataset.mangaInfo);
  }

  showDetails(event) {
    const fileId = event.currentTarget.dataset.fileId;
    const select = document.querySelector(`select[name="manga_slug[${fileId}]"]`);
    const mangaInfo = JSON.parse(select.options[select.selectedIndex].dataset.mangaInfo);

    this.modalContentTarget.innerHTML = `
            <h3 class="text-lg leading-6 font-medium text-gray-900">${mangaInfo.title}</h3>
            <div class="mt-2">
                <p><strong>Author:</strong> ${mangaInfo.author || 'N/A'}</p>
                <p><strong>Publication Year:</strong> ${mangaInfo.publicationYear || 'N/A'}</p>
                <p><strong>Genres:</strong> ${mangaInfo.genres ? mangaInfo.genres.join(', ') : 'N/A'}</p>
                <p><strong>Description:</strong> ${this.truncate(mangaInfo.description || 'N/A', 200)}</p>
            </div>
        `;

    this.modalTarget.classList.remove('hidden');
  }

  closeModal() {
    this.modalTarget.classList.add('hidden');
  }

  confirmSelected(event) {
    const selectedFiles = this.checkboxTargets.filter(checkbox => checkbox.checked).map(checkbox => checkbox.value);
    if (selectedFiles.length === 0) {
      event.preventDefault();
      alert('Veuillez sélectionner au moins un fichier à importer.');
    }
  }

  truncate(str, length) {
    return str.length > length ? str.substring(0, length) + '...' : str;
  }
}
