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

export default class extends Controller {
  static targets = ['pageContainer', 'currentPage', 'chapterSelect', 'readingModeButton']
  static values = {
    mangaSlug: String,
    chapterNumber: Number,
    totalPages: Number,
    currentPage: { type: Number, default: 1 },
    readingMode: { type: String, default: 'horizontal' }
  }

  connect() {
    this.loadChapters();
    this.loadPages();
  }

  async loadChapters() {
    try {
      const response = await fetch(`/api/chapters/${this.mangaSlugValue}`);
      const chapters = await response.json();

      this.chapterSelectTarget.innerHTML = chapters.map(chapter =>
        `<option value="${chapter.number}" ${chapter.number === this.chapterNumberValue ? 'selected' : ''}>
          Chapitre ${chapter.number}
        </option>`
      ).join('');
    } catch (error) {
      console.error('Error loading chapters:', error);
    }
  }

  async loadPages() {
    this.pageContainerTarget.innerHTML = '';
    if (this.readingModeValue === 'horizontal') {
      await this.loadPage(this.currentPageValue);
    } else {
      for (let i = 1; i <= this.totalPagesValue; i++) {
        await this.loadPage(i, true);
      }
    }
  }

  async loadPage(pageNumber, isVertical = false) {
    const response = await fetch(`/api/read/${this.mangaSlugValue}/${this.chapterNumberValue}/${pageNumber}`);
    const pageContent = await response.text();

    const img = document.createElement('img');
    img.src = `data:image/jpeg;base64,${pageContent}`;
    img.alt = `Page ${pageNumber}`;
    img.classList.add('shadow-lg', 'w-full', 'h-auto');

    if (this.readingModeValue === 'horizontal') {
      img.classList.add('cursor-pointer');
      img.dataset.action = 'click->reader#pageClick';
      this.pageContainerTarget.innerHTML = '';
    }

    if (isVertical) {
      img.loading = 'lazy';
      img.classList.add('mb-4');
    }

    this.pageContainerTarget.appendChild(img);

    if (!isVertical) {
      this.currentPageTarget.textContent = pageNumber;
      this.currentPageValue = pageNumber;
    }
  }

  pageClick(event) {
    if (this.readingModeValue === 'horizontal') {
      const pageWidth = event.target.offsetWidth;
      const clickX = event.offsetX;

      if (clickX < pageWidth / 2) {
        this.previousPage();
      } else {
        this.nextPage();
      }
    }
  }

  previousPage() {
    if (this.currentPageValue > 1) {
      this.loadPage(this.currentPageValue - 1);
    } else {
      this.previousChapter();
    }
  }

  nextPage() {
    if (this.currentPageValue < this.totalPagesValue) {
      this.loadPage(this.currentPageValue + 1);
    } else {
      this.nextChapter();
    }
  }

  async previousChapter() {
    const response = await fetch(`/api/previous-chapter/${this.mangaSlugValue}/${this.chapterNumberValue}`);
    const previousChapter = await response.json();
    if (previousChapter) {
      window.location.href = `/read/${this.mangaSlugValue}/${previousChapter.number}`;
    }
  }

  async nextChapter() {
    const response = await fetch(`/api/next-chapter/${this.mangaSlugValue}/${this.chapterNumberValue}`);
    const nextChapter = await response.json();
    if (nextChapter) {
      window.location.href = `/read/${this.mangaSlugValue}/${nextChapter.number}`;
    }
  }

  changeChapter(event) {
    const selectedChapterNumber = event.target.value;
    window.location.href = `/read/${this.mangaSlugValue}/${selectedChapterNumber}`;
  }

  toggleReadingMode() {
    this.readingModeValue = this.readingModeValue === 'horizontal' ? 'vertical' : 'horizontal';
    this.readingModeButtonTarget.textContent = this.readingModeValue === 'horizontal' ? 'Passer en mode vertical' : 'Passer en mode horizontal';
    this.loadPages();
  }
}
