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

      <!-- Rules 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.point_rules.col_id') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.point_rules.col_action_key') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.point_rules.col_points') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.point_rules.col_description') }}</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.point_rules.col_status') }}</th>
              <th class="text-right px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ t('gamification.point_rules.col_actions') }}</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-700/50">
            <tr v-for="rule in rules" :key="rule.id" class="hover:bg-slate-700/30 transition">
              <td class="px-6 py-4 text-sm text-slate-400">{{ rule.id }}</td>
              <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">{{ rule.action_key }}</code>
              </td>
              <td class="px-6 py-4">
                <span class="text-sm font-semibold" :class="rule.points >= 0 ? 'text-emerald-400' : 'text-rose-400'">
                  {{ rule.points >= 0 ? '+' : '' }}{{ rule.points }}
                </span>
              </td>
              <td class="px-6 py-4 text-sm text-slate-300 max-w-xs truncate">{{ rule.description || '—' }}</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="rule.is_active ? 'bg-emerald-500/10 text-emerald-400' : 'bg-slate-500/10 text-slate-400'">
                  {{ rule.is_active ? t('gamification.point_rules.active') : t('gamification.point_rules.inactive') }}
                </span>
              </td>
              <td class="px-6 py-4 text-right">
                <div class="flex items-center justify-end gap-2">
                  <button @click="openEditModal(rule)" class="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition" :title="t('gamification.point_rules.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(rule)" class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-rose-500/10 transition" :title="t('gamification.point_rules.delete_title')">
                    <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="rules.length === 0">
              <td colspan="6" class="px-6 py-12 text-center text-sm text-slate-500">
                {{ t('gamification.point_rules.empty') }}
              </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">{{ editingRule ? t('gamification.point_rules.edit_title') : t('gamification.point_rules.create_title') }}</h2>

        <form @submit.prevent="saveRule" class="space-y-4">
          <!-- Action Key -->
          <div>
            <label class="block text-sm font-medium text-slate-300 mb-1">{{ t('gamification.point_rules.action_key_label') }}</label>
            <input
              v-model="form.action_key"
              type="text"
              required
              maxlength="100"
              :placeholder="t('gamification.point_rules.action_key_placeholder')"
              class="w-full px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-amber-500/50 focus:border-amber-500 text-sm"
            />
          </div>

          <!-- Points -->
          <div>
            <label class="block text-sm font-medium text-slate-300 mb-1">{{ t('gamification.point_rules.points_label') }}</label>
            <input
              v-model.number="form.points"
              type="number"
              required
              min="-10000"
              max="10000"
              placeholder="0"
              class="w-full px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-amber-500/50 focus:border-amber-500 text-sm"
            />
          </div>

          <!-- Description -->
          <div>
            <label class="block text-sm font-medium text-slate-300 mb-1">{{ t('gamification.point_rules.description_label') }}</label>
            <textarea
              v-model="form.description"
              rows="3"
              :placeholder="t('gamification.point_rules.description_placeholder')"
              class="w-full px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-amber-500/50 focus:border-amber-500 text-sm resize-none"
            ></textarea>
          </div>

          <!-- Is Active -->
          <div class="flex items-center gap-3">
            <input
              v-model="form.is_active"
              type="checkbox"
              id="is_active"
              class="w-4 h-4 rounded bg-slate-700 border-slate-600 text-amber-500 focus:ring-amber-500/50"
            />
            <label for="is_active" class="text-sm text-slate-300">{{ t('gamification.point_rules.active_label') }}</label>
          </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.point_rules.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.point_rules.saving') : t('gamification.point_rules.save') }}
            </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">
        <h2 class="text-lg font-semibold text-white mb-2">{{ t('gamification.point_rules.delete_confirm_title') }}</h2>
        <p class="text-sm text-slate-400 mb-6">
          {{ t('gamification.point_rules.delete_confirm_body', { action_key: deletingRule?.action_key }) }}
        </p>
        <div class="flex justify-end gap-3">
          <button @click="showDeleteModal = false" class="px-4 py-2 text-sm text-slate-400 hover:text-white transition">{{ t('gamification.point_rules.cancel') }}</button>
          <button @click="deleteRule" :disabled="saving" class="px-4 py-2 bg-rose-600 hover:bg-rose-500 disabled:bg-rose-600/50 text-white rounded-lg text-sm font-medium transition">
            {{ saving ? t('gamification.point_rules.deleting') : t('gamification.point_rules.delete') }}
          </button>
        </div>
      </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 PointRule {
  id: number
  action_key: string
  points: number
  description: string | null
  is_active: boolean
}

const loading = ref(true)
const error = ref(false)
const rules = ref<PointRule[]>([])
const showModal = ref(false)
const showDeleteModal = ref(false)
const editingRule = ref<PointRule | null>(null)
const deletingRule = ref<PointRule | null>(null)
const saving = ref(false)
const formError = ref('')
const toast = ref('')

const form = reactive({
  action_key: '',
  points: 0,
  description: '',
  is_active: true,
})

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 resetForm() {
  form.action_key = ''
  form.points = 0
  form.description = ''
  form.is_active = true
  formError.value = ''
}

function openCreateModal() {
  editingRule.value = null
  resetForm()
  showModal.value = true
}

function openEditModal(rule: PointRule) {
  editingRule.value = rule
  form.action_key = rule.action_key
  form.points = rule.points
  form.description = rule.description || ''
  form.is_active = rule.is_active
  formError.value = ''
  showModal.value = true
}

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

function confirmDelete(rule: PointRule) {
  deletingRule.value = rule
  showDeleteModal.value = true
}

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

async function saveRule() {
  saving.value = true
  formError.value = ''
  try {
    const payload = {
      action_key: form.action_key,
      points: form.points,
      description: form.description || null,
      is_active: form.is_active,
    }

    if (editingRule.value) {
      // Update existing rule
      await $fetch(`/api/v1/admin/gamification/point-rules/${editingRule.value.id}`, {
        method: 'PUT',
        headers: getHeaders(),
        body: payload,
      })
      showToast(t('gamification.point_rules.updated'))
    } else {
      // Create new rule
      await $fetch('/api/v1/admin/gamification/point-rules', {
        method: 'POST',
        headers: getHeaders(),
        body: payload,
      })
      showToast(t('gamification.point_rules.created'))
    }
    closeModal()
    await fetchRules()
  } catch (e: any) {
    if (e?.response?.status === 409) {
      formError.value = t('gamification.point_rules.duplicate_error')
    } else {
      formError.value = t('gamification.point_rules.save_error')
    }
    console.error('Failed to save point rule:', e)
  } finally {
    saving.value = false
  }
}

async function deleteRule() {
  if (!deletingRule.value) return
  saving.value = true
  try {
    await $fetch(`/api/v1/admin/gamification/point-rules/${deletingRule.value.id}`, {
      method: 'DELETE',
      headers: getHeaders(),
    })
    showToast(t('gamification.point_rules.deleted'))
    showDeleteModal.value = false
    deletingRule.value = null
    await fetchRules()
  } catch (e) {
    console.error('Failed to delete point rule:', e)
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  fetchRules()
})
</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>
