<script setup lang="ts">
import { computed, ref } from 'vue'
import Button from '@/components/ds/core/Button.vue'
import Icon from '@/components/ds/core/Icon.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'

const props = defineProps<{
  configData: Record<string, any>
}>()

const emit = defineEmits<{
  'update:configData': [configData: Record<string, any>]
}>()

const newGroupName = ref('')

// Merge all VIP maps by key name to compute the unified group list
const groups = computed(() => {
  const homesLimits: Record<string, number> = props.configData?.Home?.VIPHomesLimits || {}
  const cooldowns: Record<string, number> = props.configData?.TPR?.VIPCooldowns || {}
  const countdowns: Record<string, number> = props.configData?.TPR?.VIPCountdowns || {}
  const dailyLimits: Record<string, number> = props.configData?.TPR?.VIPDailyLimits || {}

  const allKeys = new Set([
    ...Object.keys(homesLimits),
    ...Object.keys(cooldowns),
    ...Object.keys(countdowns),
    ...Object.keys(dailyLimits),
  ])

  return Array.from(allKeys).map(name => ({
    name,
    homesLimit: homesLimits[name] ?? 5,
    cooldown: cooldowns[name] ?? 300,
    countdown: countdowns[name] ?? 5,
    dailyLimit: dailyLimits[name] ?? 10,
  }))
})

function ensurePaths(data: Record<string, any>) {
  if (!data.Home) data.Home = {}
  if (!data.Home.VIPHomesLimits) data.Home.VIPHomesLimits = {}
  if (!data.TPR) data.TPR = {}
  if (!data.TPR.VIPCooldowns) data.TPR.VIPCooldowns = {}
  if (!data.TPR.VIPCountdowns) data.TPR.VIPCountdowns = {}
  if (!data.TPR.VIPDailyLimits) data.TPR.VIPDailyLimits = {}
}

function addGroup() {
  const name = newGroupName.value.trim()
  if (!name) return
  if (groups.value.some(g => g.name === name)) return

  const updated = { ...props.configData }
  ensurePaths(updated)
  updated.Home.VIPHomesLimits[name] = 5
  updated.TPR.VIPCooldowns[name] = 300
  updated.TPR.VIPCountdowns[name] = 5
  updated.TPR.VIPDailyLimits[name] = 10
  emit('update:configData', updated)
  newGroupName.value = ''
}

function removeGroup(name: string) {
  if (!confirm(`Remove VIP group "${name}"?`)) return
  const updated = { ...props.configData }
  ensurePaths(updated)
  delete updated.Home.VIPHomesLimits[name]
  delete updated.TPR.VIPCooldowns[name]
  delete updated.TPR.VIPCountdowns[name]
  delete updated.TPR.VIPDailyLimits[name]
  emit('update:configData', updated)
}

function updateField(groupName: string, field: string, value: number) {
  const updated = { ...props.configData }
  ensurePaths(updated)

  switch (field) {
    case 'homesLimit':
      updated.Home.VIPHomesLimits[groupName] = value
      break
    case 'cooldown':
      updated.TPR.VIPCooldowns[groupName] = value
      break
    case 'countdown':
      updated.TPR.VIPCountdowns[groupName] = value
      break
    case 'dailyLimit':
      updated.TPR.VIPDailyLimits[groupName] = value
      break
  }

  emit('update:configData', updated)
}
</script>

<template>
  <div class="pge">
    <div class="pge__head">
      <div class="pge__section-label">VIP permission groups</div>
    </div>

    <!-- Add group row -->
    <div class="pge__add-row">
      <input
        v-model="newGroupName"
        type="text"
        class="pge__name-input"
        placeholder="New group name (e.g. vip, vip+, mvp)…"
        @keydown.enter="addGroup"
      />
      <Button
        size="sm"
        icon="plus"
        :disabled="!newGroupName.trim()"
        @click="addGroup"
      >Add group</Button>
    </div>

    <!-- Empty state -->
    <EmptyState
      v-if="groups.length === 0"
      icon="users"
      title="No VIP groups defined"
      description="Add groups to configure per-permission teleport limits, cooldowns, and countdowns."
    />

    <!-- Groups table -->
    <div v-else class="pge__table-wrap">
      <table class="pge__table">
        <thead>
          <tr>
            <th class="pge__th pge__th--left">Group name</th>
            <th class="pge__th">Homes limit</th>
            <th class="pge__th">Cooldown (s)</th>
            <th class="pge__th">Countdown (s)</th>
            <th class="pge__th">Daily limit</th>
            <th class="pge__th pge__th--action" />
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="group in groups"
            :key="group.name"
            class="pge__tr"
          >
            <td class="pge__td pge__td--name">{{ group.name }}</td>
            <td class="pge__td pge__td--num">
              <input
                type="number"
                class="pge__num-input"
                :value="group.homesLimit"
                min="0"
                @input="updateField(group.name, 'homesLimit', Number(($event.target as HTMLInputElement).value))"
              />
            </td>
            <td class="pge__td pge__td--num">
              <input
                type="number"
                class="pge__num-input"
                :value="group.cooldown"
                min="0"
                @input="updateField(group.name, 'cooldown', Number(($event.target as HTMLInputElement).value))"
              />
            </td>
            <td class="pge__td pge__td--num">
              <input
                type="number"
                class="pge__num-input"
                :value="group.countdown"
                min="0"
                @input="updateField(group.name, 'countdown', Number(($event.target as HTMLInputElement).value))"
              />
            </td>
            <td class="pge__td pge__td--num">
              <input
                type="number"
                class="pge__num-input"
                :value="group.dailyLimit"
                min="0"
                @input="updateField(group.name, 'dailyLimit', Number(($event.target as HTMLInputElement).value))"
              />
            </td>
            <td class="pge__td pge__td--action">
              <button class="pge__del" type="button" @click="removeGroup(group.name)">
                <Icon name="trash-2" :size="15" />
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<style scoped>
/* ---------- Shell ---------- */
.pge { display: flex; flex-direction: column; gap: 14px; }

/* ---------- Head ---------- */
.pge__head { display: flex; align-items: center; justify-content: space-between; }
.pge__section-label {
  font-size: var(--text-xs); font-weight: 600; color: var(--text-tertiary);
  text-transform: uppercase; letter-spacing: var(--tracking-wider);
}

/* ---------- Add row ---------- */
.pge__add-row { display: flex; gap: 8px; align-items: center; }
.pge__name-input {
  flex: 1; height: var(--control-h-sm); padding: 0 10px;
  background: var(--surface-inset); border: 0; border-radius: var(--radius-sm);
  box-shadow: var(--ring-default); font-family: var(--font-sans);
  font-size: var(--text-sm); color: var(--text-primary);
}
.pge__name-input:focus { outline: none; box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }
.pge__name-input::placeholder { color: var(--text-muted); }

/* ---------- Table ---------- */
.pge__table-wrap { border-radius: var(--radius-md); overflow: hidden; box-shadow: var(--ring-default); }
.pge__table { width: 100%; border-collapse: collapse; }
.pge__th {
  padding: 9px 12px; font-size: var(--text-xs); font-weight: 600;
  color: var(--text-tertiary); text-align: center;
  background: var(--surface-raised); border-bottom: 1px solid var(--border-subtle);
}
.pge__th--left { text-align: left; }
.pge__th--action { width: 44px; }
.pge__tr { border-bottom: 1px solid var(--border-subtle); }
.pge__tr:last-child { border-bottom: 0; }
.pge__tr:hover { background: var(--surface-hover); }
.pge__td { padding: 8px 12px; font-size: var(--text-sm); color: var(--text-primary); }
.pge__td--name { font-weight: 500; font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
.pge__td--num { text-align: center; }
.pge__td--action { text-align: center; }

/* ---------- Number input (table cell) ---------- */
.pge__num-input {
  width: 80px; height: 28px; padding: 0 8px; text-align: center;
  background: var(--surface-inset); border: 0; border-radius: var(--radius-sm);
  box-shadow: var(--ring-default); font-family: var(--font-mono);
  font-size: var(--text-sm); color: var(--text-primary);
  font-variant-numeric: tabular-nums;
}
.pge__num-input:focus { outline: none; box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }

/* ---------- Delete button ---------- */
.pge__del {
  display: inline-flex; align-items: center; justify-content: center;
  width: 28px; height: 28px; border-radius: var(--radius-sm); border: none;
  background: transparent; color: var(--text-muted); cursor: pointer;
  transition: var(--transition-colors);
}
.pge__del:hover { color: var(--danger); background: var(--status-offline-soft); }
</style>
