import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["eventsCount", "rulesCount", "networkRangesCount", "systemHealth", "recentEvents", "topBlockedIps"]
  static values = {
    period: String,
    refreshInterval: { type: Number, default: 30000 } // 30 seconds
  }

  connect() {
    this.startRefreshing()
  }

  disconnect() {
    this.stopRefreshing()
  }

  startRefreshing() {
    this.refreshTimer = setInterval(() => {
      this.refreshDashboard()
    }, this.refreshIntervalValue)
  }

  stopRefreshing() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
  }

  async refreshDashboard() {
    try {
      const response = await fetch(`/analytics?period=${this.periodValue}`, {
        headers: {
          "Accept": "text/vnd.turbo-stream.html"
        }
      })

      if (response.ok) {
        const html = await response.text()
        Turbo.renderStreamMessage(html)
      }
    } catch (error) {
      console.error("Failed to refresh dashboard:", error)
    }
  }

  periodChanged(event) {
    this.periodValue = event.currentTarget.dataset.period
    this.refreshDashboard()
  }
}