// assets/controllers/preferred-sources_controller.js

import {Controller} from "@hotwired/stimulus"
import Sortable from 'sortablejs'

export default class extends Controller {
  static targets = ["preferredList", "availableList"]
  static values = {
    mangaId: Number,
    preferredSources: Array,
    allSources: Array
  }

  connect() {
    this.initSortable()
  }

  initSortable() {
    new Sortable(this.preferredListTarget, {
      animation: 150,
      ghostClass: 'bg-gray-300',
      onEnd: this.handleDragEnd.bind(this)
    })
  }

  handleDragEnd() {
    this.updatePreferredSources()
  }

  addSource(event) {
    const sourceId = parseInt(event.currentTarget.dataset.sourceId)
    if (!this.preferredSourcesValue.includes(sourceId)) {
      this.preferredSourcesValue = [...this.preferredSourcesValue, sourceId]
      this.updateLists()
      this.save()
    }
  }

  removeSource(event) {
    const sourceId = parseInt(event.currentTarget.dataset.sourceId)
    this.preferredSourcesValue = this.preferredSourcesValue.filter(id => id !== sourceId)
    this.updateLists()
    this.save()
  }

  updatePreferredSources() {
    this.preferredSourcesValue = Array.from(this.preferredListTarget.children).map(li => parseInt(li.dataset.id))
    this.save()
  }

  updateLists() {
    this.preferredListTarget.innerHTML = this.preferredSourcesValue
      .map(id => this.allSourcesValue.find(s => s.id === id))
      .map(source => this.sourceTemplate(source, true))
      .join('')

    this.availableListTarget.innerHTML = this.allSourcesValue
      .filter(source => !this.preferredSourcesValue.includes(source.id))
      .map(source => this.sourceTemplate(source, false))
      .join('')

    this.initSortable()
  }

  sourceTemplate(source, isPreferred) {
    return `
      <li data-id="${source.id}" draggable="true" class="flex items-center justify-between p-2 bg-gray-100 rounded ${isPreferred ? 'cursor-move' : ''}">
        <span>${source.name}</span>
        <button type="button" data-action="preferred-sources#${isPreferred ? 'removeSource' : 'addSource'}" data-source-id="${source.id}" class="text-${isPreferred ? 'red' : 'green'}-500 hover:text-${isPreferred ? 'red' : 'green'}-700">
          <i class="fas fa-${isPreferred ? 'times' : 'plus'}"></i>
        </button>
      </li>
    `
  }

  async save() {
    try {
      const response = await fetch(`/manga/${this.mangaIdValue}/preferred-sources`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
          preferredSources: this.preferredSourcesValue
        })
      })

      if (response.ok) {
        console.log('Preferred sources saved successfully')
        // Optionally show a success message
      } else {
        console.error('Error saving preferred sources')
        // Optionally show an error message
      }
    } catch (error) {
      console.error('Error:', error)
      // Optionally show an error message
    }
  }
}
