<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1>{{ $t('devices.title') }}</h1>
        <p>{{ $t('devices.manage') }}</p>
      </div>
    </div>

    <!-- Device Registration Toggle -->
    <div class="registration-banner" :class="{ enabled: autoRegistrationEnabled }">
      <div class="registration-content">
        <div class="registration-info">
          <h2>
            <span v-if="autoRegistrationEnabled">🟢 {{ $t('devices.registrationEnabled') }}</span>
            <span v-else>🔴 {{ $t('devices.registrationDisabled') }}</span>
          </h2>
          <p v-if="autoRegistrationEnabled" class="warning">
            ⚠️ {{ $t('devices.registrationWarning') }}
            <span v-if="registrationTimeLeft > 0">
              - {{ $t('devices.autoDisableIn') }} {{ formatTimeLeft(registrationTimeLeft) }}
            </span>
          </p>
          <p v-else>{{ $t('devices.registrationHint') }}</p>
        </div>
        <div class="registration-toggle">
          <label class="toggle-switch-large">
            <input
              type="checkbox"
              :checked="autoRegistrationEnabled"
              @change="toggleAutoRegistration"
              :disabled="togglingRegistration"
            />
            <span class="toggle-slider"></span>
            <span v-if="togglingRegistration" class="spinner">⏳</span>
          </label>
        </div>
      </div>
    </div>

    <div class="content">
      <!-- Search and Filters -->
      <div class="filters-row">
        <div class="search-box">
          <input
            v-model="searchQuery"
            type="text"
            :placeholder="$t('devices.searchPlaceholder')"
            class="search-input"
            @input="onSearch"
          />
          <span v-if="searchQuery" class="search-clear" @click="clearSearch">×</span>
        </div>

        <label class="filter-checkbox">
          <input type="checkbox" v-model="onlineOnly" @change="loadDevices" />
          <span>{{ $t('devices.onlineOnly') }}</span>
        </label>

        <button @click="showDefaultConfigModal" class="btn-primary btn-edit-default">
          Edit Default Config
        </button>
      </div>

      <div v-if="loading" class="loading">{{ $t('common.loading') }}</div>

      <div v-else-if="error" class="error">{{ error }}</div>

      <table v-else-if="devices.length > 0" class="data-table">
        <thead>
          <tr>
            <th @click="sortBy('simple_id')">
              {{ $t('devices.simpleId') }}
              <span v-if="sortColumn === 'simple_id'">{{ sortDirection === 'asc' ? '↑' : '↓' }}</span>
            </th>
            <th @click="sortBy('mac_address')">
              {{ $t('devices.macAddress') }}
              <span v-if="sortColumn === 'mac_address'">{{ sortDirection === 'asc' ? '↑' : '↓' }}</span>
            </th>
            <th>BLE Enabled</th>
            <th>WiFi Enabled</th>
            <th @click="sortBy('status')">
              {{ $t('common.status') }}
              <span v-if="sortColumn === 'status'">{{ sortDirection === 'asc' ? '↑' : '↓' }}</span>
            </th>
            <th @click="sortBy('last_seen_at')">
              {{ $t('devices.lastSeen') }}
              <span v-if="sortColumn === 'last_seen_at'">{{ sortDirection === 'asc' ? '↑' : '↓' }}</span>
            </th>
            <th>{{ $t('common.actions') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="device in sortedDevices" :key="device.id">
            <td><strong>#{{ device.simple_id }}</strong></td>
            <td><code>{{ device.mac_address }}</code></td>
            <td class="text-center">
              <label class="toggle-switch-inline">
                <input
                  type="checkbox"
                  :checked="device.config?.ble?.enabled ?? false"
                  @click="toggleBLE(device, $event)"
                />
                <span class="toggle-slider"></span>
              </label>
            </td>
            <td class="text-center">
              <label class="toggle-switch-inline">
                <input
                  type="checkbox"
                  :checked="device.config?.wifi?.monitor_enabled ?? false"
                  @click="toggleWiFi(device, $event)"
                />
                <span class="toggle-slider"></span>
              </label>
            </td>
            <td><span class="badge" :class="`status-${device.status}`">{{ $t(`devices.${device.status}`) }}</span></td>
            <td>{{ formatRelativeTime(device.last_seen_at) }}</td>
            <td>
              <button @click="showEditModal(device)" class="btn-icon" title="Edit">✏️</button>
              <button
                @click="openSSH(device)"
                class="btn-icon"
                :class="{ loading: tunnelLoading[`${device.id}:ssh`] }"
                :disabled="tunnelLoading[`${device.id}:ssh`]"
                :title="tunnelLoading[`${device.id}:ssh`] ? 'Connecting...' : 'SSH Terminal'">
                <span v-if="tunnelLoading[`${device.id}:ssh`]" class="spinner">⏳</span>
                <span v-else>🖥️</span>
              </button>
              <button
                @click="openDashboard(device)"
                class="btn-icon"
                :class="{ loading: tunnelLoading[`${device.id}:dashboard`] }"
                :disabled="tunnelLoading[`${device.id}:dashboard`]"
                :title="tunnelLoading[`${device.id}:dashboard`] ? 'Connecting...' : 'Dashboard'">
                <span v-if="tunnelLoading[`${device.id}:dashboard`]" class="spinner">⏳</span>
                <span v-else>📊</span>
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-else class="empty">No devices yet</div>
    </div>

    <!-- Edit Modal -->
    <div v-if="modalVisible" class="modal-overlay" @click="closeModal">
      <div class="modal modal-wide" @click.stop>
        <div class="modal-header">
          <h2>Device #{{ editingDevice?.simple_id }} - {{ editingDevice?.mac_address }}</h2>
          <button @click="closeModal" class="btn-close">×</button>
        </div>
        <form @submit.prevent="saveDevice" class="modal-body">
          <!-- WiFi Scanner Section -->
          <div class="config-section">
            <h3>WiFi Scanner</h3>
            <div class="toggle-row">
              <span>{{ $t('devices.config.wifiScannerEnabled') }}</span>
              <label class="toggle-switch">
                <input type="checkbox" v-model="config.wifi.monitor_enabled" @change="onWifiMonitorChange" />
                <span class="toggle-slider"></span>
              </label>
            </div>
            <div v-if="config.wifi.monitor_enabled" class="toggle-content">
              <div class="form-group">
                <label>{{ $t('devices.config.wifiBatchInterval') }} (ms)</label>
                <input v-model.number="config.wifi.batch_interval_ms" type="number" min="1000" step="1000" />
              </div>
              <div class="form-group">
                <label>{{ $t('devices.config.uploadEndpoint') }}</label>
                <input v-model="config.wifi.upload_endpoint" type="text" placeholder="http://custom.example.com:8080/wifi" />
                <div class="form-hint">{{ $t('devices.config.uploadEndpointHint') }}</div>
              </div>
            </div>
          </div>

          <!-- BLE Section -->
          <div class="config-section">
            <h3>BLE Scanner</h3>
            <div class="toggle-row">
              <span>{{ $t('devices.config.bleScannerEnabled') }}</span>
              <label class="toggle-switch">
                <input type="checkbox" v-model="config.ble.enabled" />
                <span class="toggle-slider"></span>
              </label>
            </div>
            <div v-if="config.ble.enabled" class="toggle-content">
              <div class="form-group">
                <label>{{ $t('devices.config.bleBatchInterval') }} (ms)</label>
                <input v-model.number="config.ble.batch_interval_ms" type="number" min="100" step="100" />
              </div>
              <div class="form-group">
                <label>{{ $t('devices.config.uuidFilter') }}</label>
                <input v-model="config.ble.uuid_filter_hex" type="text" placeholder="f7826da64fa24e988024bc5b71e0893e" maxlength="32" />
                <div class="form-hint">{{ $t('devices.config.uuidFilterHint') }}</div>
              </div>
              <div class="form-group">
                <label>{{ $t('devices.config.uploadEndpoint') }}</label>
                <input v-model="config.ble.upload_endpoint" type="text" placeholder="http://custom.example.com:8080/ble" />
                <div class="form-hint">{{ $t('devices.config.uploadEndpointHint') }}</div>
              </div>
            </div>
          </div>

          <!-- WiFi Client Section -->
          <div class="config-section">
            <h3>WiFi Client</h3>
            <div class="toggle-row">
              <span>{{ $t('devices.config.wifiClientEnabled') }}</span>
              <label class="toggle-switch">
                <input type="checkbox" v-model="config.wifi.client_enabled" @change="onWifiClientChange" />
                <span class="toggle-slider"></span>
              </label>
            </div>
            <div v-if="config.wifi.client_enabled" class="toggle-content">
              <div class="form-row">
                <div class="form-group">
                  <label>{{ $t('devices.config.wifiSsid') }}</label>
                  <input v-model="config.wifi.ssid" type="text" />
                </div>
                <div class="form-group">
                  <label>{{ $t('devices.config.wifiPassword') }}</label>
                  <input v-model="config.wifi.psk" type="password" />
                </div>
              </div>
            </div>
          </div>

          <!-- NTP Section -->
          <div class="config-section">
            <h3>NTP Servers</h3>
            <div class="form-group">
              <label>{{ $t('devices.config.ntpServers') }}</label>
              <input v-model="ntpServersText" type="text" placeholder="pool.ntp.org, time.google.com" />
              <div class="form-hint">{{ $t('devices.config.ntpHint') }}</div>
            </div>
          </div>

          <!-- Other Settings -->
          <div class="config-section">
            <h3>Other</h3>
            <div class="form-group">
              <label>Config Polling Timeout (seconds)</label>
              <input v-model.number="config.cfg_polling_timeout" type="number" min="5" max="300" step="5" />
              <div class="form-hint">How often device fetches config from server (min: 5s, recommended: 30-300s)</div>
            </div>
            <div class="toggle-row">
              <span>{{ $t('devices.config.forceCloud') }}</span>
              <label class="toggle-switch">
                <input type="checkbox" v-model="config.force_cloud" />
                <span class="toggle-slider"></span>
              </label>
            </div>
            <div class="toggle-row">
              <span>{{ $t('devices.config.debug') }}</span>
              <label class="toggle-switch">
                <input type="checkbox" v-model="config.debug" />
                <span class="toggle-slider"></span>
              </label>
            </div>
            <div class="toggle-row">
              <span>{{ $t('devices.config.dashboardEnabled') }}</span>
              <label class="toggle-switch">
                <input type="checkbox" v-model="config.dashboard.enabled" />
                <span class="toggle-slider"></span>
              </label>
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" @click="deleteDevice" class="btn-danger btn-delete" :disabled="saving">
              Delete Device
            </button>
            <div style="flex: 1"></div>
            <button type="button" @click="closeModal" class="btn-secondary">{{ $t('common.cancel') }}</button>
            <button type="submit" :disabled="saving" class="btn-primary">
              {{ saving ? $t('common.loading') : $t('common.save') }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Edit Default Config Modal -->
    <div v-if="defaultConfigModalVisible" class="modal-overlay" @click="closeDefaultConfigModal">
      <div class="modal modal-wide" @click.stop>
        <div class="modal-header">
          <h2>Edit Default Device Configuration</h2>
          <button @click="closeDefaultConfigModal" class="btn-close">×</button>
        </div>

        <!-- Tabs -->
        <div class="modal-tabs">
          <button
            @click="defaultConfigTab = 'interactive'"
            :class="['tab-button', { active: defaultConfigTab === 'interactive' }]"
          >
            Interactive
          </button>
          <button
            @click="switchToJsonTab"
            :class="['tab-button', { active: defaultConfigTab === 'json' }]"
          >
            JSON
          </button>
        </div>

        <div class="modal-body">
          <p style="margin-bottom: 16px; color: #718096; font-size: 14px;">
            This configuration will be copied to all newly registered devices.
            Changes do not affect existing devices.
          </p>

          <!-- Interactive Tab -->
          <div v-if="defaultConfigTab === 'interactive'">
            <!-- WiFi Scanner Section -->
            <div class="config-section">
              <h3>WiFi Scanner</h3>
              <div class="toggle-row">
                <span>WiFi Scanner Enabled</span>
                <label class="toggle-switch">
                  <input type="checkbox" v-model="defaultConfig.wifi.monitor_enabled" @change="onDefaultWifiMonitorChange" />
                  <span class="toggle-slider"></span>
                </label>
              </div>
              <div v-if="defaultConfig.wifi.monitor_enabled" class="toggle-content">
                <div class="form-group">
                  <label>Batch Interval (ms)</label>
                  <input v-model.number="defaultConfig.wifi.batch_interval_ms" type="number" min="1000" step="1000" />
                </div>
                <div class="form-group">
                  <label>Upload Endpoint (optional)</label>
                  <input v-model="defaultConfig.wifi.upload_endpoint" type="text" placeholder="http://custom.example.com:8080/wifi" />
                  <div class="form-hint">Custom upload endpoint URL (leave empty for default)</div>
                </div>
              </div>
            </div>

            <!-- BLE Section -->
            <div class="config-section">
              <h3>BLE Scanner</h3>
              <div class="toggle-row">
                <span>BLE Scanner Enabled</span>
                <label class="toggle-switch">
                  <input type="checkbox" v-model="defaultConfig.ble.enabled" />
                  <span class="toggle-slider"></span>
                </label>
              </div>
              <div v-if="defaultConfig.ble.enabled" class="toggle-content">
                <div class="form-group">
                  <label>Batch Interval (ms)</label>
                  <input v-model.number="defaultConfig.ble.batch_interval_ms" type="number" min="100" step="100" />
                </div>
                <div class="form-group">
                  <label>UUID Filter</label>
                  <input v-model="defaultConfig.ble.uuid_filter_hex" type="text" placeholder="f7826da64fa24e988024bc5b71e0893e" maxlength="32" />
                  <div class="form-hint">Filter beacons by UUID (32 hex chars, optional)</div>
                </div>
                <div class="form-group">
                  <label>Upload Endpoint (optional)</label>
                  <input v-model="defaultConfig.ble.upload_endpoint" type="text" placeholder="http://custom.example.com:8080/ble" />
                  <div class="form-hint">Custom upload endpoint URL (leave empty for default)</div>
                </div>
              </div>
            </div>

            <!-- WiFi Client Section -->
            <div class="config-section">
              <h3>WiFi Client</h3>
              <div class="toggle-row">
                <span>WiFi Client Enabled</span>
                <label class="toggle-switch">
                  <input type="checkbox" v-model="defaultConfig.wifi.client_enabled" @change="onDefaultWifiClientChange" />
                  <span class="toggle-slider"></span>
                </label>
              </div>
              <div v-if="defaultConfig.wifi.client_enabled" class="toggle-content">
                <div class="form-row">
                  <div class="form-group">
                    <label>WiFi SSID</label>
                    <input v-model="defaultConfig.wifi.ssid" type="text" />
                  </div>
                  <div class="form-group">
                    <label>WiFi Password</label>
                    <input v-model="defaultConfig.wifi.psk" type="password" />
                  </div>
                </div>
              </div>
            </div>

            <!-- NTP Section -->
            <div class="config-section">
              <h3>NTP Servers</h3>
              <div class="form-group">
                <label>NTP Servers</label>
                <input v-model="defaultNtpServersText" type="text" placeholder="pool.ntp.org, time.google.com" />
                <div class="form-hint">Comma-separated list of NTP server addresses</div>
              </div>
            </div>

            <!-- Other Settings -->
            <div class="config-section">
              <h3>Other</h3>
              <div class="form-group">
                <label>Config Polling Timeout (seconds)</label>
                <input v-model.number="defaultConfig.cfg_polling_timeout" type="number" min="5" max="300" step="5" />
                <div class="form-hint">How often device fetches config from server (min: 5s, recommended: 30-300s)</div>
              </div>
              <div class="toggle-row">
                <span>Force Cloud Mode</span>
                <label class="toggle-switch">
                  <input type="checkbox" v-model="defaultConfig.force_cloud" />
                  <span class="toggle-slider"></span>
                </label>
              </div>
              <div class="toggle-row">
                <span>Debug Logging</span>
                <label class="toggle-switch">
                  <input type="checkbox" v-model="defaultConfig.debug" />
                  <span class="toggle-slider"></span>
                </label>
              </div>
              <div class="toggle-row">
                <span>Dashboard Enabled</span>
                <label class="toggle-switch">
                  <input type="checkbox" v-model="defaultConfig.dashboard.enabled" />
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
          </div>

          <!-- JSON Tab -->
          <div v-if="defaultConfigTab === 'json'">
            <div class="form-group">
              <label>Configuration (JSON)</label>
              <textarea
                v-model="defaultConfigJson"
                rows="25"
                class="config-editor"
                @input="validateJson"
              ></textarea>
              <div v-if="jsonError" class="form-error">{{ jsonError }}</div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" @click="closeDefaultConfigModal" class="btn-secondary">Cancel</button>
          <button
            type="button"
            @click="saveDefaultConfig"
            :disabled="savingDefaultConfig || (defaultConfigTab === 'json' && !!jsonError)"
            class="btn-primary"
          >
            {{ savingDefaultConfig ? 'Saving...' : 'Save Default Config' }}
          </button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import devicesApi from '@/api/devices'
import organizationsApi from '@/api/organizations'
import tunnelsApi from '@/api/tunnels'
import settingsApi from '@/api/settings'

// Auto-registration state
const autoRegistrationEnabled = ref(false)
const togglingRegistration = ref(false)
const registrationTimeLeft = ref(0)
let registrationTimer = null

const devices = ref([])
const organizations = ref([])
const loading = ref(false)
const error = ref(null)
const modalVisible = ref(false)
const editingDevice = ref(null)
const saving = ref(false)
const searchQuery = ref('')
const onlineOnly = ref(false)
const sortColumn = ref('simple_id')
const sortDirection = ref('desc')
const ntpServersText = ref('')
const tunnelLoading = ref({})
const defaultConfigModalVisible = ref(false)
const defaultConfigTab = ref('interactive')
const defaultConfigJson = ref('')
const savingDefaultConfig = ref(false)
const jsonError = ref(null)
const defaultNtpServersText = ref('')
const defaultConfig = ref({
  force_cloud: false,
  cfg_polling_timeout: 30,
  ble: {
    enabled: true,
    batch_interval_ms: 2500,
    uuid_filter_hex: '',
    upload_endpoint: ''
  },
  wifi: {
    client_enabled: false,
    ssid: '',
    psk: '',
    monitor_enabled: true,
    batch_interval_ms: 10000,
    upload_endpoint: ''
  },
  ssh_tunnel: {
    enabled: false,
    server: '192.168.5.4',
    port: 22,
    user: 'tunnel',
    remote_port: 0,
    keepalive_interval: 30
  },
  dashboard_tunnel: {
    enabled: false,
    server: '192.168.5.4',
    port: 22,
    user: 'tunnel',
    remote_port: 0,
    keepalive_interval: 30
  },
  dashboard: {
    enabled: true
  },
  net: {
    ntp: {
      servers: ['pool.ntp.org', 'time.google.com']
    }
  },
  debug: false
})
let searchDebounceTimer = null
let pollingInterval = null

const config = ref({
  force_cloud: false,
  cfg_polling_timeout: 30,
  ble: {
    enabled: true,
    batch_interval_ms: 2500,
    uuid_filter_hex: '',
    upload_endpoint: ''
  },
  wifi: {
    client_enabled: false,
    ssid: '',
    psk: '',
    monitor_enabled: true,
    batch_interval_ms: 10000,
    upload_endpoint: ''
  },
  dashboard: {
    enabled: true
  },
  net: {
    ntp: {
      servers: ['pool.ntp.org', 'time.google.com']
    }
  },
  debug: false
})

const sortedDevices = computed(() => {
  let result = [...devices.value]

  // Sort
  result.sort((a, b) => {
    let aVal = a[sortColumn.value]
    let bVal = b[sortColumn.value]

    // Handle nulls
    if (aVal === null || aVal === undefined) return 1
    if (bVal === null || bVal === undefined) return -1

    // String comparison
    if (typeof aVal === 'string') {
      aVal = aVal.toLowerCase()
      bVal = bVal.toLowerCase()
    }

    if (aVal < bVal) return sortDirection.value === 'asc' ? -1 : 1
    if (aVal > bVal) return sortDirection.value === 'asc' ? 1 : -1
    return 0
  })

  return result
})

function sortBy(column) {
  if (sortColumn.value === column) {
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortColumn.value = column
    sortDirection.value = 'asc'
  }
}

async function loadDevices(silent = false) {
  // Only show loading spinner on initial load, not on polling updates
  if (!silent) {
    loading.value = true
  }
  error.value = null
  try {
    const params = {}
    if (searchQuery.value && searchQuery.value.length >= 2) {
      params.search = searchQuery.value
    }
    if (onlineOnly.value) {
      params.status = 'online'
    }
    devices.value = await devicesApi.getAllSuperadmin(params)
  } catch (err) {
    error.value = err.response?.data?.detail || 'Failed to load devices'
  } finally {
    loading.value = false
  }
}

function onSearch() {
  // Debounce search - wait 300ms after user stops typing
  clearTimeout(searchDebounceTimer)
  searchDebounceTimer = setTimeout(() => {
    loadDevices()
  }, 300)
}

function clearSearch() {
  searchQuery.value = ''
  loadDevices()
}

async function loadOrganizations() {
  try {
    organizations.value = await organizationsApi.getAll()
  } catch (err) {
    console.error('Failed to load organizations:', err)
  }
}

function formatDate(dateStr) {
  if (!dateStr) return 'Never'
  const date = new Date(dateStr)
  return date.toLocaleString()
}

function formatRelativeTime(dateStr) {
  if (!dateStr) return 'Never'

  const now = new Date()
  const then = new Date(dateStr)
  const diffMs = now - then
  const diffMinutes = Math.floor(diffMs / 60000)

  if (diffMinutes < 1) {
    return 'Just now'
  } else if (diffMinutes < 120) {
    return `${diffMinutes} min ago`
  } else {
    const diffHours = Math.floor(diffMinutes / 60)
    if (diffHours < 24) {
      return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`
    } else {
      const diffDays = Math.floor(diffHours / 24)
      return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`
    }
  }
}

function showEditModal(device) {
  editingDevice.value = device
  // Deep copy device config with defaults
  config.value = {
    force_cloud: device.config?.force_cloud ?? false,
    cfg_polling_timeout: device.config?.cfg_polling_timeout ?? 30,
    ble: {
      enabled: device.config?.ble?.enabled ?? true,
      batch_interval_ms: device.config?.ble?.batch_interval_ms ?? 2500,
      uuid_filter_hex: device.config?.ble?.uuid_filter_hex ?? '',
      upload_endpoint: device.config?.ble?.upload_endpoint ?? ''
    },
    wifi: {
      client_enabled: device.config?.wifi?.client_enabled ?? false,
      ssid: device.config?.wifi?.ssid ?? '',
      psk: device.config?.wifi?.psk ?? '',
      monitor_enabled: device.config?.wifi?.monitor_enabled ?? true,
      batch_interval_ms: device.config?.wifi?.batch_interval_ms ?? 10000,
      upload_endpoint: device.config?.wifi?.upload_endpoint ?? ''
    },
    dashboard: {
      enabled: device.config?.dashboard?.enabled ?? true
    },
    net: {
      ntp: {
        servers: device.config?.net?.ntp?.servers ?? ['pool.ntp.org', 'time.google.com']
      }
    },
    debug: device.config?.debug ?? false
  }

  // Convert NTP servers array to comma-separated string
  ntpServersText.value = config.value.net.ntp.servers.join(', ')

  modalVisible.value = true
}

function closeModal() {
  modalVisible.value = false
  editingDevice.value = null
}

function onWifiClientChange() {
  // WiFi client и monitor взаимоисключающие (AIC8800 ограничение)
  if (config.value.wifi.client_enabled) {
    config.value.wifi.monitor_enabled = false
  }
}

function onWifiMonitorChange() {
  // WiFi client и monitor взаимоисключающие (AIC8800 ограничение)
  if (config.value.wifi.monitor_enabled) {
    config.value.wifi.client_enabled = false
  }
}

async function saveDevice() {
  saving.value = true
  try {
    // Parse NTP servers from comma-separated string to array
    config.value.net.ntp.servers = ntpServersText.value
      .split(',')
      .map(s => s.trim())
      .filter(s => s.length > 0)

    await devicesApi.updateSuperadmin(editingDevice.value.id, { config: config.value })
    await loadDevices()
    closeModal()
  } catch (err) {
    alert(err.response?.data?.detail || 'Failed to save device')
  } finally {
    saving.value = false
  }
}

async function deleteDevice() {
  const deviceName = `#${editingDevice.value.simple_id} (${editingDevice.value.mac_address})`

  const confirmed = confirm(
    `Are you sure you want to DELETE device ${deviceName}?\n\n` +
    `This will permanently remove the device from the system.\n` +
    `The device will need to re-register to be used again.\n\n` +
    `This action CANNOT be undone!`
  )

  if (!confirmed) {
    return
  }

  saving.value = true
  try {
    await devicesApi.deleteSuperadmin(editingDevice.value.id)
    await loadDevices()
    closeModal()
  } catch (err) {
    alert(err.response?.data?.detail || 'Failed to delete device')
    saving.value = false
  }
}

async function openTunnel(device, tunnelType) {
  const loadingKey = `${device.id}:${tunnelType}`
  tunnelLoading.value[loadingKey] = true

  try {
    // Step 1: Enable tunnel, get session UUID
    const { session_uuid } = await tunnelsApi.enableTunnel(device.id, tunnelType)

    // Step 2: Poll for tunnel status
    const maxAttempts = 60 // 60 seconds max wait
    let attempts = 0
    let opened = false // Prevent multiple window.open()

    const pollInterval = setInterval(async () => {
      attempts++

      try {
        const status = await tunnelsApi.getSessionStatus(session_uuid)

        if (status.status === 'ready' && status.tunnel_url && !opened) {
          // Clear polling
          clearInterval(pollInterval)
          tunnelLoading.value[loadingKey] = false
          opened = true

          // Open tunnel URL in new tab
          window.open(status.tunnel_url, '_blank')
        } else if (status.status === 'failed') {
          clearInterval(pollInterval)
          tunnelLoading.value[loadingKey] = false
          alert('Failed to establish tunnel')
        } else if (attempts >= maxAttempts) {
          clearInterval(pollInterval)
          tunnelLoading.value[loadingKey] = false
          alert('Tunnel connection timeout')
        }
      } catch (err) {
        clearInterval(pollInterval)
        tunnelLoading.value[loadingKey] = false
        console.error('Failed to poll tunnel status:', err)
        alert('Failed to check tunnel status')
      }
    }, 1000) // Poll every 1 second

  } catch (err) {
    tunnelLoading.value[loadingKey] = false
    console.error('Failed to enable tunnel:', err)
    alert(err.response?.data?.detail || 'Failed to enable tunnel')
  }
}

function openSSH(device) {
  openTunnel(device, 'ssh')
}

function openDashboard(device) {
  openTunnel(device, 'dashboard')
}

async function toggleBLE(device, event) {
  event.preventDefault()

  const newState = !(device.config?.ble?.enabled ?? false)
  const action = newState ? 'enable' : 'disable'

  if (!confirm(`Are you sure you want to ${action} BLE scanner for device #${device.simple_id}?`)) {
    return
  }

  try {
    const updatedConfig = {
      ...device.config,
      ble: {
        ...(device.config?.ble || {}),
        enabled: newState
      }
    }

    await devicesApi.updateSuperadmin(device.id, { config: updatedConfig })
    await loadDevices()
  } catch (err) {
    alert(err.response?.data?.detail || 'Failed to update BLE scanner')
  }
}

async function toggleWiFi(device, event) {
  event.preventDefault()

  const newState = !(device.config?.wifi?.monitor_enabled ?? false)
  const action = newState ? 'enable' : 'disable'

  if (!confirm(`Are you sure you want to ${action} WiFi scanner for device #${device.simple_id}?`)) {
    return
  }

  try {
    const updatedConfig = {
      ...device.config,
      wifi: {
        ...(device.config?.wifi || {}),
        monitor_enabled: newState
      }
    }

    await devicesApi.updateSuperadmin(device.id, { config: updatedConfig })
    await loadDevices()
  } catch (err) {
    alert(err.response?.data?.detail || 'Failed to update WiFi scanner')
  }
}

async function showDefaultConfigModal() {
  try {
    const configData = await devicesApi.getDefaultConfig()

    // Load into interactive form
    defaultConfig.value = {
      force_cloud: configData.force_cloud ?? false,
      cfg_polling_timeout: configData.cfg_polling_timeout ?? 30,
      ble: {
        enabled: configData.ble?.enabled ?? true,
        batch_interval_ms: configData.ble?.batch_interval_ms ?? 2500,
        uuid_filter_hex: configData.ble?.uuid_filter_hex ?? '',
        upload_endpoint: configData.ble?.upload_endpoint ?? ''
      },
      wifi: {
        client_enabled: configData.wifi?.client_enabled ?? false,
        ssid: configData.wifi?.ssid ?? '',
        psk: configData.wifi?.psk ?? '',
        monitor_enabled: configData.wifi?.monitor_enabled ?? true,
        batch_interval_ms: configData.wifi?.batch_interval_ms ?? 10000,
        upload_endpoint: configData.wifi?.upload_endpoint ?? ''
      },
      ssh_tunnel: configData.ssh_tunnel || {
        enabled: false,
        server: '192.168.5.4',
        port: 22,
        user: 'tunnel',
        remote_port: 0,
        keepalive_interval: 30
      },
      dashboard_tunnel: configData.dashboard_tunnel || {
        enabled: false,
        server: '192.168.5.4',
        port: 22,
        user: 'tunnel',
        remote_port: 0,
        keepalive_interval: 30
      },
      dashboard: {
        enabled: configData.dashboard?.enabled ?? true
      },
      net: {
        ntp: {
          servers: configData.net?.ntp?.servers ?? ['pool.ntp.org', 'time.google.com']
        }
      },
      debug: configData.debug ?? false
    }

    // Convert NTP servers to text
    defaultNtpServersText.value = defaultConfig.value.net.ntp.servers.join(', ')

    // Also load into JSON
    defaultConfigJson.value = JSON.stringify(configData, null, 2)

    jsonError.value = null
    defaultConfigTab.value = 'interactive'
    defaultConfigModalVisible.value = true
  } catch (err) {
    alert(err.response?.data?.detail || 'Failed to load default config')
  }
}

function closeDefaultConfigModal() {
  defaultConfigModalVisible.value = false
  defaultConfigTab.value = 'interactive'
  defaultConfigJson.value = ''
  jsonError.value = null
}

function onDefaultWifiClientChange() {
  if (defaultConfig.value.wifi.client_enabled) {
    defaultConfig.value.wifi.monitor_enabled = false
  }
}

function onDefaultWifiMonitorChange() {
  if (defaultConfig.value.wifi.monitor_enabled) {
    defaultConfig.value.wifi.client_enabled = false
  }
}

function switchToJsonTab() {
  // Convert interactive form to JSON before switching
  defaultConfig.value.net.ntp.servers = defaultNtpServersText.value
    .split(',')
    .map(s => s.trim())
    .filter(s => s.length > 0)

  defaultConfigJson.value = JSON.stringify(defaultConfig.value, null, 2)
  defaultConfigTab.value = 'json'
}

function validateJson() {
  try {
    JSON.parse(defaultConfigJson.value)
    jsonError.value = null
  } catch (e) {
    jsonError.value = `Invalid JSON: ${e.message}`
  }
}

async function saveDefaultConfig() {
  try {
    let configToSave

    if (defaultConfigTab.value === 'interactive') {
      // Parse NTP servers from text
      defaultConfig.value.net.ntp.servers = defaultNtpServersText.value
        .split(',')
        .map(s => s.trim())
        .filter(s => s.length > 0)

      configToSave = defaultConfig.value
    } else {
      // Validate and parse JSON
      configToSave = JSON.parse(defaultConfigJson.value)
    }

    savingDefaultConfig.value = true
    await devicesApi.updateDefaultConfig(configToSave)
    alert('Default configuration saved successfully!')
    closeDefaultConfigModal()
  } catch (err) {
    if (err instanceof SyntaxError) {
      jsonError.value = `Invalid JSON: ${err.message}`
    } else {
      alert(err.response?.data?.detail || 'Failed to save default config')
    }
  } finally {
    savingDefaultConfig.value = false
  }
}

// Auto-registration functions
async function loadAutoRegistrationStatus() {
  try {
    const status = await settingsApi.getAutoRegistrationStatus()
    autoRegistrationEnabled.value = status.enabled
    registrationTimeLeft.value = status.time_left || 0
  } catch (err) {
    console.error('Failed to load registration status:', err)
  }
}

async function toggleAutoRegistration() {
  togglingRegistration.value = true
  try {
    const newState = !autoRegistrationEnabled.value
    await settingsApi.toggleAutoRegistration(newState)
    autoRegistrationEnabled.value = newState
    if (newState) {
      startRegistrationTimer()
    } else {
      stopRegistrationTimer()
    }
  } catch (err) {
    console.error('Failed to toggle registration:', err)
    // Reload status to sync
    await loadAutoRegistrationStatus()
  } finally {
    togglingRegistration.value = false
  }
}

function startRegistrationTimer() {
  stopRegistrationTimer()
  registrationTimer = setInterval(async () => {
    await loadAutoRegistrationStatus()
    if (!autoRegistrationEnabled.value) {
      stopRegistrationTimer()
    }
  }, 10000) // Update every 10 seconds
}

function stopRegistrationTimer() {
  if (registrationTimer) {
    clearInterval(registrationTimer)
    registrationTimer = null
  }
}

function formatTimeLeft(seconds) {
  if (seconds < 60) return `${seconds}s`
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`
  return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`
}

onMounted(() => {
  loadDevices()
  loadOrganizations()
  loadAutoRegistrationStatus()
  startRegistrationTimer()

  // Real-time polling every 10 seconds (silent to avoid table flickering)
  pollingInterval = setInterval(() => {
    if (!modalVisible.value) {
      loadDevices(true)
    }
  }, 10000)
})

onBeforeUnmount(() => {
  if (pollingInterval) {
    clearInterval(pollingInterval)
  }
  if (searchDebounceTimer) {
    clearTimeout(searchDebounceTimer)
  }
  stopRegistrationTimer()
})
</script>

<style scoped>
.page { padding: 32px; }
.page-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 32px; }
.page-header h1 { font-size: 32px; font-weight: 700; color: #1a202c; margin-bottom: 8px; }
.page-header p { color: #718096; font-size: 16px; }

/* Registration Banner */
.registration-banner {
  background: #fff5f5;
  border: 2px solid #fc8181;
  border-radius: 12px;
  padding: 20px 24px;
  margin-bottom: 24px;
  transition: all 0.3s;
}
.registration-banner.enabled {
  background: #f0fff4;
  border-color: #68d391;
}
.registration-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 24px;
}
.registration-info h2 {
  font-size: 20px;
  font-weight: 700;
  margin-bottom: 8px;
  color: #1a202c;
}
.registration-info p {
  font-size: 14px;
  color: #718096;
  margin: 0;
}
.registration-info .warning {
  color: #c53030;
  font-weight: 500;
}
.registration-banner.enabled .warning {
  color: #276749;
}

/* Large Toggle Switch (for registration banner) */
.toggle-switch-large {
  position: relative;
  display: inline-block;
  width: 72px;
  height: 40px;
  flex-shrink: 0;
}
.toggle-switch-large input {
  opacity: 0;
  width: 0;
  height: 0;
  position: absolute;
}
.toggle-switch-large .toggle-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #cbd5e0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 40px;
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);
}
.toggle-switch-large .toggle-slider:before {
  position: absolute;
  content: '';
  height: 32px;
  width: 32px;
  left: 4px;
  top: 4px;
  background-color: white;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}
.toggle-switch-large input:checked + .toggle-slider {
  background-color: #48bb78;
}
.toggle-switch-large input:checked + .toggle-slider:before {
  transform: translateX(32px);
}
.toggle-switch-large input:focus + .toggle-slider {
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.1), 0 0 0 3px rgba(72, 187, 120, 0.3);
}
.toggle-switch-large input:disabled + .toggle-slider {
  opacity: 0.5;
  cursor: not-allowed;
}
.toggle-switch-large .spinner {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  animation: spin 1s linear infinite;
  z-index: 10;
}

.content { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); }

/* Filters Row */
.filters-row { display: flex; gap: 16px; align-items: center; margin-bottom: 20px; }
.btn-edit-default { margin-left: auto; }
.search-box { position: relative; flex: 1; max-width: 400px; }
.search-input { width: 100%; padding: 10px 40px 10px 14px; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 14px; transition: border-color 0.2s; }
.search-input:focus { outline: none; border-color: #667eea; }
.search-input::placeholder { color: #a0aec0; }
.search-clear { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); font-size: 24px; color: #a0aec0; cursor: pointer; line-height: 1; padding: 0 4px; }
.search-clear:hover { color: #718096; }
.filter-checkbox { display: flex; align-items: center; gap: 8px; cursor: pointer; user-select: none; white-space: nowrap; }
.filter-checkbox input[type="checkbox"] { cursor: pointer; width: 16px; height: 16px; }
.filter-checkbox span { color: #4a5568; font-size: 14px; }
.loading, .error, .empty { text-align: center; padding: 40px; color: #718096; }
.error { color: #e53e3e; }
.data-table { width: 100%; border-collapse: collapse; }
.data-table th { text-align: left; padding: 8px 12px; border-bottom: 2px solid #e2e8f0; font-weight: 600; color: #4a5568; font-size: 13px; cursor: pointer; user-select: none; }
.data-table th:hover { background: #f7fafc; }
.data-table td { padding: 6px 12px; border-bottom: 1px solid #e2e8f0; color: #1a202c; font-size: 14px; }
.data-table tbody tr:hover { background: #f7fafc; }
code { background: #f7fafc; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 13px; }
.badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600; background: #e2e8f0; color: #718096; }
.badge.status-online { background: #c6f6d5; color: #22543d; }
.badge.status-offline { background: #e2e8f0; color: #718096; }
.badge.status-error { background: #fed7d7; color: #742a2a; }
.btn-icon { padding: 6px 10px; background: none; border: none; cursor: pointer; font-size: 16px; opacity: 0.7; transition: opacity 0.2s; }
.btn-icon:hover { opacity: 1; background: #f7fafc; border-radius: 4px; }
.btn-icon:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-icon:disabled:hover { background: none; }
.btn-icon.loading .spinner { display: inline-block; animation: spin 1s linear infinite; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.btn-primary { padding: 12px 24px; background: #667eea; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all 0.2s; }
.btn-primary:hover { background: #5568d3; }
.btn-primary:disabled { opacity: 0.6; cursor: not-allowed; }
.btn-secondary { padding: 12px 24px; background: #e2e8f0; color: #4a5568; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all 0.2s; }
.btn-secondary:hover { background: #cbd5e0; }
.btn-danger { padding: 12px 24px; background: #f56565; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all 0.2s; }
.btn-danger:hover { background: #e53e3e; }
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.modal { background: white; border-radius: 12px; width: 90%; max-width: 600px; max-height: 90vh; overflow-y: auto; }
.modal-sm { max-width: 400px; }
.modal-wide { max-width: 800px; }
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 24px; border-bottom: 1px solid #e2e8f0; }
.modal-header h2 { font-size: 24px; font-weight: 700; color: #1a202c; }
.btn-close { width: 32px; height: 32px; border: none; background: none; font-size: 32px; color: #718096; cursor: pointer; line-height: 1; }
.btn-close:hover { color: #1a202c; }
.modal-tabs { display: flex; border-bottom: 2px solid #e2e8f0; padding: 0 24px; }
.tab-button { padding: 12px 24px; background: none; border: none; border-bottom: 3px solid transparent; color: #718096; font-weight: 500; font-size: 14px; cursor: pointer; transition: all 0.2s; margin-bottom: -2px; }
.tab-button:hover { color: #4a5568; background: #f7fafc; }
.tab-button.active { color: #667eea; border-bottom-color: #667eea; }
.modal-body { padding: 16px; }
.modal-footer { display: flex; justify-content: flex-end; gap: 12px; padding: 16px; border-top: 1px solid #e2e8f0; }
.btn-delete { margin-right: auto; }
.form-group { margin-bottom: 12px; }
.form-group label { display: block; margin-bottom: 4px; font-weight: 500; color: #4a5568; font-size: 13px; }
.form-group input, .form-group select { width: 100%; padding: 8px 10px; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 13px; transition: border-color 0.2s; }
.form-group input:focus, .form-group select:focus { outline: none; border-color: #667eea; }
.form-group input:disabled { background: #f7fafc; color: #718096; }
.form-hint { margin-top: 4px; font-size: 11px; color: #718096; }
.config-editor { width: 100%; padding: 12px; border: 1px solid #e2e8f0; border-radius: 6px; font-family: 'Courier New', monospace; font-size: 13px; line-height: 1.5; resize: vertical; transition: border-color 0.2s; }
.config-editor:focus { outline: none; border-color: #667eea; }
.form-error { margin-top: 8px; padding: 8px 12px; background: #fed7d7; color: #742a2a; border-radius: 6px; font-size: 13px; }

/* Config sections */
.config-section { border: 1px solid #e2e8f0; border-radius: 6px; padding: 12px; margin-bottom: 12px; background: #fafafa; }
.config-section h3 { margin: 0 0 12px 0; font-size: 14px; font-weight: 600; color: #2d3748; border-bottom: 1px solid #e2e8f0; padding-bottom: 6px; }
.form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; }

/* Toggle row */
.toggle-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; padding: 8px 0; }
.toggle-row:last-child { margin-bottom: 0; }
.toggle-row span { font-size: 13px; font-weight: 500; color: #4a5568; }

/* Toggle switch */
.toggle-switch { position: relative; display: inline-block; width: 48px; height: 26px; }
.toggle-switch input { opacity: 0; width: 0; height: 0; }
.toggle-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #cbd5e0; border-radius: 26px; transition: 0.3s; }
.toggle-slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 3px; bottom: 3px; background-color: white; border-radius: 50%; transition: 0.3s; }
.toggle-switch input:checked + .toggle-slider { background-color: #667eea; }
.toggle-switch input:checked + .toggle-slider:before { transform: translateX(22px); }
.toggle-switch input:disabled + .toggle-slider { opacity: 0.5; cursor: not-allowed; }

/* Toggle switch inline (for table cells) */
.toggle-switch-inline { position: relative; display: inline-block; width: 38px; height: 20px; }
.toggle-switch-inline input { opacity: 0; width: 0; height: 0; }
.toggle-switch-inline .toggle-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #cbd5e0; border-radius: 20px; transition: 0.3s; }
.toggle-switch-inline .toggle-slider:before { position: absolute; content: ""; height: 14px; width: 14px; left: 3px; bottom: 3px; background-color: white; border-radius: 50%; transition: 0.3s; }
.toggle-switch-inline input:checked + .toggle-slider { background-color: #667eea; }
.toggle-switch-inline input:checked + .toggle-slider:before { transform: translateX(18px); }
.toggle-switch-inline input:disabled + .toggle-slider { opacity: 0.5; cursor: not-allowed; }
.text-center { text-align: center; }

/* Toggle content (expanded section) */
.toggle-content { padding-left: 0; margin-top: 8px; border-top: 1px solid #e2e8f0; padding-top: 12px; }
.toggle-content .form-group:last-child { margin-bottom: 0; }
</style>
