<template>
  <div>
    <!-- Page Header -->
    <div class="mb-8">
      <h1 class="text-2xl font-bold text-white">Elutasított szolgáltatók</h1>
      <p class="text-slate-400 mt-1">Elutasított szolgáltatók visszaállítása az aktív kereshető szolgáltatók közé</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>Elutasított szolgáltatók betöltése...</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">Hiba történt a szolgáltatók betöltése közben.</p>
      <button @click="fetchRejectedProviders" class="mt-3 text-sm text-rose-300 hover:text-rose-200 underline">Újrapróbálkozás</button>
    </div>

    <template v-else>
      <!-- Rejected Queue -->
      <div class="space-y-4">
        <div
          v-for="provider in providers"
          :key="provider.id"
          class="bg-slate-800 rounded-xl border border-slate-700 p-6 hover:border-rose-500/30 transition"
        >
          <div class="flex items-start justify-between gap-4">
            <!-- Left: Provider Info -->
            <div class="flex-1 min-w-0">
              <div class="flex items-center gap-3 mb-2">
                <h3 class="text-lg font-semibold text-white truncate">{{ provider.name }}</h3>
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-rose-500/10 text-rose-400">
                  Elutasított
                </span>
                <code class="text-xs font-mono text-slate-400 bg-slate-700/50 px-2 py-0.5 rounded">{{ provider.source }}</code>
                <span v-if="provider.source_table" class="inline-flex items-center px-2 py-0.5 rounded text-xs font-mono bg-slate-700/50 text-slate-400">
                  {{ provider.source_table }}
                </span>
              </div>

              <div class="grid grid-cols-2 gap-x-8 gap-y-2 text-sm">
                <div v-if="provider.address" class="text-slate-300">
                  <span class="text-slate-500">Cím:</span> {{ provider.address }}
                </div>
                <div v-if="provider.city" class="text-slate-300">
                  <span class="text-slate-500">Város:</span> {{ provider.city }}
                </div>
                <div v-if="provider.category" class="text-slate-300">
                  <span class="text-slate-500">Kategória:</span> {{ provider.category }}
                </div>
                <div class="text-slate-300">
                  <span class="text-slate-500">Validációs pontszám:</span>
                  <span class="text-rose-400 font-medium ml-1">{{ provider.validation_score }}</span>
                </div>
                <div v-if="provider.created_at" class="text-slate-300">
                  <span class="text-slate-500">Létrehozva:</span> {{ formatDate(provider.created_at) }}
                </div>
              </div>
            </div>

            <!-- Right: Actions -->
            <div class="flex flex-col gap-2 flex-shrink-0">
              <button
                @click="openRestoreModal(provider)"
                :disabled="actionLoading === provider.id"
                class="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 disabled:bg-emerald-600/50 text-white rounded-lg text-sm font-medium transition flex items-center gap-2"
              >
                <svg v-if="actionLoading === provider.id" 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>
                <svg v-else 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="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>
                Visszaállítás
              </button>
              <NuxtLink
                :to="`/providers/${provider.id}`"
                class="px-4 py-2 bg-slate-700 hover:bg-slate-600 text-slate-300 rounded-lg text-sm font-medium transition flex items-center gap-2 text-center"
              >
                <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="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
                Részletek
              </NuxtLink>
            </div>
          </div>
        </div>

        <!-- Empty State -->
        <div v-if="providers.length === 0" class="bg-slate-800 rounded-xl border border-slate-700 p-12 text-center">
          <svg class="w-12 h-12 mx-auto text-slate-600 mb-4" 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>
          <h3 class="text-lg font-medium text-slate-400 mb-1">Nincs elutasított szolgáltató</h3>
          <p class="text-sm text-slate-500">Minden szolgáltató jóváhagyott státuszban van.</p>
        </div>
      </div>
    </template>

    <!-- Restore Modal -->
    <div v-if="showRestoreModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" @click.self="showRestoreModal = false">
      <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">Szolgáltató visszaállítása</h2>
        <p class="text-sm text-slate-400 mb-6">
          Biztosan visszaállítod a(z) <strong class="text-white">{{ restoringProvider?.name }}</strong> szolgáltatót?
          A visszaállítás után a szolgáltató újra elérhető lesz a keresőben és a listákban.
        </p>

        <form @submit.prevent="restoreProvider">
          <div class="mb-4">
            <label class="block text-sm font-medium text-slate-300 mb-1">Indoklás (opcionális)</label>
            <textarea
              v-model="restoreReason"
              rows="3"
              placeholder="Add meg a visszaállítás okát..."
              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-emerald-500/50 focus:border-emerald-500 text-sm resize-none"
            ></textarea>
          </div>

          <div class="flex justify-end gap-3">
            <button type="button" @click="showRestoreModal = false" class="px-4 py-2 text-sm text-slate-400 hover:text-white transition">Mégse</button>
            <button type="submit" :disabled="restoreLoading" class="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 disabled:bg-emerald-600/50 text-white rounded-lg text-sm font-medium transition flex items-center gap-2">
              <svg v-if="restoreLoading" 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>
              Visszaállítás
            </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 { formatDate } = useFormatter()

interface ProviderListItem {
  id: number
  name: string
  address: string | null
  city: string | null
  category: string | null
  status: string
  source: string
  source_table?: string
  validation_score: number
  added_by_user_id: number | null
  created_at: string | null
}

const loading = ref(true)
const error = ref(false)
const providers = ref<ProviderListItem[]>([])
const toast = ref('')
const actionLoading = ref<number | null>(null)
const showRestoreModal = ref(false)
const restoringProvider = ref<ProviderListItem | null>(null)
const restoreReason = ref('')
const restoreLoading = ref(false)

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)
}

async function fetchRejectedProviders() {
  loading.value = true
  error.value = false
  try {
    const data = await $fetch<ProviderListItem[]>('/api/v1/admin/providers?status=rejected&limit=100&sort_by=created_at&sort_order=desc', { headers: getHeaders() })
    providers.value = data
  } catch (e) {
    console.error('Failed to fetch rejected providers:', e)
    error.value = true
  } finally {
    loading.value = false
  }
}

function openRestoreModal(provider: ProviderListItem) {
  restoringProvider.value = provider
  restoreReason.value = ''
  showRestoreModal.value = true
}

async function restoreProvider() {
  if (!restoringProvider.value) return
  restoreLoading.value = true
  try {
    await $fetch(`/api/v1/admin/providers/${restoringProvider.value.id}/restore`, {
      method: 'POST',
      headers: getHeaders(),
      body: { reason: restoreReason.value || 'Admin restored via rejected queue' },
    })
    showToast(`"${restoringProvider.value.name}" sikeresen visszaállítva`)
    providers.value = providers.value.filter(p => p.id !== restoringProvider.value!.id)
    showRestoreModal.value = false
    restoringProvider.value = null
  } catch (e: any) {
    const detail = e?.response?._data?.detail || e?.data?.detail || 'Ismeretlen hiba'
    showToast(`Hiba: ${detail}`)
    console.error('Failed to restore provider:', e)
  } finally {
    restoreLoading.value = false
  }
}

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