import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["progressBar", "totalRecords", "processedRecords", "failedRecords", "recordsPerSecond"]
  static values = {
    importId: Number,
    refreshInterval: { type: Number, default: 2000 }
  }

  connect() {
    if (this.hasImportIdValue) {
      this.startUpdating()
    }
  }

  disconnect() {
    this.stopUpdating()
  }

  startUpdating() {
    this.updateProgress()
    this.interval = setInterval(() => {
      this.updateProgress()
    }, this.refreshIntervalValue)
  }

  stopUpdating() {
    if (this.interval) {
      clearInterval(this.interval)
    }
  }

  async updateProgress() {
    try {
      const response = await fetch(`/data_imports/${this.importIdValue}/progress`)
      const data = await response.json()

      this.updateProgressBar(data.progress_percentage)
      this.updateStats(data)

      // If completed or failed, reload the page
      if (data.status === 'completed' || data.status === 'failed') {
        setTimeout(() => {
          window.location.reload()
        }, 2000)
        this.stopUpdating()
      }
    } catch (error) {
      console.error('Error updating progress:', error)
    }
  }

  updateProgressBar(percentage) {
    if (this.hasProgressBarTarget) {
      this.progressBarTarget.style.width = `${percentage}%`
    }
  }

  updateStats(data) {
    if (this.hasTotalRecordsTarget) {
      this.totalRecordsTarget.textContent = data.total_records.toLocaleString()
    }

    if (this.hasProcessedRecordsTarget) {
      this.processedRecordsTarget.textContent = data.processed_records.toLocaleString()
    }

    if (this.hasFailedRecordsTarget) {
      this.failedRecordsTarget.textContent = data.failed_records.toLocaleString()
    }

    if (this.hasRecordsPerSecondTarget) {
      this.recordsPerSecondTarget.textContent = data.records_per_second.toLocaleString()
    }
  }
}