<template>
  <div>
    <div class="page-header">
      <h2>Zabbix Supplies</h2>
    </div>

    <div class="section-card">
      <div class="setting-group">
        <p class="setting-description">
          Connect to Zabbix for real-time printer supply monitoring. When enabled, supply levels
          are fetched from Zabbix API and displayed on printer detail pages.
        </p>

        <div class="setting-row">
          <label class="toggle-label">
            <span>Enable Zabbix Integration</span>
            <button
              class="toggle-btn"
              :class="{ active: settings.zabbix_enabled }"
              @click="toggleSetting('zabbix_enabled')"
              :disabled="saving"
            >
              <span class="toggle-slider"></span>
            </button>
          </label>
        </div>

        <div class="setting-row" v-if="settings.zabbix_enabled">
          <label>
            <span>Zabbix API URL</span>
            <input
              type="url"
              v-model="settings.zabbix_url"
              placeholder="http://zabbix.example.com:8080"
              @blur="saveSetting('zabbix_url', settings.zabbix_url)"
              :disabled="saving"
            >
          </label>
        </div>

        <div class="setting-row" v-if="settings.zabbix_enabled">
          <label>
            <span>Zabbix API Token</span>
            <input
              type="password"
              v-model="settings.zabbix_token"
              placeholder="Enter API token"
              @blur="saveSetting('zabbix_token', settings.zabbix_token)"
              :disabled="saving"
            >
          </label>
        </div>

        <div class="status-indicator" v-if="settings.zabbix_enabled">
          <span class="status-dot" :class="zabbixStatus"></span>
          <span>{{ zabbixMessage }}</span>
        </div>
      </div>
    </div>

    <div v-if="error" class="error-message">{{ error }}</div>
    <div v-if="success" class="settings-success">{{ success }}</div>
  </div>
</template>

<script setup>
import { onMounted, computed } from 'vue'
import { useSystemSettings } from '@/composables/systemSettings'

const {
  settings, saving, error, success,
  loadSettings, saveSetting, toggleSetting,
} = useSystemSettings()

// Per-page connection status (stays with the page, not the composable).
const zabbixStatus = computed(() => {
  if (!settings.zabbix_enabled) return 'inactive'
  if (!settings.zabbix_url || !settings.zabbix_token) return 'warning'
  return 'pending'
})

const zabbixMessage = computed(() => {
  if (!settings.zabbix_enabled) return 'Disabled'
  if (!settings.zabbix_url) return 'URL not configured'
  if (!settings.zabbix_token) return 'Token not configured'
  return 'Configured (connectivity checked on first use)'
})

onMounted(loadSettings)
</script>
