<template>
  <v-container fluid class="py-6">
    <v-tabs v-model="tab" color="accent" class="mb-4">
      <v-tab value="overview">Overview</v-tab>
      <v-tab value="import">Import</v-tab>
      <v-tab value="maintenance">Maintenance</v-tab>
    </v-tabs>

    <v-window v-model="tab">
      <v-window-item value="overview">
        <SystemStatsCards :stats="system.stats" />
        <v-alert
          v-if="system.stats && (system.stats.tasks.pending + system.stats.tasks.queued) > 0"
          type="info" variant="tonal" class="mt-4" closable
        >
          {{ system.stats.tasks.pending + system.stats.tasks.queued }} import task(s) pending.
          <v-btn variant="text" size="small" @click="tab = 'import'">Go to Import tab</v-btn>
        </v-alert>
      </v-window-item>

      <v-window-item value="import">
        <ImportTriggerPanel />
        <v-divider class="my-6" />
        <ImportFiltersForm />
        <v-divider class="my-6" />
        <ImportTaskList />
      </v-window-item>

      <v-window-item value="maintenance">
        <MaintenancePanel />
      </v-window-item>
    </v-window>
  </v-container>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { useSystemStore } from '../stores/system.js'
import { useImportStore } from '../stores/import.js'
import SystemStatsCards from '../components/settings/SystemStatsCards.vue'
import ImportTriggerPanel from '../components/settings/ImportTriggerPanel.vue'
import ImportFiltersForm from '../components/settings/ImportFiltersForm.vue'
import ImportTaskList from '../components/settings/ImportTaskList.vue'
import MaintenancePanel from '../components/settings/MaintenancePanel.vue'
import { useMLStore } from '../stores/ml.js'

const tab = ref('overview')
const system = useSystemStore()
const importStore = useImportStore()
const mlStore = useMLStore()

let pollId = null

function startPolling() {
  if (pollId) return
  system.refreshStats()
  pollId = setInterval(() => {
    if (!document.hidden) {
      system.refreshStats()
      if (tab.value === 'import') {
        importStore.refreshStatus()
        // Refresh the task list while a batch is in flight so the UI
        // doesn't sit stale next to a ticking imported/skipped counter.
        if (importStore.activeBatch) importStore.loadTasks(true)
      }
    }
  }, 5000)
}

function stopPolling() {
  if (pollId) { clearInterval(pollId); pollId = null }
}

onMounted(() => {
  startPolling()
  importStore.loadSettings()
  importStore.refreshStatus()
  importStore.loadTasks(true)
})
onUnmounted(stopPolling)

watch(tab, (t) => {
  if (t === 'import') {
    importStore.refreshStatus()
    importStore.loadTasks(true)
  } else if (t === 'maintenance') {
    mlStore.loadSettings()
  }
})
</script>
