import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ 'previews', 'preview', 'file' ]
  static values = {
    multiple: { type: Boolean, default: false },
    limit: { type: Number, default: 1 }
  }

  initialize() {
    this.selectedFiles = []
  }

  attach() {
    const files = Array.from(this.fileTarget.files).slice(0, this.limitValue)

    if (this.multipleValue) {
      this.selectedFiles = this.selectedFiles.concat(files)
      this.createImgElements(this.selectedFiles)
    } else {
      const [file] = files
      if (file) {
        this.selectedFiles = [file]
        this.previewTarget.src = URL.createObjectURL(file)
      }
    }
  }

  createImgElements(files) {
    //this.clearPreview()
    
    files.forEach(file => {
      const img = document.createElement('img')
      const uniqueId = `image_${Date.now()}` // Generate a unique ID
      file.uniqueId = uniqueId // Store the unique ID as a property
      img.src = URL.createObjectURL(file)
      img.setAttribute('data-image-id', uniqueId) // Add a unique attribute
      img.setAttribute('data-action', 'click->image-preview#removeImage')
      this.previewsTarget.appendChild(img)
    })
  }

  clearPreview() {
    while (this.previewsTarget.firstChild) {
      this.previewsTarget.firstChild.remove()
    }
  }

  open() {
    this.fileTarget.click()
  }

  updateFileInput() {
    const dataTransfer = new DataTransfer()

    this.selectedFiles.forEach(file => {
      dataTransfer.items.add(file)
    })

    this.fileTarget.files = dataTransfer.files
  }

  removeImage(event) {
    const imageId = event.target.getAttribute('data-image-id')
    const index = this.selectedFiles.findIndex(file => file.uniqueId === imageId)
    
    if (index !== -1) {
      const removedFile = this.selectedFiles.splice(index, 1)[0]
      //event.target.previousSibling?.remove() // Remove the <img> element
      event.target.remove() // Remove the Remove button
      URL.revokeObjectURL(removedFile.src) // Revoke the object URL
      this.updateFileInput()
    }
  }

  removeSavedImage = (event) => {
    const confirm =  window.confirm("Are you sure to delete?");
    if (!confirm) { return }
    const url =  event.currentTarget.getAttribute('data-url')
    fetch(url, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        "X-CSRF-Token": this.getMetaValue("csrf-token"),
        // Add any other headers you may need, such as authorization headers
      },
      // If you need to send data along with the request, you can include a body
      // For example, to send JSON data:
      // body: JSON.stringify({ key: 'value' }),
    })
      .then(response => {
        if (response.ok) {
          // Request was successful
          event.target.remove()
        } else {
          // Request was not successful
          console.error('Delete request failed');
        }
      })
      .catch(error => {
        console.error('Error occurred during delete request:', error);
      });
    
  }

  getMetaValue = (name) => {
    const element = document.head.querySelector(`meta[name="${name}"]`)
    return element.getAttribute("content")
  }
};
