<template>
  <div>
    <!-- Page Header -->
    <div class="mb-8">
      <h1 class="text-2xl font-bold text-white">{{ t('gamification.params.title') }}</h1>
      <p class="text-slate-400 mt-1">{{ t('gamification.params.subtitle') }}</p>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="flex items-center justify-center py-20">
      <div class="text-slate-400 flex items-center gap-3">
        <svg class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
        </svg>
        <span>{{ t('gamification.params.loading') }}</span>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="bg-rose-500/10 border border-rose-500/30 rounded-xl p-6 mb-8">
      <p class="text-rose-400">{{ t('gamification.params.load_error') }}</p>
      <button @click="fetchParams" class="mt-3 text-sm text-rose-300 hover:text-rose-200 underline">{{ t('gamification.params.retry') }}</button>
    </div>

    <template v-else>
      <!-- Params Table -->
      <div class="bg-slate-800 rounded-xl border border-slate-700 overflow-hidden">
        <table class="w-full">
          <thead>
            <tr class="border-b border-slate-700">
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.params.col_key') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.params.col_value') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.params.col_category') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.params.col_scope') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.params.col_scope_id') }}</th>
              <th class="text-right px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.params.col_actions') }}</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-700/50">
            <tr v-for="param in params" :key="param.key" class="hover:bg-slate-700/30 transition">
              <td class="px-6 py-4">
                <code class="text-sm font-mono text-amber-300 bg-amber-500/10 px-2 py-0.5 rounded">{{ param.key }}</code>
              </td>
              <td class="px-6 py-4">
                <span class="text-sm text-slate-300 max-w-xs truncate block font-mono" :title="formatValue(param.value)">
                  {{ truncateValue(formatValue(param.value), 60) }}
                </span>
              </td>
              <td class="px-6 py-4">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-500/10 text-slate-400">
                  {{ param.category || '—' }}
                </span>
              </td>
              <td class="px-6 py-4">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="scopeBadgeClass(param.scope_level)">
                  {{ param.scope_level }}
                </span>
              </td>
              <td class="px-6 py-4 text-sm text-slate-400">{{ param.scope_id || '—' }}</td>
              <td class="px-6 py-4 text-right">
                <button @click="openEditModal(param)" class="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition" :title="t('gamification.params.edit')">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                </button>
              </td>
            </tr>
            <tr v-if="params.length === 0">
              <td colspan="6" class="px-6 py-12 text-center text-sm text-slate-500">
                {{ t('gamification.params.empty') }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </template>

    <!-- Edit Modal -->
    <div v-if="showModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" @click.self="closeModal">
      <div class="bg-slate-800 rounded-xl border border-slate-700 p-6 w-full max-w-lg mx-4 shadow-2xl">
        <h2 class="text-lg font-semibold text-white mb-2">{{ t('gamification.params.edit_title') }}</h2>
        <p class="text-sm text-slate-400 mb-6">
          <code class="text-amber-300 font-mono text-xs">{{ editingParam?.key }}</code>
        </p>

        <form @submit.prevent="saveParam" class="space-y-4">
          <!-- Value (JSON or text) -->
          <div>
            <label class="block text-sm font-medium text-slate-300 mb-1">{{ t('gamification.params.value_label') }}</label>
            <textarea
              v-model="editValue"
              rows="6"
              class="w-full px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white font-mono text-sm placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-amber-500/50 focus:border-amber-500 resize-none"
              spellcheck="false"
              :placeholder="t('gamification.params.value_placeholder')"
            ></textarea>
            <p v-if="isJsonValue" class="mt-1 text-xs text-emerald-400">{{ t('gamification.params.json_detected') }}</p>
            <p v-else class="mt-1 text-xs text-slate-500">{{ t('gamification.params.text_value') }}</p>
          </div>

          <!-- Error Message -->
          <div v-if="formError" class="bg-rose-500/10 border border-rose-500/30 rounded-lg p-3">
            <p class="text-sm text-rose-400">{{ formError }}</p>
          </div>

          <!-- Actions -->
          <div class="flex justify-end gap-3 pt-2">
            <button type="button" @click="closeModal" class="px-4 py-2 text-sm text-slate-400 hover:text-white transition">{{ t('gamification.params.cancel') }}</button>
            <button type="submit" :disabled="saving" class="px-4 py-2 bg-amber-600 hover:bg-amber-500 disabled:bg-amber-600/50 text-white rounded-lg text-sm font-medium transition flex items-center gap-2">
              <svg v-if="saving" class="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              {{ saving ? t('gamification.params.saving') : t('gamification.params.save') }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Success Toast -->
    <div v-if="toast" class="fixed bottom-6 right-6 z-50 bg-emerald-600 text-white px-4 py-3 rounded-lg shadow-lg text-sm flex items-center gap-2 animate-slide-up">
      <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      {{ toast }}
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  middleware: 'auth',
})

const { t } = useI18n()

interface SystemParam {
  key: string
  value: any
  category: string | null
  scope_level: string
  scope_id: number | null
}

const loading = ref(true)
const error = ref(false)
const saving = ref(false)
const params = ref<SystemParam[]>([])
const showModal = ref(false)
const editingParam = ref<SystemParam | null>(null)
const editValue = ref('')
const formError = ref('')
const toast = ref('')

const isJsonValue = computed(() => {
  if (!editValue.value) return false
  const trimmed = editValue.value.trim()
  return (trimmed.startsWith('{') && trimmed.endsWith('}')) ||
         (trimmed.startsWith('[') && trimmed.endsWith(']'))
})

function getHeaders(): Record<string, string> {
  const tokenCookie = useCookie('access_token')
  const token = tokenCookie.value
  return token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' } : { 'Content-Type': 'application/json' }
}

function showToast(msg: string) {
  toast.value = msg
  setTimeout(() => { toast.value = '' }, 3000)
}

function formatValue(value: any): string {
  if (value === null || value === undefined) return '—'
  if (typeof value === 'object') {
    try {
      return JSON.stringify(value)
    } catch {
      return String(value)
    }
  }
  return String(value)
}

function truncateValue(val: string, maxLen: number): string {
  if (val.length <= maxLen) return val
  return val.substring(0, maxLen) + '...'
}

function scopeBadgeClass(scope: string): string {
  switch (scope?.toLowerCase()) {
    case 'global': return 'bg-emerald-500/10 text-emerald-400'
    case 'country': return 'bg-blue-500/10 text-blue-400'
    case 'region': return 'bg-violet-500/10 text-violet-400'
    case 'user': return 'bg-amber-500/10 text-amber-400'
    default: return 'bg-slate-500/10 text-slate-400'
  }
}

function openEditModal(param: SystemParam) {
  editingParam.value = param
  editValue.value = formatValue(param.value)
  formError.value = ''
  showModal.value = true
}

function closeModal() {
  showModal.value = false
  editingParam.value = null
  editValue.value = ''
  formError.value = ''
}

async function fetchParams() {
  loading.value = true
  error.value = false
  try {
    const data = await $fetch<SystemParam[]>('/api/v1/admin/gamification/system-params', { headers: getHeaders() })
    params.value = data
  } catch (e) {
    console.error('Failed to fetch system params:', e)
    error.value = true
  } finally {
    loading.value = false
  }
}

async function saveParam() {
  if (!editingParam.value) return
  saving.value = true
  formError.value = ''

  let parsedValue: any
  try {
    // Try to parse as JSON first; if fails, use as raw string
    if (isJsonValue.value) {
      parsedValue = JSON.parse(editValue.value)
    } else {
      // Try number conversion
      const num = Number(editValue.value)
      parsedValue = isNaN(num) ? editValue.value : num
    }
  } catch (e: any) {
    formError.value = t('gamification.params.invalid_json') + ' ' + (e.message || '')
    saving.value = false
    return
  }

  try {
    await $fetch(`/api/v1/admin/gamification/system-params/${editingParam.value.key}`, {
      method: 'PUT',
      headers: getHeaders(),
      body: { value: parsedValue },
    })
    showToast(t('gamification.params.updated', { key: editingParam.value.key }))
    closeModal()
    await fetchParams()
  } catch (e: any) {
    formError.value = t('gamification.params.save_error')
    console.error('Failed to save system param:', e)
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  fetchParams()
})
</script>

<style scoped>
.animate-slide-up {
  animation: slideUp 0.3s ease-out;
}
@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(1rem);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
