<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAutoDoorsStore } from '@/stores/autodoors'
import { useThemeGame } from '@/composables/useThemeGame'
import { useGameProfile } from '@/config/gameProfiles'
import Panel from '@/components/ds/data/Panel.vue'
import Button from '@/components/ds/core/Button.vue'
import Icon from '@/components/ds/core/Icon.vue'
import Switch from '@/components/ds/forms/Switch.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'

const store = useAutoDoorsStore()
const { activeGame } = useThemeGame()
const gameProfile = computed(() => useGameProfile(activeGame.value === 'all' ? 'rust' : activeGame.value))

const showCreateModal = ref(false)
const showImportModal = ref(false)
const newConfigName = ref('')
const newConfigDesc = ref('')
const importConfigName = ref('')

// Door types from the AutoDoors plugin
const doorTypes = [
  { key: 'door.hinged.wood', label: 'Wooden door', displayName: 'Wooden Door' },
  { key: 'door.hinged.metal', label: 'Sheet metal door', displayName: 'Sheet Metal Door' },
  { key: 'door.hinged.toptier', label: 'Armored door', displayName: 'Armored Door' },
  { key: 'door.double.hinged.wood', label: 'Double wooden door', displayName: 'Double Wooden Door' },
  { key: 'door.double.hinged.metal', label: 'Double sheet metal door', displayName: 'Double Sheet Metal Door' },
  { key: 'door.double.hinged.toptier', label: 'Double armored door', displayName: 'Double Armored Door' },
  { key: 'floor.ladder.hatch', label: 'Ladder hatch', displayName: 'Ladder Hatch' },
]

onMounted(async () => {
  await store.fetchConfigs()
  if (store.configs.length > 0 && store.configs[0]) {
    await store.loadConfig(store.configs[0].id)
  }
})

// --- Config data helpers ---

function getConfigValue(path: string, defaultValue: any = false): any {
  if (!store.currentConfig?.config_data) return defaultValue
  const parts = path.split('.')
  let current: any = store.currentConfig.config_data
  for (const part of parts) {
    if (current == null || typeof current !== 'object') return defaultValue
    current = current[part]
  }
  return current ?? defaultValue
}

function setConfigValue(path: string, value: any) {
  if (!store.currentConfig) return
  if (!store.currentConfig.config_data) store.currentConfig.config_data = {}
  const parts = path.split('.')
  let current: any = store.currentConfig.config_data
  for (let i = 0; i < parts.length - 1; i++) {
    const part = parts[i]!
    if (current[part] == null || typeof current[part] !== 'object') {
      current[part] = {}
    }
    current = current[part]
  }
  current[parts[parts.length - 1]!] = value
  store.markDirty()
}

// --- Permission group helpers ---

function getPermissionGroups(): Array<{ name: string; delay: number }> {
  const groups = getConfigValue('PermissionGroups', {})
  if (typeof groups !== 'object' || groups === null) return []
  return Object.entries(groups).map(([name, delay]) => ({
    name,
    delay: Number(delay) || 5,
  }))
}

function addPermissionGroup() {
  const groups = getConfigValue('PermissionGroups', {})
  const newGroups = { ...groups, '': 5 }
  setConfigValue('PermissionGroups', newGroups)
}

function updatePermissionGroupName(oldName: string, newName: string) {
  if (!store.currentConfig) return
  const groups = getConfigValue('PermissionGroups', {})
  const delay = groups[oldName] ?? 5
  const newGroups: Record<string, number> = {}
  for (const [key, val] of Object.entries(groups)) {
    if (key === oldName) {
      newGroups[newName] = delay
    } else {
      newGroups[key] = val as number
    }
  }
  setConfigValue('PermissionGroups', newGroups)
}

function updatePermissionGroupDelay(name: string, delay: number) {
  setConfigValue(`PermissionGroups.${name}`, delay)
}

function removePermissionGroup(name: string) {
  const groups = getConfigValue('PermissionGroups', {})
  const newGroups = { ...groups }
  delete newGroups[name]
  setConfigValue('PermissionGroups', newGroups)
}

// --- Action handlers ---

async function handleConfigChange(id: string) {
  if (store.isDirty) {
    if (!confirm('Unsaved changes will be lost. Continue?')) return
  }
  await store.loadConfig(id)
}

async function handleCreateConfig() {
  if (!newConfigName.value.trim()) return
  const config = await store.createConfig(
    newConfigName.value.trim(),
    newConfigDesc.value.trim() || undefined,
  )
  if (config) {
    showCreateModal.value = false
    newConfigName.value = ''
    newConfigDesc.value = ''
  }
}

async function handleDeleteConfig() {
  if (!store.currentConfig) return
  if (!confirm(`Delete "${store.currentConfig.config_name}"? This cannot be undone.`)) return
  await store.deleteConfig(store.currentConfig.id)
}

async function handleApply() {
  if (!store.currentConfig) return
  if (!confirm('Apply this AutoDoors config to the server? This will overwrite the current AutoDoors config.')) return
  if (store.isDirty) {
    await store.saveCurrentConfig()
  }
  await store.applyToServer(store.currentConfig.id)
}

async function handleImport() {
  if (!importConfigName.value.trim()) return
  const config = await store.importFromServer(importConfigName.value.trim())
  if (config) {
    showImportModal.value = false
    importConfigName.value = ''
  }
}

// Helper: coerce getConfigValue result to boolean for Switch
function getBool(path: string, def: boolean): boolean {
  return !!getConfigValue(path, def)
}
</script>

<template>
  <div class="adv">
    <!-- uMod-only guard: AutoDoors is an Oxide/uMod plugin -->
    <Panel v-if="gameProfile.mods !== 'umod'">
      <EmptyState
        icon="door-open"
        title="Rust / uMod only"
        description="Auto Doors is only available for Rust (uMod/Oxide) servers."
      />
    </Panel>

    <template v-else>
    <!-- Page head -->
    <div class="adv__head">
      <div class="adv__head-id">
        <div class="adv__head-chip">
          <Icon name="door-open" :size="20" :stroke-width="2" />
        </div>
        <div>
          <div class="t-eyebrow">Plugin config</div>
          <h1 class="adv__title">Auto doors</h1>
        </div>
      </div>
      <Button size="sm" icon="plus" @click="showCreateModal = true">New config</Button>
    </div>

    <!-- Config action bar -->
    <Panel>
      <div class="adv__bar">
        <select
          v-if="store.configs.length > 0"
          :value="store.currentConfig?.id ?? ''"
          class="adv__config-select"
          @change="handleConfigChange(($event.target as HTMLSelectElement).value)"
        >
          <option v-for="c in store.configs" :key="c.id" :value="c.id">
            {{ c.config_name }}{{ c.is_active ? ' (Active)' : '' }}
          </option>
        </select>
        <span v-else class="adv__no-configs">No configs yet</span>

        <Button
          icon="save"
          size="sm"
          :disabled="!store.currentConfig || !store.isDirty || store.isSaving"
          :loading="store.isSaving"
          @click="store.saveCurrentConfig()"
        >{{ store.isSaving ? 'Saving…' : 'Save' }}</Button>

        <Button
          variant="outline"
          icon="play"
          size="sm"
          :disabled="!store.currentConfig || store.isApplying"
          :loading="store.isApplying"
          @click="handleApply"
        >{{ store.isApplying ? 'Applying…' : 'Apply to server' }}</Button>

        <Button
          variant="secondary"
          icon="download"
          size="sm"
          @click="showImportModal = true"
        >Import from server</Button>

        <Button
          variant="danger-soft"
          icon="trash-2"
          size="sm"
          :disabled="!store.currentConfig"
          class="adv__bar-delete"
          @click="handleDeleteConfig"
        >Delete</Button>
      </div>
    </Panel>

    <!-- Loading -->
    <div v-if="store.isLoading" class="adv__loading">
      <span class="adv__spinner" />
    </div>

    <!-- Empty state -->
    <Panel v-else-if="!store.currentConfig">
      <EmptyState
        icon="door-open"
        title="No AutoDoors config selected"
        description="Create a new config, import from server, or select one from the dropdown above."
      >
        <template #action>
          <Button icon="plus" @click="showCreateModal = true">Create first config</Button>
        </template>
      </EmptyState>
    </Panel>

    <!-- Config editor -->
    <template v-else>
      <!-- Global settings -->
      <Panel title="Global settings">
        <!-- Delay sliders -->
        <div class="adv__delay-grid">
          <div class="adv__field">
            <div class="adv__field-label">Default delay (seconds)</div>
            <div class="adv__field-hint">Time before door auto-closes</div>
            <div class="adv__slider-row">
              <input
                type="range"
                :value="getConfigValue('DefaultDelay', 5)"
                min="1"
                max="30"
                step="1"
                class="adv__slider"
                style="accent-color: var(--accent)"
                @input="setConfigValue('DefaultDelay', Number(($event.target as HTMLInputElement).value))"
              />
              <input
                type="number"
                :value="getConfigValue('DefaultDelay', 5)"
                min="1"
                max="30"
                class="cc-num-input adv__delay-num"
                @input="setConfigValue('DefaultDelay', Number(($event.target as HTMLInputElement).value))"
              />
              <span class="adv__unit">sec</span>
            </div>
          </div>
          <div class="adv__field">
            <div class="adv__field-label">Minimum delay (seconds)</div>
            <div class="adv__field-hint">Lowest delay a player can set</div>
            <div class="adv__slider-row">
              <input
                type="range"
                :value="getConfigValue('MinimumDelay', 5)"
                min="1"
                max="30"
                step="1"
                class="adv__slider"
                style="accent-color: var(--accent)"
                @input="setConfigValue('MinimumDelay', Number(($event.target as HTMLInputElement).value))"
              />
              <input
                type="number"
                :value="getConfigValue('MinimumDelay', 5)"
                min="1"
                max="30"
                class="cc-num-input adv__delay-num"
                @input="setConfigValue('MinimumDelay', Number(($event.target as HTMLInputElement).value))"
              />
              <span class="adv__unit">sec</span>
            </div>
          </div>
          <div class="adv__field">
            <div class="adv__field-label">Maximum delay (seconds)</div>
            <div class="adv__field-hint">Highest delay a player can set</div>
            <div class="adv__slider-row">
              <input
                type="range"
                :value="getConfigValue('MaximumDelay', 30)"
                min="1"
                max="60"
                step="1"
                class="adv__slider"
                style="accent-color: var(--accent)"
                @input="setConfigValue('MaximumDelay', Number(($event.target as HTMLInputElement).value))"
              />
              <input
                type="number"
                :value="getConfigValue('MaximumDelay', 30)"
                min="1"
                max="60"
                class="cc-num-input adv__delay-num"
                @input="setConfigValue('MaximumDelay', Number(($event.target as HTMLInputElement).value))"
              />
              <span class="adv__unit">sec</span>
            </div>
          </div>
        </div>

        <!-- Global toggles -->
        <div class="adv__toggles adv__mt">
          <div class="adv__toggle-row">
            <div>
              <div class="adv__toggle-label">Default enabled</div>
              <div class="adv__toggle-sub">Auto-close enabled for new players by default</div>
            </div>
            <Switch
              :model-value="getBool('GlobalSettings.defaultEnabled', true)"
              @update:model-value="v => setConfigValue('GlobalSettings.defaultEnabled', v)"
            />
          </div>
          <div class="adv__toggle-row">
            <div>
              <div class="adv__toggle-label">Allow unowned doors</div>
              <div class="adv__toggle-sub">Auto-close doors that the player does not own</div>
            </div>
            <Switch
              :model-value="getBool('GlobalSettings.useUnownedDoor', false)"
              @update:model-value="v => setConfigValue('GlobalSettings.useUnownedDoor', v)"
            />
          </div>
          <div class="adv__toggle-row">
            <div>
              <div class="adv__toggle-label">Exclude door controller</div>
              <div class="adv__toggle-sub">Skip doors that have a code lock or key lock</div>
            </div>
            <Switch
              :model-value="getBool('GlobalSettings.excludeDoorController', false)"
              @update:model-value="v => setConfigValue('GlobalSettings.excludeDoorController', v)"
            />
          </div>
          <div class="adv__toggle-row">
            <div>
              <div class="adv__toggle-label">Cancel on player death</div>
              <div class="adv__toggle-sub">Cancel auto-close if the player dies</div>
            </div>
            <Switch
              :model-value="getBool('GlobalSettings.cancelOnKill', false)"
              @update:model-value="v => setConfigValue('GlobalSettings.cancelOnKill', v)"
            />
          </div>
          <div class="adv__toggle-row">
            <div>
              <div class="adv__toggle-label">Use permissions</div>
              <div class="adv__toggle-sub">Require Oxide permission to use auto-close</div>
            </div>
            <Switch
              :model-value="getBool('UsePermissions', false)"
              @update:model-value="v => setConfigValue('UsePermissions', v)"
            />
          </div>
          <div class="adv__toggle-row">
            <div>
              <div class="adv__toggle-label">Clear data on map wipe</div>
              <div class="adv__toggle-sub">Reset all player preferences on map wipe</div>
            </div>
            <Switch
              :model-value="getBool('ClearDataOnWipe', false)"
              @update:model-value="v => setConfigValue('ClearDataOnWipe', v)"
            />
          </div>
        </div>
      </Panel>

      <!-- Door types -->
      <Panel title="Door types" subtitle="Enable or disable auto-close for each door type.">
        <div class="adv__toggles">
          <div
            v-for="door in doorTypes"
            :key="door.key"
            class="adv__toggle-row"
          >
            <div>
              <div class="adv__toggle-label">{{ door.label }}</div>
              <div class="adv__toggle-sub adv__mono">{{ door.key }}</div>
            </div>
            <Switch
              :model-value="getBool(`DoorSettings.${door.key}.enabled`, true)"
              @update:model-value="v => setConfigValue(`DoorSettings.${door.key}.enabled`, v)"
            />
          </div>
        </div>
      </Panel>

      <!-- Permission group overrides -->
      <Panel title="Permission group overrides" subtitle="Override the default delay for specific Oxide permission groups.">
        <template #actions>
          <Button size="sm" icon="plus" variant="secondary" @click="addPermissionGroup">Add group</Button>
        </template>

        <div v-if="getPermissionGroups().length === 0" class="adv__perm-empty">
          No permission group overrides configured.
        </div>

        <div v-else class="adv__perm-list">
          <div
            v-for="(group, index) in getPermissionGroups()"
            :key="index"
            class="adv__perm-row"
          >
            <input
              :value="group.name"
              type="text"
              class="cc-text-input adv__perm-name"
              placeholder="Group name (e.g. vip)"
              @input="updatePermissionGroupName(group.name, ($event.target as HTMLInputElement).value)"
            />
            <input
              type="number"
              :value="group.delay"
              min="1"
              max="60"
              class="cc-num-input adv__perm-delay"
              @input="updatePermissionGroupDelay(group.name, Number(($event.target as HTMLInputElement).value))"
            />
            <span class="adv__unit">sec</span>
            <button class="adv__del-btn" title="Remove group" @click="removePermissionGroup(group.name)">
              <Icon name="trash-2" :size="15" />
            </button>
          </div>
        </div>
      </Panel>
    </template>

    <!-- Create config modal -->
    <div v-if="showCreateModal" class="adv__modal-backdrop" @click.self="showCreateModal = false">
      <div class="adv__modal">
        <h2 class="adv__modal-title">New AutoDoors config</h2>
        <div class="adv__modal-body">
          <div class="adv__field">
            <label class="adv__field-label">Config name</label>
            <input
              v-model="newConfigName"
              type="text"
              class="cc-text-input"
              placeholder="e.g. 5 second close"
              @keydown.enter="handleCreateConfig"
            />
          </div>
          <div class="adv__field">
            <label class="adv__field-label">Description (optional)</label>
            <textarea
              v-model="newConfigDesc"
              rows="2"
              class="cc-textarea"
              placeholder="What is this config for?"
            />
          </div>
        </div>
        <div class="adv__modal-footer">
          <Button variant="ghost" @click="showCreateModal = false">Cancel</Button>
          <Button :disabled="!newConfigName.trim()" @click="handleCreateConfig">Create</Button>
        </div>
      </div>
    </div>

    <!-- Import from server modal -->
    <div v-if="showImportModal" class="adv__modal-backdrop" @click.self="showImportModal = false">
      <div class="adv__modal">
        <h2 class="adv__modal-title">Import from server</h2>
        <p class="adv__modal-desc">Import the current AutoDoors config from your live server. This will create a new config profile.</p>
        <div class="adv__modal-body">
          <div class="adv__field">
            <label class="adv__field-label">Config name</label>
            <input
              v-model="importConfigName"
              type="text"
              class="cc-text-input"
              placeholder="e.g. Imported server config"
              @keydown.enter="handleImport"
            />
          </div>
        </div>
        <div class="adv__modal-footer">
          <Button variant="ghost" @click="showImportModal = false">Cancel</Button>
          <Button :disabled="!importConfigName.trim()" @click="handleImport">Import</Button>
        </div>
      </div>
    </div>
    </template>
  </div>
</template>

<style scoped>
.adv { max-width: 960px; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }

/* Page head */
.adv__head { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
.adv__head-id { display: flex; align-items: center; gap: 12px; }
.adv__head-chip {
  width: 40px; height: 40px; flex: none; border-radius: var(--radius-md);
  display: flex; align-items: center; justify-content: center;
  color: var(--accent); background: var(--accent-soft);
  box-shadow: inset 0 0 0 1px var(--accent-border);
}
.adv__title {
  font-size: var(--text-2xl); font-weight: 700; letter-spacing: -0.02em;
  color: var(--text-primary); margin-top: 3px;
}

/* Config action bar */
.adv__bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.adv__config-select {
  appearance: none; height: var(--control-h-md); padding: 0 11px;
  background: var(--surface-inset); color: var(--text-primary); border: 0;
  border-radius: var(--radius-md); box-shadow: var(--ring-default);
  font-family: var(--font-sans); font-size: var(--text-sm); cursor: pointer;
  min-width: 200px;
}
.adv__config-select:focus-visible { outline: none; box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }
.adv__no-configs { font-size: var(--text-sm); color: var(--text-muted); }
.adv__bar-delete { margin-left: auto; }

/* Loading */
.adv__loading { display: flex; align-items: center; justify-content: center; padding: 60px; }
.adv__spinner {
  width: 28px; height: 28px; border-radius: 50%; border: 2px solid var(--accent);
  border-top-color: transparent; animation: adv-spin 0.6s linear infinite;
}
@keyframes adv-spin { to { transform: rotate(360deg); } }

/* Delay grid */
.adv__delay-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
@media (max-width: 700px) { .adv__delay-grid { grid-template-columns: 1fr; } }
.adv__slider-row { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
.adv__slider { flex: 1; cursor: pointer; }
.adv__delay-num { width: 60px; flex: none; text-align: center; font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
.adv__unit { font-size: var(--text-xs); color: var(--text-tertiary); flex: none; }
.adv__mt { margin-top: 20px; }

/* Fields */
.adv__field { display: flex; flex-direction: column; gap: 4px; }
.adv__field-label { font-size: var(--text-sm); font-weight: 500; color: var(--text-primary); }
.adv__field-hint { font-size: var(--text-xs); color: var(--text-tertiary); }

/* Toggle rows */
.adv__toggles { display: flex; flex-direction: column; }
.adv__toggle-row {
  display: flex; align-items: center; justify-content: space-between;
  gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--border-subtle);
}
.adv__toggle-row:last-child { border-bottom: 0; padding-bottom: 0; }
.adv__toggle-row:first-child { padding-top: 0; }
.adv__toggle-label { font-size: var(--text-sm); font-weight: 500; color: var(--text-primary); }
.adv__toggle-sub { font-size: var(--text-xs); color: var(--text-tertiary); margin-top: 2px; }
.adv__mono { font-family: var(--font-mono); font-variant-numeric: tabular-nums; }

/* Permission groups */
.adv__perm-empty { font-size: var(--text-sm); color: var(--text-tertiary); text-align: center; padding: 20px 0; }
.adv__perm-list { display: flex; flex-direction: column; gap: 8px; }
.adv__perm-row { display: flex; align-items: center; gap: 8px; }
.adv__perm-name { flex: 1; }
.adv__perm-delay { width: 72px; flex: none; text-align: center; font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
.adv__del-btn {
  width: 34px; height: 34px; border-radius: var(--radius-sm); border: none; background: transparent;
  color: var(--danger); display: flex; align-items: center; justify-content: center;
  cursor: pointer; transition: var(--transition-colors); flex: none;
}
.adv__del-btn:hover { background: var(--status-offline-soft); }

/* Shared token inputs */
.cc-textarea {
  width: 100%; background: var(--surface-inset); color: var(--text-primary);
  border: 0; border-radius: var(--radius-md); box-shadow: var(--ring-default);
  padding: 9px 11px; font-family: var(--font-sans); font-size: var(--text-sm);
  resize: none; outline: 0; line-height: 1.5;
}
.cc-textarea:focus-visible { box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }
.cc-text-input {
  width: 100%; height: var(--control-h-md); background: var(--surface-inset); color: var(--text-primary);
  border: 0; border-radius: var(--radius-md); box-shadow: var(--ring-default);
  padding: 0 11px; font-family: var(--font-sans); font-size: var(--text-sm); outline: 0;
}
.cc-text-input:focus-visible { box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }
.cc-num-input {
  width: 100%; height: var(--control-h-md); background: var(--surface-inset); color: var(--text-primary);
  border: 0; border-radius: var(--radius-md); box-shadow: var(--ring-default);
  padding: 0 11px; font-family: var(--font-sans); font-size: var(--text-sm); outline: 0;
}
.cc-num-input:focus-visible { box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }

/* Modal */
.adv__modal-backdrop {
  position: fixed; inset: 0; background: rgba(0,0,0,0.55); z-index: 50;
  display: flex; align-items: center; justify-content: center; padding: 16px;
}
.adv__modal {
  background: var(--surface-base); border-radius: var(--radius-lg); box-shadow: var(--ring-default);
  width: 100%; max-width: 440px; padding: 24px; display: flex; flex-direction: column; gap: 16px;
}
.adv__modal-title { font-size: var(--text-lg); font-weight: 700; color: var(--text-primary); }
.adv__modal-desc { font-size: var(--text-sm); color: var(--text-tertiary); line-height: 1.5; }
.adv__modal-body { display: flex; flex-direction: column; gap: 12px; }
.adv__modal-footer { display: flex; justify-content: flex-end; gap: 8px; }
</style>
