// assets/controllers/toolbar_controller.js
import { Controller } from "@hotwired/stimulus"
import { visit } from "@hotwired/turbo"

export default class extends Controller {
  static targets = ["dropdown", "icon", "text"]
  static values = {
    currentSort: String,
    currentOrder: String,
    currentStatus: String,
    mangaId: Number
  }

  connect() {
    window.addEventListener('alert:show', this.stopLoading.bind(this));
  }

  stopLoading(event) {
    if(event.currentTarget.dataset !== undefined){
      this.iconTarget.classList.remove('fa-spin');
    }
  }

  refreshMetadata(event) {
    const mangaId = event.currentTarget.dataset.mangaid;
    const url = `/refresh_metadata`;

    this.iconTarget.classList.add('fa-spin');

    fetch(url, {
      method: 'POST',
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ mangaId: mangaId })
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      });
  }

  searchLastChapter() {
    console.log("Searching last chapter...");
  }

  import() {
    console.log("Importing...");
  }

  monitoring(event){
    const mangaId = event.currentTarget.dataset.mangaid;
    const currentTarget = event.currentTarget;

    const url = `/toggle_monitored`;

    fetch(url, {
      method: 'POST',
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ mangaId: mangaId })
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      }).then(data => {
        if(data.isMonitored === true){
          currentTarget.classList.remove('text-white');
          currentTarget.classList.add('text-green-500');
          this.textTarget.innerHTML = "Monitored";
        }else if(data.isMonitored === false){
          currentTarget.classList.remove('text-green-500');
          currentTarget.classList.add('text-white');
          this.textTarget.innerHTML = "Monitoring";
        }
        // console.log(data.isMonitored);
    });

  }

  editMangas() {
    console.log("Editing mangas...");
  }

  editManga() {
    const event = new CustomEvent('openEditModal');
    document.dispatchEvent(event);
  }

  editPreferredSources() {
    const event = new CustomEvent('openPreferredSourcesModal');
    document.dispatchEvent(event);
  }

  openImportModal() {
    const importEvent = new CustomEvent('openImportModal');
    document.dispatchEvent(importEvent);
  }

  openExportModal() {
    const exportEvent = new CustomEvent('openExportModal');
    document.dispatchEvent(exportEvent);
  }

  deleteMangas() {
    console.log("Deleting mangas...");
  }

  deleteManga() {
    const event = new CustomEvent('openDeleteModal');
    document.dispatchEvent(event);
  }

  confirmDelete(event) {
    event.preventDefault();
    const url = `/manga/delete/${this.mangaIdValue}`;

    fetch(url, {
      method: 'DELETE',
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json',
      }
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        if (data.success) {
          visit('/', {});
        } else {
          throw new Error(data.error);
        }
      })
      .catch(error => {
        console.error('Error:', error);
        // Show error message to user
      });
  }

  showOptions() {
    console.log("Showing options...");
  }

  expandAll() {
    console.log("Expanding all...");
  }

  changeView(event) {
    event.preventDefault();
    const viewOption = event.currentTarget.dataset.view;

    const url = new URL(window.location);
    url.searchParams.set('view', viewOption);

    window.location = url.toString();
  }

  sort(event) {
    event.preventDefault()
    const sortOption = event.currentTarget.dataset.sort;
    let order = 'asc';

    if (sortOption === this.currentSortValue && this.currentOrderValue === 'asc') {
      order = 'desc';
    }

    const url = new URL(window.location);
    url.searchParams.set('sort', sortOption);
    url.searchParams.set('order', order);

    window.location = url.toString();
  }

  filter(event) {
    event.preventDefault();
    const filterOption = event.currentTarget.dataset.filter;

    const url = new URL(window.location);
    url.searchParams.set('status', filterOption);

    // Réinitialiser la page à 1 si on utilise la pagination
    // url.searchParams.set('page', '1');

    window.location = url.toString();
  }

}
