<template>
  <div>
    <!-- Page Header -->
    <div class="mb-8">
      <h1 class="text-2xl font-bold text-white">{{ t('gamification.badges.title') }}</h1>
      <p class="text-slate-400 mt-1">{{ t('gamification.badges.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.badges.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.badges.error') }}</p>
      <button @click="fetchBadges" class="mt-3 text-sm text-rose-300 hover:text-rose-200 underline">{{ t('gamification.badges.retry') }}</button>
    </div>

    <template v-else>
      <!-- Create Button -->
      <div class="mb-6 flex justify-end">
        <button @click="openCreateModal" class="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-sm font-medium transition flex items-center gap-2">
          <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="M12 4v16m8-8H4" />
          </svg>
          {{ t('gamification.badges.create') }}
        </button>
      </div>

      <!-- Badges 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.badges.id') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.badges.name') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.badges.description') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.badges.icon') }}</th>
              <th class="text-right px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.badges.actions') }}</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-700/50">
            <tr v-for="badge in badges" :key="badge.id" class="hover:bg-slate-700/30 transition">
              <td class="px-6 py-4 text-sm text-slate-400">{{ badge.id }}</td>
              <td class="px-6 py-4">
                <span class="text-sm font-semibold text-white">{{ badge.name }}</span>
              </td>
              <td class="px-6 py-4 text-sm text-slate-300 max-w-xs truncate">{{ badge.description || '—' }}</td>
              <td class="px-6 py-4">
                <div v-if="badge.icon_url" class="flex items-center gap-2">
                  <img :src="badge.icon_url" alt="" class="w-8 h-8 rounded-full object-cover bg-slate-700" />
                  <span class="text-xs text-slate-400 truncate max-w-[120px]">{{ badge.icon_url }}</span>
                </div>
                <span v-else class="text-sm text-slate-500">—</span>
              </td>
              <td class="px-6 py-4 text-right">
                <div class="flex items-center justify-end gap-2">
                  <button @click="openEditModal(badge)" class="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition" :title="t('gamification.badges.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>
                  <button @click="confirmDelete(badge)" class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-rose-500/10 transition" :title="t('gamification.badges.delete')">
                    <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              </td>
            </tr>
            <tr v-if="badges.length === 0">
              <td colspan="5" class="px-6 py-12 text-center text-sm text-slate-500">
                {{ t('gamification.badges.no_items') }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </template>

    <!-- Create/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-6">{{ editingBadge ? t('gamification.badges.edit_title') : t('gamification.badges.create_title') }}</h2>

        <form @submit.prevent="saveBadge" class="space-y-4">
          <!-- Name -->
          <div>
            <label class="block text-sm font-medium text-slate-300 mb-1">{{ t('gamification.badges.name') }} <span class="text-rose-400">*</span></label>
            <input
              v-model="form.name"
              type="text"
              required
              maxlength="100"
              class="w-full px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-sm text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
              :placeholder="t('gamification.badges.name_placeholder')"
            />
          </div>

          <!-- Description -->
          <div>
            <label class="block text-sm font-medium text-slate-300 mb-1">{{ t('gamification.badges.description') }} <span class="text-rose-400">*</span></label>
            <textarea
              v-model="form.description"
              required
              maxlength="500"
              rows="3"
              class="w-full px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-sm text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent resize-none"
              :placeholder="t('gamification.badges.desc_placeholder')"
            ></textarea>
          </div>

          <!-- Icon URL -->
          <div>
            <label class="block text-sm font-medium text-slate-300 mb-1">{{ t('gamification.badges.icon') }}</label>
            <input
              v-model="form.icon_url"
              type="url"
              class="w-full px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-sm text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
              :placeholder="t('gamification.badges.icon_placeholder')"
            />
            <p class="text-xs text-slate-500 mt-1">{{ t('gamification.badges.icon_hint') }}</p>
          </div>

          <!-- Icon Preview -->
          <div v-if="form.icon_url" class="flex items-center gap-3 p-3 bg-slate-700/50 rounded-lg">
            <img :src="form.icon_url" alt="Preview" class="w-10 h-10 rounded-full object-cover bg-slate-600" @error="iconPreviewError = true" />
            <div class="text-xs text-slate-400">
              <span class="text-emerald-400">✔</span> {{ t('gamification.badges.icon_preview') }}
            </div>
          </div>

          <!-- Form Actions -->
          <div class="flex items-center justify-end gap-3 pt-2">
            <button type="button" @click="closeModal" class="px-4 py-2 text-sm font-medium text-slate-300 hover:text-white transition">
              {{ t('gamification.badges.cancel') }}
            </button>
            <button
              type="submit"
              :disabled="saving"
              class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:bg-indigo-600/50 disabled:cursor-not-allowed 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>
              {{ editingBadge ? t('gamification.badges.save') : t('gamification.badges.create_btn') }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div v-if="showDeleteModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" @click.self="showDeleteModal = false">
      <div class="bg-slate-800 rounded-xl border border-slate-700 p-6 w-full max-w-md mx-4 shadow-2xl">
        <div class="flex items-center gap-3 mb-4">
          <div class="p-2 rounded-full bg-rose-500/10 text-rose-400">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
          </div>
          <div>
            <h2 class="text-lg font-semibold text-white">{{ t('gamification.badges.delete_title') }}</h2>
            <p class="text-sm text-slate-400 mt-1">{{ t('gamification.badges.delete_confirm') }}</p>
          </div>
        </div>

        <div class="bg-slate-700/50 rounded-lg p-4 mb-6">
          <p class="text-sm font-medium text-white">{{ deletingBadge?.name }}</p>
          <p class="text-xs text-slate-400 mt-1">{{ deletingBadge?.description }}</p>
        </div>

        <div class="flex items-center justify-end gap-3">
          <button @click="showDeleteModal = false" class="px-4 py-2 text-sm font-medium text-slate-300 hover:text-white transition">
            {{ t('gamification.badges.cancel') }}
          </button>
          <button
            @click="deleteBadge"
            :disabled="saving"
            class="px-4 py-2 bg-rose-600 hover:bg-rose-500 disabled:bg-rose-600/50 disabled:cursor-not-allowed 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>
            {{ t('gamification.badges.delete_btn') }}
          </button>
        </div>
      </div>
    </div>

    <!-- Toast Notification -->
    <div v-if="toast" class="fixed bottom-6 right-6 z-50 px-4 py-3 rounded-lg shadow-xl text-sm font-medium transition-all duration-300"
      :class="toast.type === 'success' ? 'bg-emerald-600 text-white' : 'bg-rose-600 text-white'">
      {{ toast.message }}
    </div>
  </div>
</template>

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

const { t } = useI18n()

interface Badge {
  id: number
  name: string
  description: string
  icon_url: string | null
}

interface Toast {
  message: string
  type: 'success' | 'error'
}

const loading = ref(true)
const error = ref(false)
const saving = ref(false)
const badges = ref<Badge[]>([])
const showModal = ref(false)
const showDeleteModal = ref(false)
const editingBadge = ref<Badge | null>(null)
const deletingBadge = ref<Badge | null>(null)
const iconPreviewError = ref(false)
const toast = ref<Toast | null>(null)

const form = reactive({
  name: '',
  description: '',
  icon_url: '',
})

function getAuthHeaders() {
  const tokenCookie = useCookie('access_token')
  const token = tokenCookie.value
  return token ? { Authorization: `Bearer ${token}` } : {}
}

function showToast(message: string, type: 'success' | 'error') {
  toast.value = { message, type }
  setTimeout(() => { toast.value = null }, 4000)
}

async function fetchBadges() {
  loading.value = true
  error.value = false
  try {
    const data = await $fetch<Badge[]>('/api/v1/admin/gamification/badges', {
      headers: { ...getAuthHeaders() },
    })
    badges.value = data
  } catch (err) {
    console.error('[Badges] Failed to fetch:', err)
    error.value = true
  } finally {
    loading.value = false
  }
}

function openCreateModal() {
  editingBadge.value = null
  form.name = ''
  form.description = ''
  form.icon_url = ''
  iconPreviewError.value = false
  showModal.value = true
}

function openEditModal(badge: Badge) {
  editingBadge.value = badge
  form.name = badge.name
  form.description = badge.description
  form.icon_url = badge.icon_url || ''
  iconPreviewError.value = false
  showModal.value = true
}

function closeModal() {
  showModal.value = false
  editingBadge.value = null
}

async function saveBadge() {
  saving.value = true
  try {
    if (editingBadge.value) {
      // Update existing badge
      await $fetch(`/api/v1/admin/gamification/badges/${editingBadge.value.id}`, {
        method: 'PUT',
        headers: {
          ...getAuthHeaders(),
          'Content-Type': 'application/json',
        },
        body: {
          name: form.name,
          description: form.description,
          icon_url: form.icon_url || null,
        },
      })
      showToast(t('gamification.badges.updated'), 'success')
    } else {
      // Create new badge
      await $fetch('/api/v1/admin/gamification/badges', {
        method: 'POST',
        headers: {
          ...getAuthHeaders(),
          'Content-Type': 'application/json',
        },
        body: {
          name: form.name,
          description: form.description,
          icon_url: form.icon_url || null,
        },
      })
      showToast(t('gamification.badges.created'), 'success')
    }
    closeModal()
    await fetchBadges()
  } catch (err: any) {
    console.error('[Badges] Save failed:', err)
    const detail = err?.data?.detail || err?.message || t('gamification.badges.unknown_error')
    showToast(`${t('gamification.badges.save_error')}: ${detail}`, 'error')
  } finally {
    saving.value = false
  }
}

function confirmDelete(badge: Badge) {
  deletingBadge.value = badge
  showDeleteModal.value = true
}

async function deleteBadge() {
  if (!deletingBadge.value) return
  saving.value = true
  try {
    await $fetch(`/api/v1/admin/gamification/badges/${deletingBadge.value.id}`, {
      method: 'DELETE',
      headers: { ...getAuthHeaders() },
    })
    showToast(t('gamification.badges.deleted'), 'success')
    showDeleteModal.value = false
    deletingBadge.value = null
    await fetchBadges()
  } catch (err: any) {
    console.error('[Badges] Delete failed:', err)
    const detail = err?.data?.detail || err?.message || t('gamification.badges.unknown_error')
    showToast(`${t('gamification.badges.delete_error')}: ${detail}`, 'error')
  } finally {
    saving.value = false
  }
}

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